vector-core 0.12.0

Core library for Vector: the single source of truth for all Vector clients, SDKs and interfaces.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
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
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
12469
12470
12471
12472
12473
12474
12475
12476
12477
12478
12479
12480
12481
12482
12483
12484
12485
12486
12487
12488
12489
12490
12491
12492
12493
12494
12495
12496
12497
12498
12499
12500
12501
12502
12503
12504
12505
12506
12507
12508
12509
12510
12511
12512
12513
12514
12515
12516
12517
12518
12519
12520
12521
12522
12523
12524
12525
12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
12541
12542
12543
12544
12545
12546
12547
12548
12549
12550
12551
12552
12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
12569
12570
12571
12572
12573
12574
12575
12576
12577
12578
12579
12580
12581
12582
12583
12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598
12599
12600
12601
12602
12603
12604
12605
12606
12607
12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
12684
12685
12686
12687
12688
12689
12690
12691
12692
12693
12694
12695
12696
12697
12698
12699
12700
12701
12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
12790
12791
12792
12793
12794
12795
12796
12797
12798
12799
12800
12801
12802
12803
12804
12805
12806
12807
12808
12809
12810
12811
12812
12813
12814
12815
12816
12817
12818
12819
12820
12821
12822
12823
12824
12825
12826
12827
12828
12829
12830
12831
12832
12833
12834
12835
12836
12837
12838
12839
12840
12841
12842
12843
12844
12845
12846
12847
12848
12849
12850
12851
12852
12853
12854
12855
12856
12857
12858
12859
12860
12861
12862
12863
12864
12865
12866
12867
12868
12869
12870
12871
12872
12873
12874
12875
12876
12877
12878
12879
12880
12881
12882
12883
12884
12885
12886
12887
12888
12889
12890
12891
12892
12893
12894
12895
12896
12897
12898
12899
12900
12901
12902
12903
12904
12905
12906
12907
12908
12909
12910
12911
12912
12913
12914
12915
12916
12917
12918
12919
12920
12921
12922
12923
12924
12925
12926
12927
12928
12929
12930
12931
12932
12933
12934
12935
12936
12937
12938
12939
12940
12941
12942
12943
12944
12945
12946
12947
12948
12949
12950
12951
12952
12953
12954
12955
12956
12957
12958
12959
12960
12961
12962
12963
12964
12965
12966
12967
12968
12969
12970
12971
12972
12973
12974
12975
12976
12977
12978
12979
12980
12981
12982
12983
12984
12985
12986
12987
12988
12989
12990
12991
12992
12993
12994
12995
12996
12997
12998
12999
13000
13001
13002
13003
13004
13005
13006
13007
13008
13009
13010
13011
13012
13013
13014
13015
13016
13017
13018
13019
13020
13021
13022
13023
13024
13025
13026
13027
13028
13029
13030
13031
13032
13033
13034
13035
13036
13037
13038
13039
13040
13041
13042
13043
13044
13045
13046
13047
13048
13049
13050
13051
13052
13053
13054
13055
13056
13057
13058
13059
13060
13061
13062
13063
13064
13065
13066
13067
13068
13069
13070
13071
13072
13073
13074
13075
13076
13077
13078
13079
13080
13081
13082
13083
13084
13085
13086
13087
13088
13089
13090
13091
13092
13093
13094
13095
13096
13097
13098
13099
13100
13101
13102
13103
13104
13105
13106
13107
13108
13109
13110
13111
13112
13113
13114
13115
13116
13117
13118
13119
13120
13121
13122
13123
13124
13125
13126
13127
13128
13129
13130
13131
13132
13133
13134
13135
13136
13137
13138
13139
13140
13141
13142
13143
13144
13145
13146
13147
13148
13149
13150
13151
13152
13153
13154
13155
13156
13157
13158
13159
13160
13161
13162
13163
13164
13165
13166
13167
13168
13169
13170
13171
13172
13173
13174
13175
13176
13177
13178
13179
13180
13181
13182
13183
13184
13185
13186
13187
13188
13189
13190
13191
13192
13193
13194
13195
13196
13197
13198
13199
13200
13201
13202
13203
13204
13205
13206
13207
13208
13209
13210
13211
13212
13213
13214
13215
13216
13217
13218
13219
13220
13221
13222
13223
13224
13225
13226
13227
13228
13229
13230
13231
13232
13233
13234
13235
13236
13237
13238
13239
13240
13241
13242
13243
13244
13245
13246
13247
13248
13249
13250
13251
13252
13253
13254
13255
13256
13257
13258
13259
13260
13261
13262
13263
13264
13265
13266
13267
13268
13269
13270
13271
13272
13273
13274
13275
13276
13277
13278
13279
13280
13281
13282
13283
13284
13285
13286
13287
13288
13289
13290
13291
13292
13293
13294
13295
13296
13297
13298
13299
13300
13301
13302
13303
13304
13305
13306
13307
13308
13309
13310
13311
13312
13313
13314
13315
13316
13317
13318
13319
13320
13321
13322
13323
13324
13325
13326
13327
13328
13329
13330
13331
13332
13333
13334
13335
13336
13337
13338
13339
13340
13341
13342
13343
13344
13345
13346
13347
13348
13349
13350
13351
13352
13353
13354
13355
13356
13357
13358
13359
13360
13361
13362
13363
13364
13365
13366
13367
13368
13369
13370
13371
13372
13373
13374
13375
13376
13377
13378
13379
13380
13381
13382
13383
13384
13385
13386
13387
13388
13389
13390
13391
13392
13393
13394
13395
13396
13397
13398
13399
13400
13401
13402
13403
13404
13405
13406
13407
13408
13409
13410
13411
13412
13413
13414
13415
13416
13417
13418
13419
13420
13421
13422
13423
13424
13425
13426
13427
13428
13429
13430
13431
13432
13433
13434
13435
13436
13437
13438
13439
13440
13441
13442
13443
13444
13445
13446
13447
13448
13449
13450
13451
13452
13453
13454
13455
13456
13457
13458
13459
13460
13461
13462
13463
13464
13465
13466
13467
13468
13469
13470
13471
13472
13473
13474
13475
13476
13477
13478
13479
13480
13481
13482
13483
13484
13485
13486
13487
13488
13489
13490
13491
13492
13493
13494
13495
13496
13497
13498
13499
13500
13501
13502
13503
13504
13505
13506
13507
13508
13509
13510
13511
13512
13513
13514
13515
13516
13517
13518
13519
13520
13521
13522
13523
13524
13525
13526
13527
13528
13529
13530
13531
13532
13533
13534
13535
13536
13537
13538
13539
13540
13541
13542
13543
13544
13545
13546
13547
13548
13549
13550
13551
13552
13553
13554
13555
13556
13557
13558
13559
13560
13561
13562
13563
13564
13565
13566
13567
13568
13569
13570
13571
13572
13573
13574
13575
13576
13577
13578
13579
13580
13581
13582
13583
13584
13585
13586
13587
13588
13589
13590
13591
13592
13593
13594
13595
13596
13597
13598
13599
13600
13601
13602
13603
13604
13605
13606
13607
13608
13609
13610
13611
13612
13613
13614
13615
13616
13617
13618
13619
13620
13621
13622
13623
13624
13625
13626
13627
13628
13629
13630
13631
13632
13633
13634
13635
13636
13637
13638
13639
13640
13641
13642
13643
13644
13645
13646
13647
13648
13649
13650
13651
13652
13653
13654
13655
13656
13657
13658
13659
13660
13661
13662
13663
13664
13665
13666
13667
13668
13669
13670
13671
13672
13673
13674
13675
13676
13677
13678
13679
13680
13681
13682
13683
13684
13685
13686
13687
13688
13689
13690
13691
13692
13693
13694
13695
13696
13697
13698
13699
13700
13701
13702
13703
13704
13705
13706
13707
13708
13709
13710
13711
13712
13713
13714
13715
13716
13717
13718
13719
13720
13721
13722
13723
13724
13725
13726
13727
13728
13729
13730
13731
13732
13733
13734
13735
13736
13737
13738
13739
13740
13741
13742
13743
13744
13745
13746
13747
13748
13749
13750
13751
13752
13753
13754
13755
13756
13757
13758
13759
13760
13761
13762
13763
13764
13765
13766
13767
13768
13769
13770
13771
13772
13773
13774
13775
13776
13777
13778
13779
13780
13781
13782
13783
13784
13785
13786
13787
13788
13789
13790
13791
13792
13793
13794
13795
13796
13797
13798
13799
13800
13801
13802
13803
13804
13805
13806
13807
13808
13809
13810
13811
13812
13813
13814
13815
13816
13817
13818
13819
13820
13821
13822
13823
13824
13825
13826
13827
13828
13829
13830
13831
13832
13833
13834
13835
13836
13837
13838
13839
13840
13841
13842
13843
13844
13845
13846
13847
13848
13849
13850
13851
13852
13853
13854
13855
13856
13857
13858
13859
13860
13861
13862
13863
13864
13865
13866
13867
13868
13869
13870
13871
13872
13873
13874
13875
13876
13877
13878
13879
13880
13881
13882
13883
13884
13885
13886
13887
13888
13889
13890
13891
13892
13893
13894
13895
13896
13897
13898
13899
13900
13901
13902
13903
13904
13905
13906
13907
13908
13909
13910
13911
13912
13913
13914
13915
13916
13917
13918
13919
13920
13921
13922
13923
13924
13925
13926
13927
13928
13929
13930
13931
13932
13933
13934
13935
13936
13937
13938
13939
13940
13941
13942
13943
13944
13945
13946
13947
13948
13949
13950
13951
13952
13953
13954
13955
13956
13957
13958
13959
13960
13961
13962
13963
13964
13965
13966
13967
13968
13969
13970
13971
13972
13973
13974
13975
13976
13977
13978
13979
13980
13981
13982
13983
13984
13985
13986
13987
13988
13989
13990
13991
13992
13993
13994
13995
13996
13997
13998
13999
14000
14001
14002
14003
14004
14005
14006
14007
14008
14009
14010
14011
14012
14013
14014
14015
14016
14017
14018
14019
14020
14021
14022
14023
14024
14025
14026
14027
14028
14029
14030
14031
14032
14033
14034
14035
14036
14037
14038
14039
14040
14041
14042
14043
14044
14045
14046
14047
14048
14049
14050
14051
14052
14053
14054
14055
14056
14057
14058
14059
14060
14061
14062
14063
14064
14065
14066
14067
14068
14069
14070
14071
14072
14073
14074
14075
14076
14077
14078
14079
14080
14081
14082
14083
14084
14085
14086
14087
14088
14089
14090
14091
14092
14093
14094
14095
14096
14097
14098
14099
14100
14101
14102
14103
14104
14105
14106
14107
14108
14109
14110
14111
14112
14113
14114
14115
14116
14117
14118
14119
14120
14121
14122
14123
14124
14125
14126
14127
14128
14129
14130
14131
14132
14133
14134
14135
14136
14137
14138
14139
14140
14141
14142
14143
14144
14145
14146
14147
14148
14149
14150
14151
14152
14153
14154
14155
14156
14157
14158
14159
14160
14161
14162
14163
14164
14165
14166
14167
14168
14169
14170
14171
14172
14173
14174
14175
14176
14177
14178
14179
14180
14181
14182
14183
14184
14185
14186
14187
14188
14189
14190
14191
14192
14193
14194
14195
14196
14197
14198
14199
14200
14201
14202
14203
14204
14205
14206
14207
14208
14209
14210
14211
14212
14213
14214
14215
14216
14217
14218
14219
14220
14221
14222
14223
14224
14225
14226
14227
14228
14229
14230
14231
14232
14233
14234
14235
14236
14237
14238
14239
14240
14241
14242
14243
14244
14245
14246
14247
14248
14249
14250
14251
14252
14253
14254
14255
14256
14257
14258
14259
14260
14261
14262
14263
14264
14265
14266
14267
14268
14269
14270
14271
14272
14273
14274
14275
14276
14277
14278
14279
14280
14281
14282
14283
14284
14285
14286
14287
14288
14289
14290
14291
14292
14293
14294
14295
14296
14297
14298
14299
14300
14301
14302
14303
14304
14305
14306
14307
14308
14309
14310
14311
14312
14313
14314
14315
14316
14317
14318
14319
14320
14321
14322
14323
14324
14325
14326
14327
14328
14329
14330
14331
14332
14333
14334
14335
14336
14337
14338
14339
14340
14341
14342
14343
14344
14345
14346
14347
14348
14349
14350
14351
14352
14353
14354
14355
14356
14357
14358
14359
14360
14361
14362
14363
14364
14365
14366
14367
14368
14369
14370
14371
14372
14373
14374
14375
14376
14377
14378
14379
14380
14381
14382
14383
14384
14385
14386
14387
14388
14389
14390
14391
14392
14393
14394
14395
14396
14397
14398
14399
14400
14401
14402
14403
14404
14405
14406
14407
14408
14409
14410
14411
14412
14413
14414
14415
14416
14417
14418
14419
14420
14421
14422
14423
14424
14425
14426
14427
14428
14429
14430
14431
14432
14433
14434
14435
14436
14437
14438
14439
14440
14441
14442
14443
14444
14445
14446
14447
14448
14449
14450
14451
14452
14453
14454
14455
14456
14457
14458
14459
14460
14461
14462
14463
14464
14465
14466
14467
14468
14469
14470
14471
14472
14473
14474
14475
14476
14477
14478
14479
14480
14481
14482
14483
14484
14485
14486
14487
14488
14489
14490
14491
14492
14493
14494
14495
14496
14497
14498
14499
14500
14501
14502
14503
14504
14505
14506
14507
14508
14509
14510
14511
14512
14513
14514
14515
14516
14517
14518
14519
14520
14521
14522
14523
14524
14525
14526
14527
14528
14529
14530
14531
14532
14533
14534
14535
14536
14537
14538
14539
14540
14541
14542
14543
14544
14545
14546
14547
14548
14549
14550
14551
14552
14553
14554
14555
14556
14557
14558
14559
14560
14561
14562
14563
14564
14565
14566
14567
14568
14569
14570
14571
14572
14573
14574
14575
14576
14577
14578
14579
14580
14581
14582
14583
14584
14585
14586
14587
14588
14589
14590
14591
14592
14593
14594
14595
14596
14597
14598
14599
14600
14601
14602
14603
14604
14605
14606
14607
14608
14609
14610
14611
14612
14613
14614
14615
14616
14617
14618
14619
14620
14621
14622
14623
14624
14625
14626
14627
14628
14629
14630
14631
14632
14633
14634
14635
14636
14637
14638
14639
14640
14641
14642
14643
14644
14645
14646
14647
14648
14649
14650
14651
14652
14653
14654
14655
14656
14657
14658
14659
14660
14661
14662
14663
14664
14665
14666
14667
14668
14669
14670
14671
14672
14673
14674
14675
14676
14677
14678
14679
14680
14681
14682
14683
14684
14685
14686
14687
14688
14689
14690
14691
14692
14693
14694
14695
14696
14697
14698
14699
14700
14701
14702
14703
14704
14705
14706
14707
14708
14709
14710
14711
14712
14713
14714
14715
14716
14717
14718
14719
14720
14721
14722
14723
14724
14725
14726
14727
14728
14729
14730
14731
14732
14733
14734
14735
14736
14737
14738
14739
14740
14741
14742
14743
14744
14745
14746
14747
14748
14749
14750
14751
14752
14753
14754
14755
14756
14757
14758
14759
14760
14761
14762
14763
14764
14765
14766
14767
14768
14769
14770
14771
14772
14773
14774
14775
14776
14777
14778
14779
14780
14781
14782
14783
14784
14785
14786
14787
14788
14789
14790
14791
14792
14793
14794
14795
14796
14797
14798
14799
14800
14801
14802
14803
14804
14805
14806
14807
14808
14809
14810
14811
14812
14813
14814
14815
14816
14817
14818
14819
14820
14821
14822
14823
14824
14825
14826
14827
14828
14829
14830
14831
14832
14833
14834
14835
14836
14837
14838
14839
14840
14841
14842
14843
14844
14845
14846
14847
14848
14849
14850
14851
14852
14853
14854
14855
14856
14857
14858
14859
14860
14861
14862
14863
14864
14865
14866
14867
14868
14869
14870
14871
14872
14873
14874
14875
14876
14877
14878
14879
14880
14881
14882
14883
14884
14885
14886
14887
14888
14889
14890
14891
14892
14893
14894
14895
14896
14897
14898
14899
14900
14901
14902
14903
14904
14905
14906
14907
14908
14909
14910
14911
14912
14913
14914
14915
14916
14917
14918
14919
14920
14921
14922
14923
14924
14925
14926
14927
14928
14929
14930
14931
14932
14933
14934
14935
14936
14937
14938
14939
14940
14941
14942
14943
14944
14945
14946
14947
14948
14949
14950
14951
14952
14953
14954
14955
14956
14957
14958
14959
14960
14961
14962
14963
14964
14965
14966
14967
14968
14969
14970
14971
14972
14973
14974
14975
14976
14977
14978
14979
14980
14981
14982
14983
14984
14985
14986
14987
14988
14989
14990
14991
14992
14993
14994
14995
14996
14997
14998
14999
15000
15001
15002
15003
15004
15005
15006
15007
15008
15009
15010
15011
15012
15013
15014
15015
15016
15017
15018
15019
15020
15021
15022
15023
15024
15025
15026
15027
15028
15029
15030
15031
15032
15033
15034
15035
15036
15037
15038
15039
15040
15041
15042
15043
15044
15045
15046
15047
15048
15049
15050
15051
15052
15053
15054
15055
15056
15057
15058
15059
15060
15061
15062
15063
15064
15065
15066
15067
15068
15069
15070
15071
15072
15073
15074
15075
15076
15077
15078
15079
15080
15081
15082
15083
15084
15085
15086
15087
15088
15089
15090
15091
15092
15093
15094
15095
15096
15097
15098
15099
15100
15101
15102
15103
15104
15105
15106
15107
15108
15109
15110
15111
15112
15113
15114
15115
15116
15117
15118
15119
15120
15121
15122
15123
15124
15125
15126
15127
15128
15129
15130
15131
15132
15133
15134
15135
15136
15137
15138
15139
15140
15141
15142
15143
15144
15145
15146
15147
15148
15149
15150
15151
15152
15153
15154
15155
15156
15157
15158
15159
15160
15161
15162
15163
15164
15165
15166
15167
15168
15169
15170
15171
15172
15173
15174
15175
15176
15177
15178
15179
15180
15181
15182
15183
15184
15185
15186
15187
15188
15189
15190
15191
15192
15193
15194
15195
15196
15197
15198
15199
15200
15201
15202
15203
15204
15205
15206
15207
15208
15209
15210
15211
15212
15213
15214
15215
15216
15217
15218
15219
15220
15221
15222
15223
15224
15225
15226
15227
15228
15229
15230
15231
15232
15233
15234
15235
15236
15237
15238
15239
15240
15241
15242
15243
15244
15245
15246
15247
15248
15249
15250
15251
15252
15253
15254
15255
15256
15257
15258
15259
15260
15261
15262
15263
15264
15265
15266
15267
15268
15269
15270
15271
15272
15273
15274
15275
15276
15277
15278
15279
15280
15281
15282
15283
15284
15285
15286
15287
15288
15289
15290
15291
15292
15293
15294
15295
15296
15297
15298
15299
15300
15301
15302
15303
15304
15305
15306
15307
15308
15309
15310
15311
15312
15313
15314
15315
15316
15317
15318
15319
15320
15321
15322
15323
15324
15325
15326
15327
15328
15329
15330
15331
15332
15333
15334
15335
15336
15337
15338
15339
15340
15341
15342
15343
15344
15345
15346
15347
15348
15349
15350
15351
15352
15353
15354
15355
15356
15357
15358
15359
15360
15361
15362
15363
15364
15365
15366
15367
15368
15369
15370
15371
15372
15373
15374
15375
15376
15377
15378
15379
15380
15381
15382
15383
15384
15385
15386
15387
15388
15389
15390
15391
15392
15393
15394
15395
15396
15397
15398
15399
15400
15401
15402
15403
15404
15405
15406
15407
15408
15409
15410
15411
15412
15413
15414
15415
15416
15417
15418
15419
15420
15421
15422
15423
15424
15425
15426
15427
15428
15429
15430
15431
15432
15433
15434
15435
15436
15437
15438
15439
15440
15441
15442
15443
15444
15445
15446
15447
15448
15449
15450
15451
15452
15453
15454
15455
15456
15457
15458
15459
15460
15461
15462
15463
15464
15465
15466
15467
15468
15469
15470
15471
15472
15473
15474
15475
15476
15477
15478
15479
15480
15481
15482
15483
15484
15485
15486
15487
15488
15489
15490
15491
15492
15493
15494
15495
15496
15497
15498
15499
15500
15501
15502
15503
15504
15505
15506
15507
15508
15509
15510
15511
15512
15513
15514
15515
15516
15517
15518
15519
15520
15521
15522
15523
15524
15525
15526
15527
15528
15529
15530
15531
15532
15533
15534
15535
15536
15537
15538
15539
15540
15541
15542
15543
15544
15545
15546
15547
15548
15549
15550
15551
15552
15553
15554
15555
15556
15557
15558
15559
15560
15561
15562
15563
15564
15565
15566
15567
15568
15569
15570
15571
15572
15573
15574
15575
15576
15577
15578
15579
15580
15581
15582
15583
15584
15585
15586
15587
15588
15589
15590
15591
15592
15593
15594
15595
15596
15597
15598
15599
15600
15601
15602
15603
15604
15605
15606
15607
15608
15609
15610
15611
15612
15613
15614
15615
15616
15617
15618
15619
15620
15621
15622
15623
15624
15625
15626
15627
15628
15629
15630
15631
15632
15633
15634
15635
15636
15637
15638
15639
15640
15641
15642
15643
15644
15645
15646
15647
15648
15649
15650
15651
15652
15653
15654
15655
15656
15657
15658
15659
15660
15661
15662
15663
15664
15665
15666
15667
15668
15669
15670
15671
15672
15673
15674
15675
15676
15677
15678
15679
15680
15681
15682
15683
15684
15685
15686
15687
15688
15689
15690
15691
15692
15693
15694
15695
15696
15697
15698
15699
15700
15701
15702
15703
15704
15705
15706
15707
15708
15709
15710
15711
15712
15713
15714
15715
15716
15717
15718
15719
15720
15721
15722
15723
15724
15725
15726
15727
15728
15729
15730
15731
15732
15733
15734
15735
15736
15737
15738
15739
15740
15741
15742
15743
15744
15745
15746
15747
15748
15749
15750
15751
15752
15753
15754
15755
15756
15757
15758
15759
15760
15761
15762
15763
15764
15765
15766
15767
15768
15769
15770
15771
15772
15773
15774
15775
15776
15777
15778
15779
15780
15781
15782
15783
15784
15785
15786
15787
15788
15789
15790
15791
15792
15793
15794
15795
15796
15797
15798
15799
15800
15801
15802
15803
15804
15805
15806
15807
15808
15809
15810
15811
15812
15813
15814
15815
15816
15817
15818
15819
15820
15821
15822
15823
15824
15825
15826
15827
15828
15829
15830
15831
15832
15833
15834
15835
15836
15837
15838
15839
15840
15841
15842
15843
15844
15845
15846
15847
15848
15849
15850
15851
15852
15853
15854
15855
15856
15857
15858
15859
15860
15861
15862
15863
15864
15865
15866
15867
15868
15869
15870
15871
15872
15873
15874
15875
15876
15877
15878
15879
15880
15881
15882
15883
15884
15885
15886
15887
15888
15889
15890
15891
15892
15893
15894
15895
15896
15897
15898
15899
15900
15901
15902
15903
15904
15905
15906
15907
15908
15909
15910
15911
15912
15913
15914
15915
15916
15917
15918
15919
15920
15921
15922
15923
15924
15925
15926
15927
15928
15929
15930
15931
15932
15933
15934
15935
15936
15937
15938
15939
15940
15941
15942
15943
15944
15945
15946
15947
15948
15949
15950
15951
15952
15953
15954
15955
15956
15957
15958
15959
15960
15961
15962
15963
15964
15965
15966
15967
15968
15969
15970
15971
15972
15973
15974
15975
15976
15977
15978
15979
15980
15981
15982
15983
15984
15985
15986
15987
15988
15989
15990
15991
15992
15993
15994
15995
15996
15997
15998
15999
16000
16001
16002
16003
16004
16005
16006
16007
16008
16009
16010
16011
16012
16013
16014
16015
16016
16017
16018
16019
16020
16021
16022
16023
16024
16025
16026
16027
16028
16029
16030
16031
16032
16033
16034
16035
16036
16037
16038
16039
16040
16041
16042
16043
16044
16045
16046
16047
16048
16049
16050
16051
16052
16053
16054
16055
16056
16057
16058
16059
16060
16061
16062
16063
16064
16065
16066
16067
16068
16069
16070
16071
16072
16073
16074
16075
16076
16077
16078
16079
16080
16081
16082
16083
16084
16085
16086
16087
16088
16089
16090
16091
16092
16093
16094
16095
16096
16097
16098
16099
16100
16101
16102
16103
16104
16105
16106
16107
16108
16109
16110
16111
16112
16113
16114
16115
16116
16117
16118
16119
16120
16121
16122
16123
16124
16125
16126
16127
16128
16129
16130
16131
16132
16133
16134
16135
16136
16137
16138
16139
16140
16141
16142
16143
16144
16145
16146
16147
16148
16149
16150
16151
16152
16153
16154
16155
16156
16157
16158
16159
16160
16161
16162
16163
16164
16165
16166
16167
16168
16169
16170
16171
16172
16173
16174
16175
16176
16177
16178
16179
16180
16181
16182
16183
16184
16185
16186
16187
16188
16189
16190
16191
16192
16193
16194
16195
16196
16197
16198
16199
16200
16201
16202
16203
16204
16205
16206
16207
16208
16209
16210
16211
16212
16213
16214
16215
16216
16217
16218
16219
16220
16221
16222
16223
16224
16225
16226
16227
16228
16229
16230
16231
16232
16233
16234
16235
16236
16237
16238
16239
16240
16241
16242
16243
16244
16245
16246
16247
16248
16249
16250
16251
16252
16253
16254
16255
16256
16257
16258
16259
16260
16261
16262
16263
16264
16265
16266
16267
16268
16269
16270
16271
16272
16273
16274
16275
16276
16277
16278
16279
16280
16281
16282
16283
16284
16285
16286
16287
16288
16289
16290
16291
16292
16293
16294
16295
16296
16297
16298
16299
16300
16301
16302
16303
16304
16305
16306
16307
16308
16309
16310
16311
16312
16313
16314
16315
16316
16317
16318
16319
16320
16321
16322
16323
16324
16325
16326
16327
16328
16329
16330
16331
16332
16333
16334
16335
16336
16337
16338
16339
16340
16341
16342
16343
16344
16345
16346
16347
16348
16349
16350
16351
16352
16353
16354
16355
16356
16357
16358
16359
16360
16361
16362
16363
16364
16365
16366
16367
16368
16369
16370
16371
16372
16373
16374
16375
16376
16377
16378
16379
16380
16381
16382
16383
16384
16385
16386
16387
16388
16389
16390
16391
16392
16393
16394
16395
16396
16397
16398
16399
16400
16401
16402
16403
16404
16405
16406
16407
16408
16409
16410
16411
16412
16413
16414
16415
16416
16417
16418
16419
16420
16421
16422
16423
16424
16425
16426
16427
16428
16429
16430
16431
16432
16433
16434
16435
16436
16437
16438
16439
16440
16441
16442
16443
16444
16445
16446
16447
16448
16449
16450
16451
16452
16453
16454
16455
16456
16457
16458
16459
16460
16461
16462
16463
16464
16465
16466
16467
16468
16469
16470
16471
16472
16473
16474
16475
16476
16477
16478
16479
16480
16481
16482
16483
16484
16485
16486
16487
16488
16489
16490
16491
16492
16493
16494
16495
16496
16497
16498
16499
16500
16501
16502
16503
16504
16505
16506
16507
16508
16509
16510
16511
16512
16513
16514
16515
16516
16517
16518
16519
16520
16521
16522
16523
16524
16525
16526
16527
16528
16529
16530
16531
16532
16533
16534
16535
16536
16537
16538
16539
16540
16541
16542
16543
16544
16545
16546
16547
16548
16549
16550
16551
16552
16553
16554
16555
16556
16557
16558
16559
16560
16561
16562
16563
16564
16565
16566
16567
16568
16569
16570
16571
16572
16573
16574
16575
16576
16577
16578
16579
16580
16581
16582
16583
16584
16585
16586
16587
16588
16589
16590
16591
16592
16593
16594
16595
16596
16597
16598
16599
16600
16601
16602
16603
16604
16605
16606
16607
16608
16609
16610
16611
16612
16613
16614
16615
16616
16617
16618
16619
16620
16621
16622
16623
16624
16625
16626
16627
16628
16629
16630
16631
16632
16633
16634
16635
16636
16637
16638
16639
16640
16641
16642
16643
16644
16645
16646
16647
16648
16649
16650
16651
16652
16653
16654
16655
16656
16657
16658
16659
16660
16661
16662
16663
16664
16665
16666
16667
16668
16669
16670
16671
16672
16673
16674
16675
16676
16677
16678
16679
16680
16681
16682
16683
16684
16685
16686
16687
16688
16689
16690
16691
16692
16693
16694
16695
16696
16697
16698
16699
16700
16701
16702
16703
16704
16705
16706
16707
16708
16709
16710
16711
16712
16713
16714
16715
16716
16717
16718
16719
16720
16721
16722
16723
16724
16725
16726
16727
16728
16729
16730
16731
16732
16733
16734
16735
16736
16737
16738
16739
16740
16741
16742
16743
16744
16745
16746
16747
16748
16749
16750
16751
16752
16753
16754
16755
16756
16757
16758
16759
16760
16761
16762
16763
16764
16765
16766
16767
16768
16769
16770
16771
16772
16773
16774
16775
16776
16777
16778
16779
16780
16781
16782
16783
16784
16785
16786
16787
16788
16789
16790
16791
16792
16793
16794
16795
16796
16797
16798
16799
16800
16801
16802
16803
16804
16805
16806
16807
16808
16809
16810
16811
16812
16813
16814
16815
16816
16817
16818
16819
16820
16821
16822
16823
16824
16825
16826
16827
16828
16829
16830
16831
16832
16833
16834
16835
16836
16837
16838
16839
16840
16841
16842
16843
16844
16845
16846
16847
16848
16849
16850
16851
16852
16853
16854
16855
16856
16857
16858
16859
16860
16861
16862
16863
16864
16865
16866
16867
16868
16869
16870
16871
16872
16873
16874
16875
16876
16877
16878
16879
16880
16881
16882
16883
16884
16885
16886
16887
16888
16889
16890
16891
16892
16893
16894
16895
16896
16897
16898
16899
16900
16901
16902
16903
16904
16905
16906
16907
16908
16909
16910
16911
16912
16913
16914
16915
16916
16917
16918
16919
16920
16921
16922
16923
16924
16925
16926
16927
16928
16929
16930
16931
16932
16933
16934
16935
16936
16937
16938
16939
16940
16941
16942
16943
16944
16945
16946
16947
16948
16949
16950
16951
16952
16953
16954
16955
16956
16957
16958
16959
16960
16961
16962
16963
16964
16965
16966
16967
16968
16969
16970
16971
16972
16973
16974
16975
16976
16977
16978
16979
16980
16981
16982
16983
16984
16985
16986
16987
16988
16989
16990
16991
16992
16993
16994
16995
16996
16997
16998
16999
17000
17001
17002
17003
17004
17005
17006
17007
17008
17009
17010
17011
17012
17013
17014
17015
17016
17017
17018
17019
17020
17021
17022
17023
17024
17025
17026
17027
17028
17029
17030
17031
17032
17033
17034
17035
17036
17037
17038
17039
17040
17041
17042
17043
17044
17045
17046
17047
17048
17049
17050
17051
17052
17053
17054
17055
17056
17057
17058
17059
17060
17061
17062
17063
17064
17065
17066
17067
17068
17069
17070
17071
17072
17073
17074
17075
17076
17077
17078
17079
17080
17081
17082
17083
17084
17085
17086
17087
17088
17089
17090
17091
17092
17093
17094
17095
17096
17097
17098
17099
17100
17101
17102
17103
17104
17105
17106
17107
17108
17109
17110
17111
17112
17113
17114
17115
17116
17117
17118
17119
17120
17121
17122
17123
17124
17125
17126
17127
17128
17129
17130
17131
17132
17133
17134
17135
17136
17137
17138
17139
17140
17141
17142
17143
17144
17145
17146
17147
17148
17149
17150
17151
17152
17153
17154
17155
17156
17157
17158
17159
17160
17161
17162
17163
17164
17165
17166
17167
17168
17169
17170
17171
17172
17173
17174
17175
17176
17177
17178
17179
17180
17181
17182
17183
17184
17185
17186
17187
17188
17189
17190
17191
17192
17193
17194
17195
17196
17197
17198
17199
17200
17201
17202
17203
17204
17205
17206
17207
17208
17209
17210
17211
17212
17213
17214
17215
17216
17217
17218
17219
17220
17221
17222
17223
17224
17225
17226
17227
17228
17229
17230
17231
17232
17233
17234
17235
17236
17237
17238
17239
17240
17241
17242
17243
17244
17245
17246
17247
17248
17249
17250
17251
17252
17253
17254
17255
17256
17257
17258
17259
17260
17261
17262
17263
17264
17265
17266
17267
17268
17269
17270
17271
17272
17273
17274
17275
17276
17277
17278
17279
17280
17281
17282
17283
17284
17285
17286
17287
17288
17289
17290
17291
17292
17293
17294
17295
17296
17297
17298
17299
17300
17301
17302
17303
17304
17305
17306
17307
17308
17309
17310
17311
17312
17313
17314
17315
17316
17317
17318
17319
17320
17321
17322
17323
17324
17325
17326
17327
17328
17329
17330
17331
17332
17333
17334
17335
17336
17337
17338
17339
17340
17341
17342
17343
17344
17345
17346
17347
17348
17349
17350
17351
17352
17353
17354
17355
17356
17357
17358
17359
17360
17361
17362
17363
17364
17365
17366
17367
17368
17369
17370
17371
17372
17373
17374
17375
17376
17377
17378
17379
17380
17381
17382
17383
17384
17385
17386
17387
17388
17389
17390
17391
17392
17393
17394
17395
17396
17397
17398
17399
17400
17401
17402
17403
17404
17405
17406
17407
17408
17409
17410
17411
17412
17413
17414
17415
17416
17417
17418
17419
17420
17421
17422
17423
17424
17425
17426
17427
17428
17429
17430
17431
17432
17433
17434
17435
17436
17437
17438
17439
17440
17441
17442
17443
17444
17445
17446
17447
17448
17449
17450
17451
17452
17453
17454
17455
17456
17457
17458
17459
17460
17461
17462
17463
17464
17465
17466
17467
17468
17469
17470
17471
17472
17473
17474
17475
17476
17477
17478
17479
17480
17481
17482
17483
17484
17485
17486
17487
17488
17489
17490
17491
17492
17493
17494
17495
17496
17497
17498
17499
17500
17501
17502
17503
17504
17505
17506
17507
17508
17509
17510
17511
17512
17513
17514
17515
17516
17517
17518
17519
17520
17521
17522
17523
17524
17525
17526
17527
17528
17529
17530
17531
17532
17533
17534
17535
17536
17537
17538
17539
17540
17541
17542
17543
17544
17545
17546
17547
17548
17549
17550
17551
17552
17553
17554
17555
17556
17557
17558
17559
17560
17561
17562
17563
17564
17565
17566
17567
17568
17569
17570
17571
17572
17573
17574
17575
17576
17577
17578
17579
17580
17581
17582
17583
17584
17585
17586
17587
17588
17589
17590
17591
17592
17593
17594
17595
17596
17597
17598
17599
17600
17601
17602
17603
17604
17605
17606
17607
17608
17609
17610
17611
17612
17613
17614
17615
17616
17617
17618
17619
17620
17621
17622
17623
17624
17625
17626
17627
17628
17629
17630
17631
17632
17633
17634
17635
17636
17637
17638
17639
17640
17641
17642
17643
17644
17645
17646
17647
17648
17649
17650
17651
17652
17653
17654
17655
17656
17657
17658
17659
17660
17661
17662
17663
17664
17665
17666
17667
17668
17669
17670
17671
17672
17673
17674
17675
17676
17677
17678
17679
17680
17681
17682
17683
17684
17685
17686
17687
17688
17689
17690
17691
17692
17693
17694
17695
17696
17697
17698
17699
17700
17701
17702
17703
17704
17705
17706
17707
17708
17709
17710
17711
17712
17713
17714
17715
17716
17717
17718
17719
17720
17721
17722
17723
17724
17725
17726
17727
17728
17729
17730
17731
17732
17733
17734
17735
17736
17737
17738
17739
17740
17741
17742
17743
17744
17745
17746
17747
17748
17749
17750
17751
17752
17753
17754
17755
17756
17757
17758
17759
17760
17761
17762
17763
17764
17765
17766
17767
17768
17769
17770
17771
17772
17773
17774
17775
17776
17777
17778
17779
17780
17781
17782
17783
17784
17785
17786
17787
17788
17789
17790
17791
17792
17793
17794
17795
17796
17797
17798
17799
17800
17801
17802
17803
17804
17805
17806
17807
17808
17809
17810
17811
17812
17813
17814
17815
17816
17817
17818
17819
17820
17821
17822
17823
17824
17825
17826
17827
17828
17829
17830
17831
17832
17833
17834
17835
17836
17837
17838
17839
17840
17841
17842
17843
17844
17845
17846
17847
17848
17849
17850
17851
17852
17853
17854
17855
17856
17857
17858
17859
17860
17861
17862
17863
17864
17865
17866
17867
17868
17869
17870
17871
17872
17873
17874
17875
17876
17877
17878
17879
17880
17881
17882
17883
17884
17885
17886
17887
17888
17889
17890
17891
17892
17893
17894
17895
17896
17897
17898
17899
17900
17901
17902
17903
17904
17905
17906
17907
17908
17909
17910
17911
17912
17913
17914
17915
17916
17917
17918
17919
17920
17921
17922
17923
17924
17925
17926
17927
17928
17929
17930
17931
17932
17933
17934
17935
17936
17937
17938
17939
17940
17941
17942
17943
17944
17945
17946
17947
17948
17949
17950
17951
17952
17953
17954
17955
17956
17957
17958
17959
17960
17961
17962
17963
17964
17965
17966
17967
17968
17969
17970
17971
17972
17973
17974
17975
17976
17977
17978
17979
17980
17981
17982
17983
17984
17985
17986
17987
17988
17989
17990
17991
17992
17993
17994
17995
17996
17997
17998
17999
18000
18001
18002
18003
18004
18005
18006
18007
18008
18009
18010
18011
18012
18013
18014
18015
18016
18017
18018
18019
18020
18021
18022
18023
18024
18025
18026
18027
18028
18029
18030
18031
18032
18033
18034
18035
18036
18037
18038
18039
18040
18041
18042
18043
18044
18045
18046
18047
18048
18049
18050
18051
18052
18053
18054
18055
18056
18057
18058
18059
18060
18061
18062
18063
18064
18065
18066
18067
18068
18069
18070
18071
18072
18073
18074
18075
18076
18077
18078
18079
18080
18081
18082
18083
18084
18085
18086
18087
18088
18089
18090
18091
18092
18093
18094
18095
18096
18097
18098
18099
18100
18101
18102
18103
18104
18105
18106
18107
18108
18109
18110
18111
18112
18113
18114
18115
18116
18117
18118
18119
18120
18121
18122
18123
18124
18125
18126
18127
18128
18129
18130
18131
18132
18133
18134
18135
18136
18137
18138
18139
18140
18141
18142
18143
18144
18145
18146
18147
18148
18149
18150
18151
18152
18153
18154
18155
18156
18157
18158
18159
18160
18161
18162
18163
18164
18165
18166
18167
18168
18169
18170
18171
18172
18173
18174
18175
18176
18177
18178
18179
18180
18181
18182
18183
18184
18185
18186
18187
18188
18189
18190
18191
18192
18193
18194
18195
18196
18197
18198
18199
18200
18201
18202
18203
18204
18205
18206
18207
18208
18209
18210
18211
18212
18213
18214
18215
18216
18217
18218
18219
18220
18221
18222
18223
18224
18225
18226
18227
18228
18229
18230
18231
18232
18233
18234
18235
18236
18237
18238
18239
18240
18241
18242
18243
18244
18245
18246
18247
18248
18249
18250
18251
18252
18253
18254
18255
18256
18257
18258
18259
18260
18261
18262
18263
18264
18265
18266
18267
18268
18269
18270
18271
18272
18273
18274
18275
18276
18277
18278
18279
18280
18281
18282
18283
18284
18285
18286
18287
18288
18289
18290
18291
18292
18293
18294
18295
18296
18297
18298
18299
18300
18301
18302
18303
18304
18305
18306
18307
18308
18309
18310
18311
18312
18313
18314
18315
18316
18317
18318
18319
18320
18321
18322
18323
18324
18325
18326
18327
18328
18329
18330
18331
18332
18333
18334
18335
18336
18337
18338
18339
18340
18341
18342
18343
18344
18345
18346
18347
18348
18349
18350
18351
18352
18353
18354
18355
18356
18357
18358
18359
18360
18361
18362
18363
18364
18365
18366
18367
18368
18369
18370
18371
18372
18373
18374
18375
18376
18377
18378
18379
18380
18381
18382
18383
18384
18385
18386
18387
18388
18389
18390
18391
18392
18393
18394
18395
18396
18397
18398
18399
18400
18401
18402
18403
18404
18405
18406
18407
18408
18409
18410
18411
18412
18413
18414
18415
18416
18417
18418
18419
18420
18421
18422
18423
18424
18425
18426
18427
18428
18429
18430
18431
18432
18433
18434
18435
18436
18437
18438
18439
18440
18441
18442
18443
18444
18445
18446
18447
18448
18449
18450
18451
18452
18453
18454
18455
18456
18457
18458
18459
18460
18461
18462
18463
18464
18465
18466
18467
18468
18469
18470
18471
18472
18473
18474
18475
18476
18477
18478
18479
18480
18481
18482
18483
18484
18485
18486
18487
18488
18489
18490
18491
18492
18493
18494
18495
18496
18497
18498
18499
18500
18501
18502
18503
18504
18505
18506
18507
18508
18509
18510
18511
18512
18513
18514
18515
18516
18517
18518
18519
18520
18521
18522
18523
18524
18525
18526
18527
18528
18529
18530
18531
18532
18533
18534
18535
18536
18537
18538
18539
18540
18541
18542
18543
18544
18545
18546
18547
18548
18549
18550
18551
18552
18553
18554
18555
18556
18557
18558
18559
18560
18561
18562
18563
18564
18565
18566
18567
18568
18569
18570
18571
18572
18573
18574
18575
18576
18577
18578
18579
18580
18581
18582
18583
18584
18585
18586
18587
18588
18589
18590
18591
18592
18593
18594
18595
18596
18597
18598
18599
18600
18601
18602
18603
18604
18605
18606
18607
18608
18609
18610
18611
18612
18613
18614
18615
18616
18617
18618
18619
18620
18621
18622
18623
18624
18625
18626
18627
18628
18629
18630
18631
18632
18633
18634
18635
18636
18637
18638
18639
18640
18641
18642
18643
18644
18645
18646
18647
18648
18649
18650
18651
18652
18653
18654
18655
18656
18657
18658
18659
18660
18661
18662
18663
18664
18665
18666
18667
18668
18669
18670
18671
18672
18673
18674
18675
18676
18677
18678
18679
18680
18681
18682
18683
18684
18685
18686
18687
18688
18689
18690
18691
18692
18693
18694
18695
18696
18697
18698
18699
18700
18701
18702
18703
18704
18705
18706
18707
18708
18709
18710
18711
18712
18713
18714
18715
18716
18717
18718
18719
18720
18721
18722
18723
18724
18725
18726
18727
18728
18729
18730
18731
18732
18733
18734
18735
18736
18737
18738
18739
18740
18741
18742
18743
18744
18745
18746
18747
18748
18749
18750
18751
18752
18753
18754
18755
18756
18757
18758
18759
18760
18761
18762
18763
18764
18765
18766
18767
18768
18769
18770
18771
18772
18773
18774
18775
18776
18777
18778
18779
18780
18781
18782
18783
18784
18785
18786
18787
18788
18789
18790
18791
18792
18793
18794
18795
18796
18797
18798
18799
18800
18801
18802
18803
18804
18805
18806
18807
18808
18809
18810
18811
18812
18813
18814
18815
18816
18817
18818
18819
18820
18821
18822
18823
18824
18825
18826
18827
18828
18829
18830
18831
18832
18833
18834
18835
18836
18837
18838
18839
18840
18841
18842
18843
18844
18845
18846
18847
18848
18849
18850
18851
18852
18853
18854
18855
18856
18857
18858
18859
18860
18861
18862
18863
18864
18865
18866
18867
18868
18869
18870
18871
18872
18873
18874
18875
18876
18877
18878
18879
18880
18881
18882
18883
18884
18885
18886
18887
18888
18889
18890
18891
18892
18893
18894
18895
18896
18897
18898
18899
18900
18901
18902
18903
18904
18905
18906
18907
18908
18909
18910
18911
18912
18913
18914
18915
18916
18917
18918
18919
18920
18921
18922
18923
18924
18925
18926
18927
18928
18929
18930
18931
18932
18933
18934
18935
18936
18937
18938
18939
18940
18941
18942
18943
18944
18945
18946
18947
18948
18949
18950
18951
18952
18953
18954
18955
18956
18957
18958
18959
18960
18961
18962
18963
18964
18965
18966
18967
18968
18969
18970
18971
18972
18973
18974
18975
18976
18977
18978
18979
18980
18981
18982
18983
18984
18985
18986
18987
18988
18989
18990
18991
18992
18993
18994
18995
18996
18997
18998
18999
19000
19001
19002
19003
19004
19005
19006
19007
19008
19009
19010
19011
19012
19013
19014
19015
19016
19017
19018
19019
19020
19021
19022
19023
19024
19025
19026
19027
19028
19029
19030
19031
19032
19033
19034
19035
19036
19037
19038
19039
19040
19041
19042
19043
19044
19045
19046
19047
19048
19049
19050
19051
19052
19053
19054
19055
19056
19057
19058
19059
19060
19061
19062
19063
19064
19065
19066
19067
19068
19069
19070
19071
19072
19073
19074
19075
19076
19077
19078
19079
19080
19081
19082
19083
19084
19085
19086
19087
19088
19089
19090
19091
19092
19093
19094
19095
19096
19097
19098
19099
19100
19101
19102
19103
19104
19105
19106
19107
19108
19109
19110
19111
19112
19113
19114
19115
19116
19117
19118
19119
19120
19121
19122
19123
19124
19125
19126
19127
19128
19129
19130
19131
19132
19133
19134
19135
19136
19137
19138
19139
19140
19141
19142
19143
19144
19145
19146
19147
19148
19149
19150
19151
19152
19153
19154
19155
19156
19157
19158
19159
19160
19161
19162
19163
19164
19165
19166
19167
19168
19169
19170
19171
19172
19173
19174
19175
19176
19177
19178
19179
19180
19181
19182
19183
19184
19185
19186
19187
19188
19189
19190
19191
19192
19193
19194
19195
19196
19197
19198
19199
19200
19201
19202
19203
19204
19205
19206
19207
19208
19209
19210
19211
19212
19213
19214
19215
19216
19217
19218
19219
19220
19221
19222
19223
19224
19225
19226
19227
19228
19229
19230
19231
19232
19233
19234
19235
19236
19237
19238
19239
19240
19241
19242
19243
19244
19245
19246
19247
19248
19249
19250
19251
19252
19253
19254
19255
19256
19257
19258
19259
19260
19261
19262
19263
19264
19265
19266
19267
19268
19269
19270
19271
19272
19273
19274
19275
19276
19277
19278
19279
19280
19281
19282
19283
19284
19285
19286
19287
19288
19289
19290
19291
19292
19293
19294
19295
19296
19297
19298
19299
19300
19301
19302
19303
19304
19305
19306
19307
19308
19309
19310
19311
19312
19313
19314
19315
19316
19317
19318
19319
19320
19321
19322
19323
19324
19325
19326
19327
19328
19329
19330
19331
19332
19333
19334
19335
19336
19337
19338
19339
19340
19341
19342
19343
19344
19345
19346
19347
19348
19349
19350
19351
19352
19353
19354
19355
19356
19357
19358
19359
19360
19361
19362
19363
19364
19365
19366
19367
19368
19369
19370
19371
19372
19373
19374
19375
19376
19377
19378
19379
19380
19381
19382
19383
19384
19385
19386
19387
19388
19389
19390
19391
19392
19393
19394
19395
19396
19397
19398
19399
19400
19401
19402
19403
19404
19405
19406
19407
19408
19409
19410
19411
19412
19413
19414
19415
19416
19417
19418
19419
19420
19421
19422
19423
19424
19425
19426
19427
19428
19429
19430
19431
19432
19433
19434
19435
19436
19437
19438
19439
19440
19441
19442
19443
19444
19445
19446
19447
19448
19449
19450
19451
19452
19453
19454
19455
19456
19457
19458
19459
19460
19461
19462
19463
19464
19465
19466
19467
19468
19469
19470
19471
19472
19473
19474
19475
19476
19477
19478
19479
19480
19481
19482
19483
19484
19485
19486
19487
19488
19489
19490
19491
19492
19493
19494
19495
19496
19497
19498
19499
19500
19501
19502
19503
19504
19505
19506
19507
19508
19509
19510
19511
19512
19513
19514
19515
19516
19517
19518
19519
19520
19521
19522
19523
19524
19525
19526
19527
19528
19529
19530
19531
19532
19533
19534
19535
19536
19537
19538
19539
19540
19541
19542
19543
19544
19545
19546
19547
19548
19549
19550
19551
19552
19553
19554
19555
19556
19557
19558
19559
19560
19561
19562
19563
19564
19565
19566
19567
19568
19569
19570
19571
19572
19573
19574
19575
19576
19577
19578
19579
19580
19581
19582
19583
19584
19585
19586
19587
19588
19589
19590
19591
19592
19593
19594
19595
19596
19597
19598
19599
19600
19601
19602
19603
19604
19605
19606
19607
19608
19609
19610
19611
19612
19613
19614
19615
19616
19617
19618
19619
19620
19621
19622
19623
19624
19625
19626
19627
19628
19629
19630
19631
19632
19633
19634
19635
19636
19637
19638
19639
19640
19641
19642
19643
19644
19645
19646
19647
19648
19649
19650
19651
19652
19653
19654
19655
19656
19657
19658
19659
19660
19661
19662
19663
19664
19665
19666
19667
19668
19669
19670
19671
19672
19673
19674
19675
19676
19677
19678
19679
19680
19681
19682
19683
19684
19685
19686
19687
19688
19689
19690
19691
19692
19693
19694
19695
19696
19697
19698
19699
19700
19701
19702
19703
19704
19705
19706
19707
19708
19709
19710
19711
19712
19713
19714
19715
19716
19717
19718
19719
19720
19721
19722
19723
19724
19725
19726
19727
19728
19729
19730
19731
19732
19733
19734
19735
19736
19737
19738
19739
19740
19741
19742
19743
19744
19745
19746
19747
19748
19749
19750
19751
19752
19753
19754
19755
19756
19757
19758
19759
19760
19761
19762
19763
19764
19765
19766
19767
19768
19769
19770
19771
19772
19773
19774
19775
19776
19777
19778
19779
19780
19781
19782
19783
19784
19785
19786
19787
19788
19789
19790
19791
19792
19793
19794
19795
19796
19797
19798
19799
19800
19801
19802
19803
19804
19805
19806
19807
19808
19809
19810
19811
19812
19813
19814
19815
19816
19817
19818
19819
19820
19821
19822
19823
19824
19825
19826
19827
19828
19829
19830
19831
19832
19833
19834
19835
19836
19837
19838
19839
19840
19841
19842
19843
19844
19845
19846
19847
19848
19849
19850
19851
19852
19853
19854
19855
19856
19857
19858
19859
19860
19861
19862
19863
19864
19865
19866
19867
19868
19869
19870
19871
19872
19873
19874
19875
19876
19877
19878
19879
19880
19881
19882
19883
19884
19885
19886
19887
19888
19889
19890
19891
19892
19893
19894
19895
19896
19897
19898
19899
19900
19901
19902
19903
19904
19905
19906
19907
19908
19909
19910
19911
19912
19913
19914
19915
19916
19917
19918
19919
19920
19921
19922
19923
19924
19925
19926
19927
19928
19929
19930
19931
19932
19933
19934
19935
19936
19937
19938
19939
19940
19941
19942
19943
19944
19945
19946
19947
19948
19949
19950
19951
19952
19953
19954
19955
19956
19957
19958
19959
19960
19961
19962
19963
19964
19965
19966
19967
19968
19969
19970
19971
19972
19973
19974
19975
19976
19977
19978
19979
19980
19981
19982
19983
19984
19985
19986
19987
19988
19989
19990
19991
19992
19993
19994
19995
19996
19997
19998
19999
20000
20001
20002
20003
20004
20005
20006
20007
20008
20009
20010
20011
20012
20013
20014
20015
20016
20017
20018
20019
20020
20021
20022
20023
20024
20025
20026
20027
20028
20029
20030
20031
20032
20033
20034
20035
20036
20037
20038
20039
20040
20041
20042
20043
20044
20045
20046
20047
20048
20049
20050
20051
20052
20053
20054
20055
20056
20057
20058
20059
20060
20061
20062
20063
20064
20065
20066
20067
20068
20069
20070
20071
20072
20073
20074
20075
20076
20077
20078
20079
20080
20081
20082
20083
20084
20085
20086
20087
20088
20089
20090
20091
20092
20093
20094
20095
20096
20097
20098
20099
20100
20101
20102
20103
20104
20105
20106
20107
20108
20109
20110
20111
20112
20113
20114
20115
20116
20117
20118
20119
20120
20121
20122
20123
20124
20125
20126
20127
20128
20129
20130
20131
20132
20133
20134
20135
20136
20137
20138
20139
20140
20141
20142
20143
20144
20145
20146
20147
20148
20149
20150
20151
20152
20153
20154
20155
20156
20157
20158
20159
20160
20161
20162
20163
20164
20165
20166
20167
20168
20169
20170
20171
20172
20173
20174
20175
20176
20177
20178
20179
20180
20181
20182
20183
20184
20185
20186
20187
20188
20189
20190
20191
20192
20193
20194
20195
20196
20197
20198
20199
20200
20201
20202
20203
20204
20205
20206
20207
20208
20209
20210
20211
20212
20213
20214
20215
20216
20217
20218
20219
20220
20221
20222
20223
20224
20225
20226
20227
20228
20229
20230
20231
20232
20233
20234
20235
20236
20237
20238
20239
20240
20241
20242
20243
20244
20245
20246
20247
20248
20249
20250
20251
20252
20253
20254
20255
20256
20257
20258
20259
20260
20261
20262
20263
20264
20265
20266
20267
20268
20269
20270
20271
20272
20273
20274
20275
20276
20277
20278
20279
20280
20281
20282
20283
20284
20285
20286
20287
20288
20289
20290
20291
20292
20293
20294
20295
20296
20297
20298
20299
20300
20301
20302
20303
20304
20305
20306
20307
20308
20309
20310
20311
20312
20313
20314
20315
20316
20317
20318
20319
20320
20321
20322
20323
20324
20325
20326
20327
20328
20329
20330
20331
20332
20333
20334
20335
20336
20337
20338
20339
20340
20341
20342
20343
20344
20345
20346
20347
20348
20349
20350
20351
20352
20353
20354
20355
20356
20357
20358
20359
20360
20361
20362
20363
20364
20365
20366
20367
20368
20369
20370
20371
20372
20373
20374
20375
20376
20377
20378
20379
20380
20381
20382
20383
20384
20385
20386
20387
20388
20389
20390
20391
20392
20393
20394
20395
20396
20397
20398
20399
20400
20401
20402
20403
20404
20405
20406
20407
20408
20409
20410
20411
20412
20413
20414
20415
20416
20417
20418
20419
20420
20421
20422
20423
20424
20425
20426
20427
20428
20429
20430
20431
20432
20433
20434
20435
20436
20437
20438
20439
20440
20441
20442
20443
20444
20445
20446
20447
20448
20449
20450
20451
20452
20453
20454
20455
20456
20457
20458
20459
20460
20461
20462
20463
20464
20465
20466
20467
20468
20469
20470
20471
20472
20473
20474
20475
20476
20477
20478
20479
20480
20481
20482
20483
20484
20485
20486
20487
20488
20489
20490
20491
20492
20493
20494
20495
20496
20497
20498
20499
20500
20501
20502
20503
20504
20505
20506
20507
20508
20509
20510
20511
20512
20513
20514
20515
20516
20517
20518
20519
20520
20521
20522
20523
20524
20525
20526
20527
20528
20529
20530
20531
20532
20533
20534
20535
20536
20537
20538
20539
20540
20541
20542
20543
20544
20545
20546
20547
20548
20549
20550
20551
20552
20553
20554
20555
20556
20557
20558
20559
20560
20561
20562
20563
20564
20565
20566
20567
20568
20569
20570
20571
20572
20573
20574
20575
20576
20577
20578
20579
20580
20581
20582
20583
20584
20585
20586
20587
20588
20589
20590
20591
20592
20593
20594
20595
20596
20597
20598
20599
20600
20601
20602
20603
20604
20605
20606
20607
20608
20609
20610
20611
20612
20613
20614
20615
20616
20617
20618
20619
20620
20621
20622
20623
20624
20625
20626
20627
20628
20629
20630
20631
20632
20633
20634
20635
20636
20637
20638
20639
20640
20641
20642
20643
20644
20645
20646
20647
20648
20649
20650
20651
20652
20653
20654
20655
20656
20657
20658
20659
20660
20661
20662
20663
20664
20665
20666
20667
20668
20669
20670
20671
20672
20673
20674
20675
20676
20677
20678
20679
20680
20681
20682
20683
20684
20685
20686
20687
20688
20689
20690
20691
20692
20693
20694
20695
20696
20697
20698
20699
20700
20701
20702
20703
20704
20705
20706
20707
20708
20709
20710
20711
20712
20713
20714
20715
20716
20717
20718
20719
20720
20721
20722
20723
20724
20725
20726
20727
20728
20729
20730
20731
20732
20733
20734
20735
20736
20737
20738
20739
20740
20741
20742
20743
20744
20745
20746
20747
20748
20749
20750
20751
20752
20753
20754
20755
20756
20757
20758
20759
20760
20761
20762
20763
20764
20765
20766
20767
20768
20769
20770
20771
20772
20773
20774
20775
20776
20777
20778
20779
20780
20781
20782
20783
20784
20785
20786
20787
20788
20789
20790
20791
20792
20793
20794
20795
20796
20797
20798
20799
20800
20801
20802
20803
20804
20805
20806
20807
20808
20809
20810
20811
20812
20813
20814
20815
20816
20817
20818
20819
20820
20821
20822
20823
20824
20825
20826
20827
20828
20829
20830
20831
20832
20833
20834
20835
20836
20837
20838
20839
20840
20841
20842
20843
20844
20845
20846
20847
20848
20849
20850
20851
20852
20853
20854
20855
20856
20857
20858
20859
20860
20861
20862
20863
20864
20865
20866
20867
20868
20869
20870
20871
20872
20873
20874
20875
20876
20877
20878
20879
20880
20881
20882
20883
20884
20885
20886
20887
20888
20889
20890
20891
20892
20893
20894
20895
20896
20897
20898
20899
20900
20901
20902
20903
20904
20905
20906
20907
20908
20909
20910
20911
20912
20913
20914
20915
20916
20917
20918
20919
20920
20921
20922
20923
20924
20925
20926
20927
20928
20929
20930
20931
20932
20933
20934
20935
20936
20937
20938
20939
20940
20941
20942
20943
20944
20945
20946
20947
20948
20949
20950
20951
20952
20953
20954
20955
20956
20957
20958
20959
20960
20961
20962
20963
20964
20965
20966
20967
20968
20969
20970
20971
20972
20973
20974
20975
20976
20977
20978
20979
20980
20981
20982
20983
20984
20985
20986
20987
20988
20989
20990
20991
20992
20993
20994
20995
20996
20997
20998
20999
21000
21001
21002
21003
21004
21005
21006
21007
21008
21009
21010
21011
21012
21013
21014
21015
21016
21017
21018
21019
21020
21021
21022
21023
21024
21025
21026
21027
21028
21029
21030
21031
21032
21033
21034
21035
21036
21037
21038
21039
21040
21041
21042
21043
21044
21045
21046
21047
21048
21049
21050
21051
21052
21053
21054
21055
21056
21057
21058
21059
21060
21061
21062
21063
21064
21065
21066
21067
21068
21069
21070
21071
21072
21073
21074
21075
21076
21077
21078
21079
21080
21081
21082
21083
21084
21085
21086
21087
21088
21089
21090
21091
21092
21093
21094
21095
21096
21097
21098
21099
21100
21101
21102
21103
21104
21105
21106
21107
21108
21109
21110
21111
21112
21113
21114
21115
21116
21117
21118
21119
21120
21121
21122
21123
21124
21125
21126
21127
21128
21129
21130
21131
21132
21133
21134
21135
21136
21137
21138
21139
21140
21141
21142
21143
21144
21145
21146
21147
21148
21149
21150
21151
21152
21153
21154
21155
21156
21157
21158
21159
21160
21161
21162
21163
21164
21165
21166
21167
21168
21169
21170
21171
21172
21173
21174
21175
21176
21177
21178
21179
21180
21181
21182
21183
21184
21185
21186
21187
21188
21189
21190
21191
21192
21193
21194
21195
21196
21197
21198
21199
21200
21201
21202
21203
21204
21205
21206
21207
21208
21209
21210
21211
21212
21213
21214
21215
21216
21217
21218
21219
21220
21221
21222
21223
21224
21225
21226
21227
21228
21229
21230
21231
21232
21233
21234
21235
21236
21237
21238
21239
21240
21241
21242
21243
21244
21245
21246
21247
21248
21249
21250
21251
21252
21253
21254
21255
21256
21257
21258
21259
21260
21261
21262
21263
21264
21265
21266
21267
21268
21269
21270
21271
21272
21273
21274
21275
21276
21277
21278
21279
21280
21281
21282
21283
21284
21285
21286
21287
21288
21289
21290
21291
21292
21293
21294
21295
21296
21297
21298
21299
21300
21301
21302
21303
21304
21305
21306
21307
21308
21309
21310
21311
21312
21313
21314
21315
21316
21317
21318
21319
21320
21321
21322
21323
21324
21325
21326
21327
21328
21329
21330
21331
21332
21333
21334
21335
21336
21337
21338
21339
21340
21341
21342
21343
21344
21345
21346
21347
21348
21349
21350
21351
21352
21353
21354
21355
21356
21357
21358
21359
21360
21361
21362
21363
21364
21365
21366
21367
21368
21369
21370
21371
21372
21373
21374
21375
21376
21377
21378
21379
21380
21381
21382
21383
21384
21385
21386
21387
21388
21389
21390
21391
21392
21393
21394
21395
21396
21397
21398
21399
21400
21401
21402
21403
21404
21405
21406
21407
21408
21409
21410
21411
21412
21413
21414
21415
21416
21417
21418
21419
21420
21421
21422
21423
21424
21425
21426
21427
21428
21429
21430
21431
21432
21433
21434
21435
21436
21437
21438
21439
21440
21441
21442
21443
21444
21445
21446
21447
21448
21449
21450
21451
21452
21453
21454
21455
21456
21457
21458
21459
21460
21461
21462
21463
21464
21465
21466
21467
21468
21469
21470
21471
21472
21473
21474
21475
21476
21477
21478
21479
21480
21481
21482
21483
21484
21485
21486
21487
21488
21489
21490
21491
21492
21493
21494
21495
21496
21497
21498
21499
21500
21501
21502
21503
21504
21505
21506
21507
21508
21509
21510
21511
21512
21513
21514
21515
21516
21517
21518
21519
21520
21521
21522
21523
21524
21525
21526
21527
21528
21529
21530
21531
21532
21533
21534
21535
21536
21537
21538
21539
21540
21541
21542
21543
21544
21545
21546
21547
21548
21549
21550
21551
21552
21553
21554
21555
21556
21557
21558
21559
21560
21561
21562
21563
21564
21565
21566
21567
21568
21569
21570
21571
21572
21573
21574
21575
21576
21577
21578
21579
21580
21581
21582
21583
21584
21585
21586
21587
21588
21589
21590
21591
21592
21593
21594
21595
21596
21597
21598
21599
21600
21601
21602
21603
21604
21605
21606
21607
21608
21609
21610
21611
21612
21613
21614
21615
21616
21617
21618
21619
21620
21621
21622
21623
21624
21625
21626
21627
21628
21629
21630
21631
21632
21633
21634
21635
21636
21637
21638
21639
21640
21641
21642
21643
21644
21645
21646
21647
21648
21649
21650
21651
21652
21653
21654
21655
21656
21657
21658
21659
21660
21661
21662
21663
21664
21665
21666
21667
21668
21669
21670
21671
21672
21673
21674
21675
21676
21677
21678
21679
21680
21681
21682
21683
21684
21685
21686
21687
21688
21689
21690
21691
21692
21693
21694
21695
21696
21697
21698
21699
21700
21701
21702
21703
21704
21705
21706
21707
21708
21709
21710
21711
21712
21713
21714
21715
21716
21717
21718
21719
21720
21721
21722
21723
21724
21725
21726
21727
21728
21729
21730
21731
21732
21733
21734
21735
21736
21737
21738
21739
21740
21741
21742
21743
21744
21745
21746
21747
21748
21749
21750
21751
21752
21753
21754
21755
21756
21757
21758
21759
21760
21761
21762
21763
21764
21765
21766
21767
21768
21769
21770
21771
21772
21773
21774
21775
21776
21777
21778
21779
21780
21781
21782
21783
21784
21785
21786
21787
21788
21789
21790
21791
21792
21793
21794
21795
21796
21797
21798
21799
21800
21801
21802
21803
21804
21805
21806
21807
21808
21809
21810
21811
21812
21813
21814
21815
21816
21817
21818
21819
21820
21821
21822
21823
21824
21825
21826
21827
21828
21829
21830
21831
21832
21833
21834
21835
21836
21837
21838
21839
21840
21841
21842
21843
21844
21845
21846
21847
21848
21849
21850
21851
21852
21853
21854
21855
21856
21857
21858
21859
21860
21861
21862
21863
21864
21865
21866
21867
21868
21869
21870
21871
21872
21873
21874
21875
21876
21877
21878
21879
21880
21881
21882
21883
21884
21885
21886
21887
21888
21889
21890
21891
21892
21893
21894
21895
21896
21897
21898
21899
21900
21901
21902
21903
21904
21905
21906
21907
21908
21909
21910
21911
21912
21913
21914
21915
21916
21917
21918
21919
21920
21921
21922
21923
21924
21925
21926
21927
21928
21929
21930
21931
21932
21933
21934
21935
21936
21937
21938
21939
21940
21941
21942
21943
21944
21945
21946
21947
21948
21949
21950
21951
21952
21953
21954
21955
21956
21957
21958
21959
21960
21961
21962
21963
21964
21965
21966
21967
21968
21969
21970
21971
21972
21973
21974
21975
21976
21977
21978
21979
21980
21981
21982
21983
21984
21985
21986
21987
21988
21989
21990
21991
21992
21993
21994
21995
21996
21997
21998
21999
22000
22001
22002
22003
22004
22005
22006
22007
22008
22009
22010
22011
22012
22013
22014
22015
22016
22017
22018
22019
22020
22021
22022
22023
22024
22025
22026
22027
22028
22029
22030
22031
22032
22033
22034
22035
22036
22037
22038
22039
22040
22041
22042
22043
22044
22045
22046
22047
22048
22049
22050
22051
22052
22053
22054
22055
22056
22057
22058
22059
22060
22061
22062
22063
22064
22065
22066
22067
22068
22069
22070
22071
22072
22073
22074
22075
22076
22077
22078
22079
22080
22081
22082
22083
22084
22085
22086
22087
22088
22089
22090
22091
22092
22093
22094
22095
22096
22097
22098
22099
22100
22101
22102
22103
22104
22105
22106
22107
22108
22109
22110
22111
22112
22113
22114
22115
22116
22117
22118
22119
22120
22121
22122
22123
22124
22125
22126
22127
22128
22129
22130
22131
22132
22133
22134
22135
22136
22137
22138
22139
22140
22141
22142
22143
22144
22145
22146
22147
22148
22149
22150
22151
22152
22153
22154
22155
22156
22157
22158
22159
22160
22161
22162
22163
22164
22165
22166
22167
22168
22169
22170
22171
22172
22173
22174
22175
22176
22177
22178
22179
22180
22181
22182
22183
22184
22185
22186
22187
22188
22189
22190
22191
22192
22193
22194
22195
22196
22197
22198
22199
22200
22201
22202
22203
22204
22205
22206
22207
22208
22209
22210
22211
22212
22213
22214
22215
22216
22217
22218
22219
22220
22221
22222
22223
22224
22225
22226
22227
22228
22229
22230
22231
22232
22233
22234
22235
22236
22237
22238
22239
22240
22241
22242
22243
22244
22245
22246
22247
22248
22249
22250
22251
22252
22253
22254
22255
22256
22257
22258
22259
22260
22261
22262
22263
22264
22265
22266
22267
22268
22269
22270
22271
22272
22273
22274
22275
22276
22277
22278
22279
22280
22281
22282
22283
22284
22285
22286
22287
22288
22289
22290
22291
22292
22293
22294
22295
22296
22297
22298
22299
22300
22301
22302
22303
22304
22305
22306
22307
22308
22309
22310
22311
22312
22313
22314
22315
22316
22317
22318
22319
22320
22321
22322
22323
22324
22325
22326
22327
22328
22329
22330
22331
22332
22333
22334
22335
22336
22337
22338
22339
22340
22341
22342
22343
22344
22345
22346
22347
22348
22349
22350
22351
22352
22353
22354
22355
22356
22357
22358
22359
22360
22361
22362
22363
22364
22365
22366
22367
22368
22369
22370
22371
22372
22373
22374
22375
22376
22377
22378
22379
22380
22381
22382
22383
22384
22385
22386
22387
22388
22389
22390
22391
22392
22393
22394
22395
22396
22397
22398
22399
22400
22401
22402
22403
22404
22405
22406
22407
22408
22409
22410
22411
22412
22413
22414
22415
22416
22417
22418
22419
22420
22421
22422
22423
22424
22425
22426
22427
22428
22429
22430
22431
22432
22433
22434
22435
22436
22437
22438
22439
22440
22441
22442
22443
22444
22445
22446
22447
22448
22449
22450
22451
22452
22453
22454
22455
22456
22457
22458
22459
22460
22461
22462
22463
22464
22465
22466
22467
22468
22469
22470
22471
22472
22473
22474
22475
22476
22477
22478
22479
22480
22481
22482
22483
22484
22485
22486
22487
22488
22489
22490
22491
22492
22493
22494
22495
22496
22497
22498
22499
22500
22501
22502
22503
22504
22505
22506
22507
22508
22509
22510
22511
22512
22513
22514
22515
22516
22517
22518
22519
22520
22521
22522
22523
22524
22525
22526
22527
22528
22529
22530
22531
22532
22533
22534
22535
22536
22537
22538
22539
22540
22541
22542
22543
22544
22545
22546
22547
22548
22549
22550
22551
22552
22553
22554
22555
22556
22557
22558
22559
22560
22561
22562
22563
22564
22565
22566
22567
22568
22569
22570
22571
22572
22573
22574
22575
22576
22577
22578
22579
22580
22581
22582
22583
22584
22585
22586
22587
22588
22589
22590
22591
22592
22593
22594
22595
22596
22597
22598
22599
22600
22601
22602
22603
22604
22605
22606
22607
22608
22609
22610
22611
22612
22613
22614
22615
22616
22617
22618
22619
22620
22621
22622
22623
22624
22625
22626
22627
22628
22629
22630
22631
22632
22633
22634
22635
22636
22637
22638
22639
22640
22641
22642
22643
22644
22645
22646
22647
22648
22649
22650
22651
22652
22653
22654
22655
22656
22657
22658
22659
22660
22661
22662
22663
22664
22665
22666
22667
22668
22669
22670
22671
22672
22673
22674
22675
22676
22677
22678
22679
22680
22681
22682
22683
22684
22685
22686
22687
22688
22689
22690
22691
22692
22693
22694
22695
22696
22697
22698
22699
22700
22701
22702
22703
22704
22705
22706
22707
22708
22709
22710
22711
22712
22713
22714
22715
22716
22717
22718
22719
22720
22721
22722
22723
22724
22725
22726
22727
22728
22729
22730
22731
22732
22733
22734
22735
22736
22737
22738
22739
22740
22741
22742
22743
22744
22745
22746
22747
22748
22749
22750
22751
22752
22753
22754
22755
22756
22757
22758
22759
22760
22761
22762
22763
22764
22765
22766
22767
22768
22769
22770
22771
22772
22773
22774
22775
22776
22777
22778
22779
22780
22781
22782
22783
22784
22785
22786
22787
22788
22789
22790
22791
22792
22793
22794
22795
22796
22797
22798
22799
22800
22801
22802
22803
22804
22805
22806
22807
22808
22809
22810
22811
22812
22813
22814
22815
22816
22817
22818
22819
22820
22821
22822
22823
22824
22825
22826
22827
22828
22829
22830
22831
22832
22833
22834
22835
22836
22837
22838
22839
22840
22841
22842
22843
22844
22845
22846
22847
22848
22849
22850
22851
22852
22853
22854
22855
22856
22857
22858
22859
22860
22861
22862
22863
22864
22865
22866
22867
22868
22869
22870
22871
22872
22873
22874
22875
22876
22877
22878
22879
22880
22881
22882
22883
22884
22885
22886
22887
22888
22889
22890
22891
22892
22893
22894
22895
22896
22897
22898
22899
22900
22901
22902
22903
22904
22905
22906
22907
22908
22909
22910
22911
22912
22913
22914
22915
22916
22917
22918
22919
22920
22921
22922
22923
22924
22925
22926
22927
22928
22929
22930
22931
22932
22933
22934
22935
22936
22937
22938
22939
22940
22941
22942
22943
22944
22945
22946
22947
22948
22949
22950
22951
22952
22953
22954
22955
22956
22957
22958
22959
22960
22961
22962
22963
22964
22965
22966
22967
22968
22969
22970
22971
22972
22973
22974
22975
22976
22977
22978
22979
22980
22981
22982
22983
22984
22985
22986
22987
22988
22989
22990
22991
22992
22993
22994
22995
22996
22997
22998
22999
23000
23001
23002
23003
23004
23005
23006
23007
23008
23009
23010
23011
23012
23013
23014
23015
23016
23017
23018
23019
23020
23021
23022
23023
23024
23025
23026
23027
23028
23029
23030
23031
23032
23033
23034
23035
23036
23037
23038
23039
23040
23041
23042
23043
23044
23045
23046
23047
23048
23049
23050
23051
23052
23053
23054
23055
23056
23057
23058
23059
23060
23061
23062
23063
23064
23065
23066
23067
23068
23069
23070
23071
23072
23073
23074
23075
23076
23077
23078
23079
23080
23081
23082
23083
23084
23085
23086
23087
23088
23089
23090
23091
23092
23093
23094
23095
23096
23097
23098
23099
23100
23101
23102
23103
23104
23105
23106
23107
23108
23109
23110
23111
23112
23113
23114
23115
23116
23117
23118
23119
23120
23121
23122
23123
23124
23125
23126
23127
23128
23129
23130
23131
23132
23133
23134
23135
23136
23137
23138
23139
23140
23141
23142
23143
23144
23145
23146
23147
23148
23149
23150
23151
23152
23153
23154
23155
23156
23157
23158
23159
23160
23161
23162
23163
23164
23165
23166
23167
23168
23169
23170
23171
23172
23173
23174
23175
23176
23177
23178
23179
23180
23181
23182
23183
23184
23185
23186
23187
23188
23189
23190
23191
23192
23193
23194
23195
23196
23197
23198
23199
23200
23201
23202
23203
23204
23205
23206
23207
23208
23209
23210
23211
23212
23213
23214
23215
23216
23217
23218
23219
23220
23221
23222
23223
23224
23225
23226
23227
23228
23229
23230
23231
23232
23233
23234
23235
23236
23237
23238
23239
23240
23241
23242
23243
23244
23245
23246
23247
23248
23249
23250
23251
23252
23253
23254
23255
23256
23257
23258
23259
23260
23261
23262
23263
23264
23265
23266
23267
23268
23269
23270
23271
23272
23273
23274
23275
23276
23277
23278
23279
23280
23281
23282
23283
23284
23285
23286
23287
23288
23289
23290
23291
23292
23293
23294
23295
23296
23297
23298
23299
23300
23301
23302
23303
23304
23305
23306
23307
23308
23309
23310
23311
23312
23313
23314
23315
23316
23317
23318
23319
23320
23321
23322
23323
23324
23325
23326
23327
23328
23329
23330
23331
23332
23333
23334
23335
23336
23337
23338
23339
23340
23341
23342
23343
23344
23345
23346
23347
23348
23349
23350
23351
23352
23353
23354
23355
23356
23357
23358
23359
23360
23361
23362
23363
23364
23365
23366
23367
23368
23369
23370
23371
23372
23373
23374
23375
23376
23377
23378
23379
23380
23381
23382
23383
23384
23385
23386
23387
23388
23389
23390
23391
23392
23393
23394
23395
23396
23397
23398
23399
23400
23401
23402
23403
23404
23405
23406
23407
23408
23409
23410
23411
23412
23413
23414
23415
23416
23417
23418
23419
23420
23421
23422
23423
23424
23425
23426
23427
23428
23429
23430
23431
23432
23433
23434
23435
23436
23437
23438
23439
23440
23441
23442
23443
23444
23445
23446
23447
23448
23449
23450
23451
23452
23453
23454
23455
23456
23457
23458
23459
23460
23461
23462
23463
23464
23465
23466
23467
23468
23469
23470
23471
23472
23473
23474
23475
23476
23477
23478
23479
23480
23481
23482
23483
23484
23485
23486
23487
23488
23489
23490
23491
23492
23493
23494
23495
23496
23497
23498
23499
23500
23501
23502
23503
23504
23505
23506
23507
23508
23509
23510
23511
23512
23513
23514
23515
23516
23517
23518
23519
23520
23521
23522
23523
23524
23525
23526
23527
23528
23529
23530
23531
23532
23533
23534
23535
23536
23537
23538
23539
23540
23541
23542
23543
23544
23545
23546
23547
23548
23549
23550
23551
23552
23553
23554
23555
23556
23557
23558
23559
23560
23561
23562
23563
23564
23565
23566
23567
23568
23569
23570
23571
23572
23573
23574
23575
23576
23577
23578
23579
23580
23581
23582
23583
23584
23585
23586
23587
23588
23589
23590
23591
23592
23593
23594
23595
23596
23597
23598
23599
23600
23601
23602
23603
23604
23605
23606
23607
23608
23609
23610
23611
23612
23613
23614
23615
23616
23617
23618
23619
23620
23621
23622
23623
23624
23625
23626
23627
23628
23629
23630
23631
23632
23633
23634
23635
23636
23637
23638
23639
23640
23641
23642
23643
23644
23645
23646
23647
23648
23649
23650
23651
23652
23653
23654
23655
23656
23657
23658
23659
23660
23661
23662
23663
23664
23665
23666
23667
23668
23669
23670
23671
23672
23673
23674
23675
23676
23677
23678
23679
23680
23681
23682
23683
23684
23685
23686
23687
23688
23689
23690
23691
23692
23693
23694
23695
23696
23697
23698
23699
23700
23701
23702
23703
23704
23705
23706
23707
23708
23709
23710
23711
23712
23713
23714
23715
23716
23717
23718
23719
23720
23721
23722
23723
23724
23725
23726
23727
23728
23729
23730
23731
23732
23733
23734
23735
23736
23737
23738
23739
23740
23741
23742
23743
23744
23745
23746
23747
23748
23749
23750
23751
23752
23753
23754
23755
23756
23757
23758
23759
23760
23761
23762
23763
23764
23765
23766
23767
23768
23769
23770
23771
23772
23773
23774
23775
23776
23777
23778
23779
23780
23781
23782
23783
23784
23785
23786
23787
23788
23789
23790
23791
23792
23793
23794
23795
23796
23797
23798
23799
23800
23801
23802
23803
23804
23805
23806
23807
23808
23809
23810
23811
23812
23813
23814
23815
23816
23817
23818
23819
23820
23821
23822
23823
23824
23825
23826
23827
23828
23829
23830
23831
23832
23833
23834
23835
23836
23837
23838
23839
23840
23841
23842
23843
23844
23845
23846
23847
23848
23849
23850
23851
23852
23853
23854
23855
23856
23857
23858
23859
23860
23861
23862
23863
23864
23865
23866
23867
23868
23869
23870
23871
23872
23873
23874
23875
23876
23877
23878
23879
23880
23881
23882
23883
23884
23885
23886
23887
23888
23889
23890
23891
23892
23893
23894
23895
23896
23897
23898
23899
23900
23901
23902
23903
23904
23905
23906
23907
23908
23909
23910
23911
23912
23913
23914
23915
23916
23917
23918
23919
23920
23921
23922
23923
23924
23925
23926
23927
23928
23929
23930
23931
23932
23933
23934
23935
23936
23937
23938
23939
23940
23941
23942
23943
23944
23945
23946
23947
23948
23949
23950
23951
23952
23953
23954
23955
23956
23957
23958
23959
23960
23961
23962
23963
23964
23965
23966
23967
23968
23969
23970
23971
23972
23973
23974
23975
23976
23977
23978
23979
23980
23981
23982
23983
23984
23985
23986
23987
23988
23989
23990
23991
23992
23993
23994
23995
23996
23997
23998
23999
24000
24001
24002
24003
24004
24005
24006
24007
24008
24009
24010
24011
24012
24013
24014
24015
24016
24017
24018
24019
24020
24021
24022
24023
24024
24025
24026
24027
24028
24029
24030
24031
24032
24033
24034
24035
24036
24037
24038
24039
24040
24041
24042
24043
24044
24045
24046
24047
24048
24049
24050
24051
24052
24053
24054
24055
24056
24057
24058
24059
24060
24061
24062
24063
24064
24065
24066
24067
24068
24069
24070
24071
24072
24073
24074
24075
24076
24077
24078
24079
24080
24081
24082
24083
24084
24085
24086
24087
24088
24089
24090
24091
24092
24093
24094
24095
24096
24097
24098
24099
24100
24101
24102
24103
24104
24105
24106
24107
24108
24109
24110
24111
24112
24113
24114
24115
24116
24117
24118
24119
24120
24121
24122
24123
24124
24125
24126
24127
24128
24129
24130
24131
24132
24133
24134
24135
24136
24137
24138
24139
24140
24141
24142
24143
24144
24145
24146
24147
24148
24149
24150
24151
24152
24153
24154
24155
24156
24157
24158
24159
24160
24161
24162
24163
24164
24165
24166
24167
24168
24169
24170
24171
24172
24173
24174
24175
24176
24177
24178
24179
24180
24181
24182
24183
24184
24185
24186
24187
24188
24189
24190
24191
24192
24193
24194
24195
24196
24197
24198
24199
24200
24201
24202
24203
24204
24205
24206
24207
24208
24209
24210
24211
24212
24213
24214
24215
24216
24217
24218
24219
24220
24221
24222
24223
24224
24225
24226
24227
24228
24229
24230
24231
24232
24233
24234
24235
24236
24237
24238
24239
24240
24241
24242
24243
24244
24245
24246
24247
24248
24249
24250
24251
24252
24253
24254
24255
24256
24257
24258
24259
24260
24261
24262
24263
24264
24265
24266
24267
24268
24269
24270
24271
24272
24273
24274
24275
24276
24277
24278
24279
24280
24281
24282
24283
24284
24285
24286
24287
24288
24289
24290
24291
24292
24293
24294
24295
24296
24297
24298
24299
24300
24301
24302
24303
24304
24305
24306
24307
24308
24309
24310
24311
24312
24313
24314
24315
24316
24317
24318
24319
24320
24321
24322
24323
24324
24325
24326
24327
24328
24329
24330
24331
24332
24333
24334
24335
24336
24337
24338
24339
24340
24341
24342
24343
24344
24345
24346
24347
24348
24349
24350
24351
24352
24353
24354
24355
24356
24357
24358
24359
24360
24361
24362
24363
24364
24365
24366
24367
24368
24369
24370
24371
24372
24373
24374
24375
24376
24377
24378
24379
24380
24381
24382
24383
24384
24385
24386
24387
24388
24389
24390
24391
24392
24393
24394
24395
24396
24397
24398
24399
24400
24401
24402
24403
24404
24405
24406
24407
24408
24409
24410
24411
24412
24413
24414
24415
24416
24417
24418
24419
24420
24421
24422
24423
24424
24425
24426
24427
24428
24429
24430
24431
24432
24433
24434
24435
24436
24437
24438
24439
24440
24441
24442
24443
24444
24445
24446
24447
24448
24449
24450
24451
24452
24453
24454
24455
24456
24457
24458
24459
24460
24461
24462
24463
24464
24465
24466
24467
24468
24469
24470
24471
24472
24473
24474
24475
24476
24477
24478
24479
24480
24481
24482
24483
24484
24485
24486
24487
24488
24489
24490
24491
24492
24493
24494
24495
24496
24497
24498
24499
24500
24501
24502
24503
24504
24505
24506
24507
24508
24509
24510
24511
24512
24513
24514
24515
24516
24517
24518
24519
24520
24521
24522
24523
24524
24525
24526
24527
24528
24529
24530
24531
24532
24533
24534
24535
24536
24537
24538
24539
24540
24541
24542
24543
24544
24545
24546
24547
24548
24549
24550
24551
24552
24553
24554
24555
24556
24557
24558
24559
24560
24561
24562
24563
24564
24565
24566
24567
24568
24569
24570
24571
24572
24573
24574
24575
24576
24577
24578
24579
24580
24581
24582
24583
24584
24585
24586
24587
24588
24589
24590
24591
24592
24593
24594
24595
24596
24597
24598
24599
24600
24601
24602
24603
24604
24605
24606
24607
24608
24609
24610
24611
24612
24613
24614
24615
24616
24617
24618
24619
24620
24621
24622
24623
24624
24625
24626
24627
24628
24629
24630
24631
24632
24633
24634
24635
24636
24637
24638
24639
24640
24641
24642
24643
24644
24645
24646
24647
24648
24649
24650
24651
24652
24653
24654
24655
24656
24657
24658
24659
24660
24661
24662
24663
24664
24665
24666
24667
24668
24669
24670
24671
24672
24673
24674
24675
24676
24677
24678
24679
24680
24681
24682
24683
24684
24685
24686
24687
24688
24689
24690
24691
24692
24693
24694
24695
24696
24697
24698
24699
24700
24701
24702
24703
24704
24705
24706
24707
24708
24709
24710
24711
24712
24713
24714
24715
24716
24717
24718
24719
24720
24721
24722
24723
24724
24725
24726
24727
24728
24729
24730
24731
24732
24733
24734
24735
24736
24737
24738
24739
24740
24741
24742
24743
24744
24745
24746
24747
24748
24749
24750
24751
24752
24753
24754
24755
24756
24757
24758
24759
24760
24761
24762
24763
24764
24765
24766
24767
24768
24769
24770
24771
24772
24773
24774
24775
24776
24777
24778
24779
24780
24781
24782
24783
24784
24785
24786
24787
24788
24789
24790
24791
24792
24793
24794
24795
24796
24797
24798
24799
24800
24801
24802
24803
24804
24805
24806
24807
24808
24809
24810
24811
24812
24813
24814
24815
24816
24817
24818
24819
24820
24821
24822
24823
24824
24825
24826
24827
24828
24829
24830
24831
24832
24833
24834
24835
24836
24837
24838
24839
24840
24841
24842
24843
24844
24845
24846
24847
24848
24849
24850
24851
24852
24853
24854
24855
24856
24857
24858
24859
24860
24861
24862
24863
24864
24865
24866
24867
24868
24869
24870
24871
24872
24873
24874
24875
24876
24877
24878
24879
24880
24881
24882
24883
24884
24885
24886
24887
24888
24889
24890
24891
24892
24893
24894
24895
24896
24897
24898
24899
24900
24901
24902
24903
24904
24905
24906
24907
24908
24909
24910
24911
24912
24913
24914
24915
24916
24917
24918
24919
24920
24921
24922
24923
24924
24925
24926
24927
24928
24929
24930
24931
24932
24933
24934
24935
24936
24937
24938
24939
24940
24941
24942
24943
24944
24945
24946
24947
24948
24949
24950
24951
24952
24953
24954
24955
24956
24957
24958
24959
24960
24961
24962
24963
24964
24965
24966
24967
24968
24969
24970
24971
24972
24973
24974
24975
24976
24977
24978
24979
24980
24981
24982
24983
24984
24985
24986
24987
24988
24989
24990
24991
24992
24993
24994
24995
24996
24997
24998
24999
25000
25001
25002
25003
25004
25005
25006
25007
25008
25009
25010
25011
25012
25013
25014
25015
25016
25017
25018
25019
25020
25021
25022
25023
25024
25025
25026
25027
25028
25029
25030
25031
25032
25033
25034
25035
25036
25037
25038
25039
25040
25041
25042
25043
25044
25045
25046
25047
25048
25049
25050
25051
25052
25053
25054
25055
25056
25057
25058
25059
25060
25061
25062
25063
25064
25065
25066
25067
25068
25069
25070
25071
25072
25073
25074
25075
25076
25077
25078
25079
25080
25081
25082
25083
25084
25085
25086
25087
25088
25089
25090
25091
25092
25093
25094
25095
25096
25097
25098
25099
25100
25101
25102
25103
25104
25105
25106
25107
25108
25109
25110
25111
25112
25113
25114
25115
25116
25117
25118
25119
25120
25121
25122
25123
25124
25125
25126
25127
25128
25129
25130
25131
25132
25133
25134
25135
25136
25137
25138
25139
25140
25141
25142
25143
25144
25145
25146
25147
25148
25149
25150
25151
25152
25153
25154
25155
25156
25157
25158
25159
25160
25161
25162
25163
25164
25165
25166
25167
25168
25169
25170
25171
25172
25173
25174
25175
25176
25177
25178
25179
25180
25181
25182
25183
25184
25185
25186
25187
25188
25189
25190
25191
25192
25193
25194
25195
25196
25197
25198
25199
25200
25201
25202
25203
25204
25205
25206
25207
25208
25209
25210
25211
25212
25213
25214
25215
25216
25217
25218
25219
25220
25221
25222
25223
25224
25225
25226
25227
25228
25229
25230
25231
25232
25233
25234
25235
25236
25237
25238
25239
25240
25241
25242
25243
25244
25245
25246
25247
25248
25249
25250
25251
25252
25253
25254
25255
25256
25257
25258
25259
25260
25261
25262
25263
25264
25265
25266
25267
25268
25269
25270
25271
25272
25273
25274
25275
25276
25277
25278
25279
25280
25281
25282
25283
25284
25285
25286
25287
25288
25289
25290
25291
25292
25293
25294
25295
25296
25297
25298
25299
25300
25301
25302
25303
25304
25305
25306
25307
25308
25309
25310
25311
25312
25313
25314
25315
25316
25317
25318
25319
25320
25321
25322
25323
25324
25325
25326
25327
25328
25329
25330
25331
25332
25333
25334
25335
25336
25337
25338
25339
25340
25341
25342
25343
25344
25345
25346
25347
25348
25349
25350
25351
25352
25353
25354
25355
25356
25357
25358
25359
25360
25361
25362
25363
25364
25365
25366
25367
25368
25369
25370
25371
25372
25373
25374
25375
25376
25377
25378
25379
25380
25381
25382
25383
25384
25385
25386
25387
25388
25389
25390
25391
25392
25393
25394
25395
25396
25397
25398
25399
25400
25401
25402
25403
25404
25405
25406
25407
25408
25409
25410
25411
25412
25413
25414
25415
25416
25417
25418
25419
25420
25421
25422
25423
25424
25425
25426
25427
25428
25429
25430
25431
25432
25433
25434
25435
25436
25437
25438
25439
25440
25441
25442
25443
25444
25445
25446
25447
25448
25449
25450
25451
25452
25453
25454
25455
25456
25457
25458
25459
25460
25461
25462
25463
25464
25465
25466
25467
25468
25469
25470
25471
25472
25473
25474
25475
25476
25477
25478
25479
25480
25481
25482
25483
25484
25485
25486
25487
25488
25489
25490
25491
25492
25493
25494
25495
25496
25497
25498
25499
25500
25501
25502
25503
25504
25505
25506
25507
25508
25509
25510
25511
25512
25513
25514
25515
25516
25517
25518
25519
25520
25521
25522
25523
25524
25525
25526
25527
25528
25529
25530
25531
25532
25533
25534
25535
25536
25537
25538
25539
25540
25541
25542
25543
25544
25545
25546
25547
25548
25549
25550
25551
25552
25553
25554
25555
25556
25557
25558
25559
25560
25561
25562
25563
25564
25565
25566
25567
25568
25569
25570
25571
25572
25573
25574
25575
25576
25577
25578
25579
25580
25581
25582
25583
25584
25585
25586
25587
25588
25589
25590
25591
25592
25593
25594
25595
25596
25597
25598
25599
25600
25601
25602
25603
25604
25605
25606
25607
25608
25609
25610
25611
25612
25613
25614
25615
25616
25617
25618
25619
25620
25621
25622
25623
25624
25625
25626
25627
25628
25629
25630
25631
25632
25633
25634
25635
25636
25637
25638
25639
25640
25641
25642
25643
25644
25645
25646
25647
25648
25649
25650
25651
25652
25653
25654
25655
25656
25657
25658
25659
25660
25661
25662
25663
25664
25665
25666
25667
25668
25669
25670
25671
25672
25673
25674
25675
25676
25677
25678
25679
25680
25681
25682
25683
25684
25685
25686
25687
25688
25689
25690
25691
25692
25693
25694
25695
25696
25697
25698
25699
25700
25701
25702
25703
25704
25705
25706
25707
25708
25709
25710
25711
25712
25713
25714
25715
25716
25717
25718
25719
25720
25721
25722
25723
25724
25725
25726
25727
25728
25729
25730
25731
25732
25733
25734
25735
25736
25737
25738
25739
25740
25741
25742
25743
25744
25745
25746
25747
25748
25749
25750
25751
25752
25753
25754
25755
25756
25757
25758
25759
25760
25761
25762
25763
25764
25765
25766
25767
25768
25769
25770
25771
25772
25773
25774
25775
25776
25777
25778
25779
25780
25781
25782
25783
25784
25785
25786
25787
25788
25789
25790
25791
25792
25793
25794
25795
25796
25797
25798
25799
25800
25801
25802
25803
25804
25805
25806
25807
25808
25809
25810
25811
25812
25813
25814
25815
25816
25817
25818
25819
25820
25821
25822
25823
25824
25825
25826
25827
25828
25829
25830
25831
25832
25833
25834
25835
25836
25837
25838
25839
25840
25841
25842
25843
25844
25845
25846
25847
25848
25849
25850
25851
25852
25853
25854
25855
25856
25857
25858
25859
25860
25861
25862
25863
25864
25865
25866
25867
25868
25869
25870
25871
25872
25873
25874
25875
25876
25877
25878
25879
25880
25881
25882
25883
25884
25885
25886
25887
25888
25889
25890
25891
25892
25893
25894
25895
25896
25897
25898
25899
25900
25901
25902
25903
25904
25905
25906
25907
25908
25909
25910
25911
25912
25913
25914
25915
25916
25917
25918
25919
25920
25921
25922
25923
25924
25925
25926
25927
25928
25929
25930
25931
25932
25933
25934
25935
25936
25937
25938
25939
25940
25941
25942
25943
25944
25945
25946
25947
25948
25949
25950
25951
25952
25953
25954
25955
25956
25957
25958
25959
25960
25961
25962
25963
25964
25965
25966
25967
25968
25969
25970
25971
25972
25973
25974
25975
25976
25977
25978
25979
25980
25981
25982
25983
25984
25985
25986
25987
25988
25989
25990
25991
25992
25993
25994
25995
25996
25997
25998
25999
26000
26001
26002
26003
26004
26005
26006
26007
26008
26009
26010
26011
26012
26013
26014
26015
26016
26017
26018
26019
26020
26021
26022
26023
26024
26025
26026
26027
26028
26029
26030
26031
26032
26033
26034
26035
26036
26037
26038
26039
26040
26041
26042
26043
26044
26045
26046
26047
26048
26049
26050
26051
26052
26053
26054
26055
26056
26057
26058
26059
26060
26061
26062
26063
26064
26065
26066
26067
26068
26069
26070
26071
26072
26073
26074
26075
26076
26077
26078
26079
26080
26081
26082
26083
26084
26085
26086
26087
26088
26089
26090
26091
26092
26093
26094
26095
26096
26097
26098
26099
26100
26101
26102
26103
26104
26105
26106
26107
26108
26109
26110
26111
26112
26113
26114
26115
26116
26117
26118
26119
26120
26121
26122
26123
26124
26125
26126
26127
26128
26129
26130
26131
26132
26133
26134
26135
26136
26137
26138
26139
26140
26141
26142
26143
26144
26145
26146
26147
26148
26149
26150
26151
26152
26153
26154
26155
26156
26157
26158
26159
26160
26161
26162
26163
26164
26165
26166
26167
26168
26169
26170
26171
26172
26173
26174
26175
26176
26177
26178
26179
26180
26181
26182
26183
26184
26185
26186
26187
26188
26189
26190
26191
26192
26193
26194
26195
26196
26197
26198
26199
26200
26201
26202
26203
26204
26205
26206
26207
26208
26209
26210
26211
26212
26213
26214
26215
26216
26217
26218
26219
26220
26221
26222
26223
26224
26225
26226
26227
26228
26229
26230
26231
26232
26233
26234
26235
26236
26237
26238
26239
26240
26241
26242
26243
26244
26245
26246
26247
26248
26249
26250
26251
26252
26253
26254
26255
26256
26257
26258
26259
26260
26261
26262
26263
26264
26265
26266
26267
26268
26269
26270
26271
26272
26273
26274
26275
26276
26277
26278
26279
26280
26281
26282
26283
26284
26285
26286
26287
26288
26289
26290
26291
26292
26293
26294
26295
26296
26297
26298
26299
26300
26301
26302
26303
26304
26305
26306
26307
26308
26309
26310
26311
26312
26313
26314
26315
26316
26317
26318
26319
26320
26321
26322
26323
26324
26325
26326
26327
26328
26329
26330
26331
26332
26333
26334
26335
26336
26337
26338
26339
26340
26341
26342
26343
26344
26345
26346
26347
26348
26349
26350
26351
26352
26353
26354
26355
26356
26357
26358
26359
26360
26361
26362
26363
26364
26365
26366
26367
26368
26369
26370
26371
26372
26373
26374
26375
26376
26377
26378
26379
26380
26381
26382
26383
26384
26385
26386
26387
26388
26389
26390
26391
26392
26393
26394
26395
26396
26397
26398
26399
26400
26401
26402
26403
26404
26405
26406
26407
26408
26409
26410
26411
26412
26413
26414
26415
26416
26417
26418
26419
26420
26421
26422
26423
26424
26425
26426
26427
26428
26429
26430
26431
26432
26433
26434
26435
26436
26437
26438
26439
26440
26441
26442
26443
26444
26445
26446
26447
26448
26449
26450
26451
26452
26453
26454
26455
26456
26457
26458
26459
26460
26461
26462
26463
26464
26465
26466
26467
26468
26469
26470
26471
26472
26473
26474
26475
26476
26477
26478
26479
26480
26481
26482
26483
26484
26485
26486
26487
26488
26489
26490
26491
26492
26493
26494
26495
26496
26497
26498
26499
26500
26501
26502
26503
26504
26505
26506
26507
26508
26509
26510
26511
26512
26513
26514
26515
26516
26517
26518
26519
26520
26521
26522
26523
26524
26525
26526
26527
26528
26529
26530
26531
26532
26533
26534
26535
26536
26537
26538
26539
26540
26541
26542
26543
26544
26545
26546
26547
26548
26549
26550
26551
26552
26553
26554
26555
26556
26557
26558
26559
26560
26561
26562
26563
26564
26565
26566
26567
26568
26569
26570
26571
26572
26573
26574
26575
26576
26577
26578
26579
26580
26581
26582
26583
26584
26585
26586
26587
26588
26589
26590
26591
26592
26593
26594
26595
26596
26597
26598
26599
26600
26601
26602
26603
26604
26605
26606
26607
26608
26609
26610
26611
26612
26613
26614
26615
26616
26617
26618
26619
26620
26621
26622
26623
26624
26625
26626
26627
26628
26629
26630
26631
26632
26633
26634
26635
26636
26637
26638
26639
26640
26641
26642
26643
26644
26645
26646
26647
26648
26649
26650
26651
26652
26653
26654
26655
26656
26657
26658
26659
26660
26661
26662
26663
26664
26665
26666
26667
26668
26669
26670
26671
26672
26673
26674
26675
26676
26677
26678
26679
26680
26681
26682
26683
26684
26685
26686
26687
26688
26689
26690
26691
26692
26693
26694
26695
26696
26697
26698
26699
26700
26701
26702
26703
26704
26705
26706
26707
26708
26709
26710
26711
26712
26713
26714
26715
26716
26717
26718
26719
26720
26721
26722
26723
26724
26725
26726
26727
26728
26729
26730
26731
26732
26733
26734
26735
26736
26737
26738
26739
26740
26741
26742
26743
26744
26745
26746
26747
26748
26749
26750
26751
26752
26753
26754
26755
26756
26757
26758
26759
26760
26761
26762
26763
26764
26765
26766
26767
26768
26769
26770
26771
26772
26773
26774
26775
26776
26777
26778
26779
26780
26781
26782
26783
26784
26785
26786
26787
26788
26789
26790
26791
26792
26793
26794
26795
26796
26797
26798
26799
26800
26801
26802
26803
26804
26805
26806
26807
26808
26809
26810
26811
26812
26813
26814
26815
26816
26817
26818
26819
26820
26821
26822
26823
26824
26825
26826
26827
26828
26829
26830
26831
26832
26833
26834
26835
26836
26837
26838
26839
26840
26841
26842
26843
26844
26845
26846
26847
26848
26849
26850
26851
26852
26853
26854
26855
26856
26857
26858
26859
26860
26861
26862
26863
26864
26865
26866
26867
26868
26869
26870
26871
26872
26873
26874
26875
26876
26877
26878
26879
26880
26881
26882
26883
26884
26885
26886
26887
26888
26889
26890
26891
26892
26893
26894
26895
26896
26897
26898
26899
26900
26901
26902
26903
26904
26905
26906
26907
26908
26909
26910
26911
26912
26913
26914
26915
26916
26917
26918
26919
26920
26921
26922
26923
26924
26925
26926
26927
26928
26929
26930
26931
26932
26933
26934
26935
26936
26937
26938
26939
26940
26941
26942
26943
26944
26945
26946
26947
26948
26949
26950
26951
26952
26953
26954
26955
26956
26957
26958
26959
26960
26961
26962
26963
26964
26965
26966
26967
26968
26969
26970
26971
26972
26973
26974
26975
26976
26977
26978
26979
26980
26981
26982
26983
26984
26985
26986
26987
26988
26989
26990
26991
26992
26993
26994
26995
26996
26997
26998
26999
27000
27001
27002
27003
27004
27005
27006
27007
27008
27009
27010
27011
27012
27013
27014
27015
27016
27017
27018
27019
27020
27021
27022
27023
27024
27025
27026
27027
27028
27029
27030
27031
27032
27033
27034
27035
27036
27037
27038
27039
27040
27041
27042
27043
27044
27045
27046
27047
27048
27049
27050
27051
27052
27053
27054
27055
27056
27057
27058
27059
27060
27061
27062
27063
27064
27065
27066
27067
27068
27069
27070
27071
27072
27073
27074
27075
27076
27077
27078
27079
27080
27081
27082
27083
27084
27085
27086
27087
27088
27089
27090
27091
27092
27093
27094
27095
27096
27097
27098
27099
27100
27101
27102
27103
27104
27105
27106
27107
27108
27109
27110
27111
27112
27113
27114
27115
27116
27117
27118
27119
27120
27121
27122
27123
27124
27125
27126
27127
27128
27129
27130
27131
27132
27133
27134
27135
27136
27137
27138
27139
27140
27141
27142
27143
27144
27145
27146
27147
27148
27149
27150
27151
27152
27153
27154
27155
27156
27157
27158
27159
27160
27161
27162
27163
27164
27165
27166
27167
27168
27169
27170
27171
27172
27173
27174
27175
27176
27177
27178
27179
27180
27181
27182
27183
27184
27185
27186
27187
27188
27189
27190
27191
27192
27193
27194
27195
27196
27197
27198
27199
27200
27201
27202
27203
27204
27205
27206
27207
27208
27209
27210
27211
27212
27213
27214
27215
27216
27217
27218
27219
27220
27221
27222
27223
27224
27225
27226
27227
27228
27229
27230
27231
27232
27233
27234
27235
27236
27237
27238
27239
27240
27241
27242
27243
27244
27245
27246
27247
27248
27249
27250
27251
27252
27253
27254
27255
27256
27257
27258
27259
27260
27261
27262
27263
27264
27265
27266
27267
27268
27269
27270
27271
27272
27273
27274
27275
27276
27277
27278
27279
27280
27281
27282
27283
27284
27285
27286
27287
27288
27289
27290
27291
27292
27293
27294
27295
27296
27297
27298
27299
27300
27301
27302
27303
27304
27305
27306
27307
27308
27309
27310
27311
27312
27313
27314
27315
27316
27317
27318
27319
27320
27321
27322
27323
27324
27325
27326
27327
27328
27329
27330
27331
27332
27333
27334
27335
27336
27337
27338
27339
27340
27341
27342
27343
27344
27345
27346
27347
27348
27349
27350
27351
27352
27353
27354
27355
27356
27357
27358
27359
27360
27361
27362
27363
27364
27365
27366
27367
27368
27369
27370
27371
27372
27373
27374
27375
27376
27377
27378
27379
27380
27381
27382
27383
27384
27385
27386
27387
27388
27389
27390
27391
27392
27393
27394
27395
27396
27397
27398
27399
27400
27401
27402
27403
27404
27405
27406
27407
27408
27409
27410
27411
27412
27413
27414
27415
27416
27417
27418
27419
27420
27421
27422
27423
27424
27425
27426
27427
27428
27429
27430
27431
27432
27433
27434
27435
27436
27437
27438
27439
27440
27441
27442
27443
27444
27445
27446
27447
27448
27449
27450
27451
27452
27453
27454
27455
27456
27457
27458
27459
27460
27461
27462
27463
27464
27465
27466
27467
27468
27469
27470
27471
27472
27473
27474
27475
27476
27477
27478
27479
27480
27481
27482
27483
27484
27485
27486
27487
27488
27489
27490
27491
27492
27493
27494
27495
27496
27497
27498
27499
27500
27501
27502
27503
27504
27505
27506
27507
27508
27509
27510
27511
27512
27513
27514
27515
27516
27517
27518
27519
27520
27521
27522
27523
27524
27525
27526
27527
27528
27529
27530
27531
27532
27533
27534
27535
27536
27537
27538
27539
27540
27541
27542
27543
27544
27545
27546
27547
27548
27549
27550
27551
27552
27553
27554
27555
27556
27557
27558
27559
27560
27561
27562
27563
27564
27565
27566
27567
27568
27569
27570
27571
27572
27573
27574
27575
27576
27577
27578
27579
27580
27581
27582
27583
27584
27585
27586
27587
27588
27589
27590
27591
27592
27593
27594
27595
27596
27597
27598
27599
27600
27601
27602
27603
27604
27605
27606
27607
27608
27609
27610
27611
27612
27613
27614
27615
27616
27617
27618
27619
27620
27621
27622
27623
27624
27625
27626
27627
27628
27629
27630
27631
27632
27633
27634
27635
27636
27637
27638
27639
27640
27641
27642
27643
27644
27645
27646
27647
27648
27649
27650
27651
27652
27653
27654
27655
27656
27657
27658
27659
27660
27661
27662
27663
27664
27665
27666
27667
27668
27669
27670
27671
27672
27673
27674
27675
27676
27677
27678
27679
27680
27681
27682
27683
27684
27685
27686
27687
27688
27689
27690
27691
27692
27693
27694
27695
27696
27697
27698
27699
27700
27701
27702
27703
27704
27705
27706
27707
27708
27709
27710
27711
27712
27713
27714
27715
27716
27717
27718
27719
27720
27721
27722
27723
27724
27725
27726
27727
27728
27729
27730
27731
27732
27733
27734
27735
27736
27737
27738
27739
27740
27741
27742
27743
27744
27745
27746
27747
27748
27749
27750
27751
27752
27753
27754
27755
27756
27757
27758
27759
27760
27761
27762
27763
27764
27765
27766
27767
27768
27769
27770
27771
27772
27773
27774
27775
27776
27777
27778
27779
27780
27781
27782
27783
27784
27785
27786
27787
27788
27789
27790
27791
27792
27793
27794
27795
27796
27797
27798
27799
27800
27801
27802
27803
27804
27805
27806
27807
27808
27809
27810
27811
27812
27813
27814
27815
27816
27817
27818
27819
27820
27821
27822
27823
27824
27825
27826
27827
27828
27829
27830
27831
27832
27833
27834
27835
27836
27837
27838
27839
27840
27841
27842
27843
27844
27845
27846
27847
27848
27849
27850
27851
27852
27853
27854
27855
27856
27857
27858
27859
27860
27861
27862
27863
27864
27865
27866
27867
27868
27869
27870
27871
27872
27873
27874
27875
27876
27877
27878
27879
27880
27881
27882
27883
27884
27885
27886
27887
27888
27889
27890
27891
27892
27893
27894
27895
27896
27897
27898
27899
27900
27901
27902
27903
27904
27905
27906
27907
27908
27909
27910
27911
27912
27913
27914
27915
27916
27917
27918
27919
27920
27921
27922
27923
27924
27925
27926
27927
27928
27929
27930
27931
27932
27933
27934
27935
27936
27937
27938
27939
27940
27941
27942
27943
27944
27945
27946
27947
27948
27949
27950
27951
27952
27953
27954
27955
27956
27957
27958
27959
27960
27961
27962
27963
27964
27965
27966
27967
27968
27969
27970
27971
27972
27973
27974
27975
27976
27977
27978
27979
27980
27981
27982
27983
27984
27985
27986
27987
27988
27989
27990
27991
27992
27993
27994
27995
27996
27997
27998
27999
28000
28001
28002
28003
28004
28005
28006
28007
28008
28009
28010
28011
28012
28013
28014
28015
28016
28017
28018
28019
28020
28021
28022
28023
28024
28025
28026
28027
28028
28029
28030
28031
28032
28033
28034
28035
28036
28037
28038
28039
28040
28041
28042
28043
28044
28045
28046
28047
28048
28049
28050
28051
28052
28053
28054
28055
28056
28057
28058
28059
28060
28061
28062
28063
28064
28065
28066
28067
28068
28069
28070
28071
28072
28073
28074
28075
28076
28077
28078
28079
28080
28081
28082
28083
28084
28085
28086
28087
28088
28089
28090
28091
28092
28093
28094
28095
28096
28097
28098
28099
28100
28101
28102
28103
28104
28105
28106
28107
28108
28109
28110
28111
28112
28113
28114
28115
28116
28117
28118
28119
28120
28121
28122
28123
28124
28125
28126
28127
28128
28129
28130
28131
28132
28133
28134
28135
28136
28137
28138
28139
28140
28141
28142
28143
28144
28145
28146
28147
28148
28149
28150
28151
28152
28153
28154
28155
28156
28157
28158
28159
28160
28161
28162
28163
28164
28165
28166
28167
28168
28169
28170
28171
28172
28173
28174
28175
28176
28177
28178
28179
28180
28181
28182
28183
28184
28185
28186
28187
28188
28189
28190
28191
28192
28193
28194
28195
28196
28197
28198
28199
28200
28201
28202
28203
28204
28205
28206
28207
28208
28209
28210
28211
28212
28213
28214
28215
28216
28217
28218
28219
28220
28221
28222
28223
28224
28225
28226
28227
28228
28229
28230
28231
28232
28233
28234
28235
28236
28237
28238
28239
28240
28241
28242
28243
28244
28245
28246
28247
28248
28249
28250
28251
28252
28253
28254
28255
28256
28257
28258
28259
28260
28261
28262
28263
28264
28265
28266
28267
28268
28269
28270
28271
28272
28273
28274
28275
28276
28277
28278
28279
28280
28281
28282
28283
28284
28285
28286
28287
28288
28289
28290
28291
28292
28293
28294
28295
28296
28297
28298
28299
28300
28301
28302
28303
28304
28305
28306
28307
28308
28309
28310
28311
28312
28313
28314
28315
28316
28317
28318
28319
28320
28321
28322
28323
28324
28325
28326
28327
28328
28329
28330
28331
28332
28333
28334
28335
28336
28337
28338
28339
28340
28341
28342
28343
28344
28345
28346
28347
28348
28349
28350
28351
28352
28353
28354
28355
28356
28357
28358
28359
28360
28361
28362
28363
28364
28365
28366
28367
28368
28369
28370
28371
28372
28373
28374
28375
28376
28377
28378
28379
28380
28381
28382
28383
28384
28385
28386
28387
28388
28389
28390
28391
28392
28393
28394
28395
28396
28397
28398
28399
28400
28401
28402
28403
28404
28405
28406
28407
28408
28409
28410
28411
28412
28413
28414
28415
28416
28417
28418
28419
28420
28421
28422
28423
28424
28425
28426
28427
28428
28429
28430
28431
28432
28433
28434
28435
28436
28437
28438
28439
28440
28441
28442
28443
28444
28445
28446
28447
28448
28449
28450
28451
28452
28453
28454
28455
28456
28457
28458
28459
28460
28461
28462
28463
28464
28465
28466
28467
28468
28469
28470
28471
28472
28473
28474
28475
28476
28477
28478
28479
28480
28481
28482
28483
28484
28485
28486
28487
28488
28489
28490
28491
28492
28493
28494
28495
28496
28497
28498
28499
28500
28501
28502
28503
28504
28505
28506
28507
28508
28509
28510
28511
28512
28513
28514
28515
28516
28517
28518
28519
28520
28521
28522
28523
28524
28525
28526
28527
28528
28529
28530
28531
28532
28533
28534
28535
28536
28537
28538
28539
28540
28541
28542
28543
28544
28545
28546
28547
28548
28549
28550
28551
28552
28553
28554
28555
28556
28557
28558
28559
28560
28561
28562
28563
28564
28565
28566
28567
28568
28569
28570
28571
28572
28573
28574
28575
28576
28577
28578
28579
28580
28581
28582
28583
28584
28585
28586
28587
28588
28589
28590
28591
28592
28593
28594
28595
28596
28597
28598
28599
28600
28601
28602
28603
28604
28605
28606
28607
28608
28609
28610
28611
28612
28613
28614
28615
28616
28617
28618
28619
28620
28621
28622
28623
28624
28625
28626
28627
28628
28629
28630
28631
28632
28633
28634
28635
28636
28637
28638
28639
28640
28641
28642
28643
28644
28645
28646
28647
28648
28649
28650
28651
28652
28653
28654
28655
28656
28657
28658
28659
28660
28661
28662
28663
28664
28665
28666
28667
28668
28669
28670
28671
28672
28673
28674
28675
28676
28677
28678
28679
28680
28681
28682
28683
28684
28685
28686
28687
28688
28689
28690
28691
28692
28693
28694
28695
28696
28697
28698
28699
28700
28701
28702
28703
28704
28705
28706
28707
28708
28709
28710
28711
28712
28713
28714
28715
28716
28717
28718
28719
28720
28721
28722
28723
28724
28725
28726
28727
28728
28729
28730
28731
28732
28733
28734
28735
28736
28737
28738
28739
28740
28741
28742
28743
28744
28745
28746
28747
28748
28749
28750
28751
28752
28753
28754
28755
28756
28757
28758
28759
28760
28761
28762
28763
28764
28765
28766
28767
28768
28769
28770
28771
28772
28773
28774
28775
28776
28777
28778
28779
28780
28781
28782
28783
28784
28785
28786
28787
28788
28789
28790
28791
28792
28793
28794
28795
28796
28797
28798
28799
28800
28801
28802
28803
28804
28805
28806
28807
28808
28809
28810
28811
28812
28813
28814
28815
28816
28817
28818
28819
28820
28821
28822
28823
28824
28825
28826
28827
28828
28829
28830
28831
28832
28833
28834
28835
28836
28837
28838
28839
28840
28841
28842
28843
28844
28845
28846
28847
28848
28849
28850
28851
28852
28853
28854
28855
28856
28857
28858
28859
28860
28861
28862
28863
28864
28865
28866
28867
28868
28869
28870
28871
28872
28873
28874
28875
28876
28877
28878
28879
28880
28881
28882
28883
28884
28885
28886
28887
28888
28889
28890
28891
28892
28893
28894
28895
28896
28897
28898
28899
28900
28901
28902
28903
28904
28905
28906
28907
28908
28909
28910
28911
28912
28913
28914
28915
28916
28917
28918
28919
28920
28921
28922
28923
28924
28925
28926
28927
28928
28929
28930
28931
28932
28933
28934
28935
28936
28937
28938
28939
28940
28941
28942
28943
28944
28945
28946
28947
28948
28949
28950
28951
28952
28953
28954
28955
28956
28957
28958
28959
28960
28961
28962
28963
28964
28965
28966
28967
28968
28969
28970
28971
28972
28973
28974
28975
28976
28977
28978
28979
28980
28981
28982
28983
28984
28985
28986
28987
28988
28989
28990
28991
28992
28993
28994
28995
28996
28997
28998
28999
29000
29001
29002
29003
29004
29005
29006
29007
29008
29009
29010
29011
29012
29013
29014
29015
29016
29017
29018
29019
29020
29021
29022
29023
29024
29025
29026
29027
29028
29029
29030
29031
29032
29033
29034
29035
29036
29037
29038
29039
29040
29041
29042
29043
29044
29045
29046
29047
29048
29049
29050
29051
29052
29053
29054
29055
29056
29057
29058
29059
29060
29061
29062
29063
29064
29065
29066
29067
29068
29069
29070
29071
29072
29073
29074
29075
29076
29077
29078
29079
29080
29081
29082
29083
29084
29085
29086
29087
29088
29089
29090
29091
29092
29093
29094
29095
29096
29097
29098
29099
29100
29101
29102
29103
29104
29105
29106
29107
29108
29109
29110
29111
29112
29113
29114
29115
29116
29117
29118
29119
29120
29121
29122
29123
29124
29125
29126
29127
29128
29129
29130
29131
29132
29133
29134
29135
29136
29137
29138
29139
29140
29141
29142
29143
29144
29145
29146
29147
29148
29149
29150
29151
29152
29153
29154
29155
29156
29157
29158
29159
29160
29161
29162
29163
29164
29165
29166
29167
29168
29169
29170
29171
29172
29173
29174
29175
29176
29177
29178
29179
29180
29181
29182
29183
29184
29185
29186
29187
29188
29189
29190
29191
29192
29193
29194
29195
29196
29197
29198
29199
29200
29201
29202
29203
29204
29205
29206
29207
29208
29209
29210
29211
29212
29213
29214
29215
29216
29217
29218
29219
29220
29221
29222
29223
29224
29225
29226
29227
29228
29229
29230
29231
29232
29233
29234
29235
29236
29237
29238
29239
29240
29241
29242
29243
29244
29245
29246
29247
29248
29249
29250
29251
29252
29253
29254
29255
29256
29257
29258
29259
29260
29261
29262
29263
29264
29265
29266
29267
29268
29269
29270
29271
29272
29273
29274
29275
29276
29277
29278
29279
29280
29281
29282
29283
29284
29285
29286
29287
29288
29289
29290
29291
29292
29293
29294
29295
29296
29297
29298
29299
29300
29301
29302
29303
29304
29305
29306
29307
29308
29309
29310
29311
29312
29313
29314
29315
29316
29317
29318
29319
29320
29321
29322
29323
29324
29325
29326
29327
29328
29329
29330
29331
29332
29333
29334
29335
29336
29337
29338
29339
29340
29341
29342
29343
29344
29345
29346
29347
29348
29349
29350
29351
29352
29353
29354
29355
29356
29357
29358
29359
29360
29361
29362
29363
29364
29365
29366
29367
29368
29369
29370
29371
29372
29373
29374
29375
29376
29377
29378
29379
29380
29381
29382
29383
29384
29385
29386
29387
29388
29389
29390
29391
29392
29393
29394
29395
29396
29397
29398
29399
29400
29401
29402
29403
29404
29405
29406
29407
29408
29409
29410
29411
29412
29413
29414
29415
29416
29417
29418
29419
29420
29421
29422
29423
29424
29425
29426
29427
29428
29429
29430
29431
29432
29433
29434
29435
29436
29437
29438
29439
29440
29441
29442
29443
29444
29445
29446
29447
29448
29449
29450
29451
29452
29453
29454
29455
29456
29457
29458
29459
29460
29461
29462
29463
29464
29465
29466
29467
29468
29469
29470
29471
29472
29473
29474
29475
29476
29477
29478
29479
29480
29481
29482
29483
29484
29485
29486
29487
29488
29489
29490
29491
29492
29493
29494
29495
29496
29497
29498
29499
29500
29501
29502
29503
29504
29505
29506
29507
29508
29509
29510
29511
29512
29513
29514
29515
29516
29517
29518
29519
29520
29521
29522
29523
29524
29525
29526
29527
29528
29529
29530
29531
29532
29533
29534
29535
29536
29537
29538
29539
29540
29541
29542
29543
29544
29545
29546
29547
29548
29549
29550
29551
29552
29553
29554
29555
29556
29557
29558
29559
29560
29561
29562
29563
29564
29565
29566
29567
29568
29569
29570
29571
29572
29573
29574
29575
29576
29577
29578
29579
29580
29581
29582
29583
29584
29585
29586
29587
29588
29589
29590
29591
29592
29593
29594
29595
29596
29597
29598
29599
29600
29601
29602
29603
29604
29605
29606
29607
29608
29609
29610
29611
29612
29613
29614
29615
29616
29617
29618
29619
29620
29621
29622
29623
29624
29625
29626
29627
29628
29629
29630
29631
29632
29633
29634
29635
29636
29637
29638
29639
29640
29641
29642
29643
29644
29645
29646
29647
29648
29649
29650
29651
29652
29653
29654
29655
29656
29657
29658
29659
29660
29661
29662
29663
29664
29665
29666
29667
29668
29669
29670
29671
29672
29673
29674
29675
29676
29677
29678
29679
29680
29681
29682
29683
29684
29685
29686
29687
29688
29689
29690
29691
29692
29693
29694
29695
29696
29697
29698
29699
29700
29701
29702
29703
29704
29705
29706
29707
29708
29709
29710
29711
29712
29713
29714
29715
29716
29717
29718
29719
29720
29721
29722
29723
29724
29725
29726
29727
29728
29729
29730
29731
29732
29733
29734
29735
29736
29737
29738
29739
29740
29741
29742
29743
29744
29745
29746
29747
29748
29749
29750
29751
29752
29753
29754
29755
29756
29757
29758
29759
29760
29761
29762
29763
29764
29765
29766
29767
29768
29769
29770
29771
29772
29773
29774
29775
29776
29777
29778
29779
29780
29781
29782
29783
29784
29785
29786
29787
29788
29789
29790
29791
29792
29793
29794
29795
29796
29797
29798
29799
29800
29801
29802
29803
29804
29805
29806
29807
29808
29809
29810
29811
29812
29813
29814
29815
29816
29817
29818
29819
29820
29821
29822
29823
29824
29825
29826
29827
29828
29829
29830
29831
29832
29833
29834
29835
29836
29837
29838
29839
29840
29841
29842
29843
29844
29845
29846
29847
29848
29849
29850
29851
29852
29853
29854
29855
29856
29857
29858
29859
29860
29861
29862
29863
29864
29865
29866
29867
29868
29869
29870
29871
29872
29873
29874
29875
29876
29877
29878
29879
29880
29881
29882
29883
29884
29885
29886
29887
29888
29889
29890
29891
29892
29893
29894
29895
29896
29897
29898
29899
29900
29901
29902
29903
29904
29905
29906
29907
29908
29909
29910
29911
29912
29913
29914
29915
29916
29917
29918
29919
29920
29921
29922
29923
29924
29925
29926
29927
29928
29929
29930
29931
29932
29933
29934
29935
29936
29937
29938
29939
29940
29941
29942
29943
29944
29945
29946
29947
29948
29949
29950
29951
29952
29953
29954
29955
29956
29957
29958
29959
29960
29961
29962
29963
29964
29965
29966
29967
29968
29969
29970
29971
29972
29973
29974
29975
29976
29977
29978
29979
29980
29981
29982
29983
29984
29985
29986
29987
29988
29989
29990
29991
29992
29993
29994
29995
29996
29997
29998
29999
30000
30001
30002
30003
30004
30005
30006
30007
30008
30009
30010
30011
30012
30013
30014
30015
30016
30017
30018
30019
30020
30021
30022
30023
30024
30025
30026
30027
30028
30029
30030
30031
30032
30033
30034
30035
30036
30037
30038
30039
30040
30041
30042
30043
30044
30045
30046
30047
30048
30049
30050
30051
30052
30053
30054
30055
30056
30057
30058
30059
30060
30061
30062
30063
30064
30065
30066
30067
30068
30069
30070
30071
30072
30073
30074
30075
30076
30077
30078
30079
30080
30081
30082
30083
30084
30085
30086
30087
30088
30089
30090
30091
30092
30093
30094
30095
30096
30097
30098
30099
30100
30101
30102
30103
30104
30105
30106
30107
30108
30109
30110
30111
30112
30113
30114
30115
30116
30117
30118
30119
30120
30121
30122
30123
30124
30125
30126
30127
30128
30129
30130
30131
30132
30133
30134
30135
30136
30137
30138
30139
30140
30141
30142
30143
30144
30145
30146
30147
30148
30149
30150
30151
30152
30153
30154
30155
30156
30157
30158
30159
30160
30161
30162
30163
30164
30165
30166
30167
30168
30169
30170
30171
30172
30173
30174
30175
30176
30177
30178
30179
30180
30181
30182
30183
30184
30185
30186
30187
30188
30189
30190
30191
30192
30193
30194
30195
30196
30197
30198
30199
30200
30201
30202
30203
30204
30205
30206
30207
30208
30209
30210
30211
30212
30213
30214
30215
30216
30217
30218
30219
30220
30221
30222
30223
30224
30225
30226
30227
30228
30229
30230
30231
30232
30233
30234
30235
30236
30237
30238
30239
30240
30241
30242
30243
30244
30245
30246
30247
30248
30249
30250
30251
30252
30253
30254
30255
30256
30257
30258
30259
30260
30261
30262
30263
30264
30265
30266
30267
30268
30269
30270
30271
30272
30273
30274
30275
30276
30277
30278
30279
30280
30281
30282
30283
30284
30285
30286
30287
30288
30289
30290
30291
30292
30293
30294
30295
30296
30297
30298
30299
30300
30301
30302
30303
30304
30305
30306
30307
30308
30309
30310
30311
30312
30313
30314
30315
30316
30317
30318
30319
30320
30321
30322
30323
30324
30325
30326
30327
30328
30329
30330
30331
30332
30333
30334
30335
30336
30337
30338
30339
30340
30341
30342
30343
30344
30345
30346
30347
30348
30349
30350
30351
30352
30353
30354
30355
30356
30357
30358
30359
30360
30361
30362
30363
30364
30365
30366
30367
30368
30369
30370
30371
30372
30373
30374
30375
30376
30377
30378
30379
30380
30381
30382
30383
30384
30385
30386
30387
30388
30389
30390
30391
30392
30393
30394
30395
30396
30397
30398
30399
30400
30401
30402
30403
30404
30405
30406
30407
30408
30409
30410
30411
30412
30413
30414
30415
30416
30417
30418
30419
30420
30421
30422
30423
30424
30425
30426
30427
30428
30429
30430
30431
30432
30433
30434
30435
30436
30437
30438
30439
30440
30441
30442
30443
30444
30445
30446
30447
30448
30449
30450
30451
30452
30453
30454
30455
30456
30457
30458
30459
30460
30461
30462
30463
30464
30465
30466
30467
30468
30469
30470
30471
30472
30473
30474
30475
30476
30477
30478
30479
30480
30481
30482
30483
30484
30485
30486
30487
30488
30489
30490
30491
30492
30493
30494
30495
30496
30497
30498
30499
30500
30501
30502
30503
30504
30505
30506
30507
30508
30509
30510
30511
30512
30513
30514
30515
30516
30517
30518
30519
30520
30521
30522
30523
30524
30525
30526
30527
30528
30529
30530
30531
30532
30533
30534
30535
30536
30537
30538
30539
30540
30541
30542
30543
30544
30545
30546
30547
30548
30549
30550
30551
30552
30553
30554
30555
30556
30557
30558
30559
30560
30561
30562
30563
30564
30565
30566
30567
30568
30569
30570
30571
30572
30573
30574
30575
30576
30577
30578
30579
30580
30581
30582
30583
30584
30585
30586
30587
30588
30589
30590
30591
30592
30593
30594
30595
30596
30597
30598
30599
30600
30601
30602
30603
30604
30605
30606
30607
30608
30609
30610
30611
30612
30613
30614
30615
30616
30617
30618
30619
30620
30621
30622
30623
30624
30625
30626
30627
30628
30629
30630
30631
30632
30633
30634
30635
30636
30637
30638
30639
30640
30641
30642
30643
30644
30645
30646
30647
30648
30649
30650
30651
30652
30653
30654
30655
30656
30657
30658
30659
30660
30661
30662
30663
30664
30665
30666
30667
30668
30669
30670
30671
30672
30673
30674
30675
30676
30677
30678
30679
30680
30681
30682
30683
30684
30685
30686
30687
30688
30689
30690
30691
30692
30693
30694
30695
30696
30697
30698
30699
30700
30701
30702
30703
30704
30705
30706
30707
30708
30709
30710
30711
30712
30713
30714
30715
30716
30717
30718
30719
30720
30721
30722
30723
30724
30725
30726
30727
30728
30729
30730
30731
30732
30733
30734
30735
30736
30737
30738
30739
30740
30741
30742
30743
30744
30745
30746
30747
30748
30749
30750
30751
30752
30753
30754
30755
30756
30757
30758
30759
30760
30761
30762
30763
30764
30765
30766
30767
30768
30769
30770
30771
30772
30773
30774
30775
30776
30777
30778
30779
30780
30781
30782
30783
30784
30785
30786
30787
30788
30789
30790
30791
30792
30793
30794
30795
30796
30797
30798
30799
30800
30801
30802
30803
30804
30805
30806
30807
30808
30809
30810
30811
30812
30813
30814
30815
30816
30817
30818
30819
30820
30821
30822
30823
30824
30825
30826
30827
30828
30829
30830
30831
30832
30833
30834
30835
30836
30837
30838
30839
30840
30841
30842
30843
30844
30845
30846
30847
30848
30849
30850
30851
30852
30853
30854
30855
30856
30857
30858
30859
30860
30861
30862
30863
30864
30865
30866
30867
30868
30869
30870
30871
30872
30873
30874
30875
30876
30877
30878
30879
30880
30881
30882
30883
30884
30885
30886
30887
30888
30889
30890
30891
30892
30893
30894
30895
30896
30897
30898
30899
30900
30901
30902
30903
30904
30905
30906
30907
30908
30909
30910
30911
30912
30913
30914
30915
30916
30917
30918
30919
30920
30921
30922
30923
30924
30925
30926
30927
30928
30929
30930
30931
30932
30933
30934
30935
30936
30937
30938
30939
30940
30941
30942
30943
30944
30945
30946
30947
30948
30949
30950
30951
30952
30953
30954
30955
30956
30957
30958
30959
30960
30961
30962
30963
30964
30965
30966
30967
30968
30969
30970
30971
30972
30973
30974
30975
30976
30977
30978
30979
30980
30981
30982
30983
30984
30985
30986
30987
30988
30989
30990
30991
30992
30993
30994
30995
30996
30997
30998
30999
31000
31001
31002
31003
31004
31005
31006
31007
31008
31009
31010
31011
31012
31013
31014
31015
31016
31017
31018
31019
31020
31021
31022
31023
31024
31025
31026
31027
31028
31029
31030
31031
31032
31033
31034
31035
31036
31037
31038
31039
31040
31041
31042
31043
31044
31045
31046
31047
31048
31049
31050
31051
31052
31053
31054
31055
31056
31057
31058
31059
31060
31061
31062
31063
31064
31065
31066
31067
31068
31069
31070
31071
31072
31073
31074
31075
31076
31077
31078
31079
31080
31081
31082
31083
31084
31085
31086
31087
31088
31089
31090
31091
31092
31093
31094
31095
31096
31097
31098
31099
31100
31101
31102
31103
31104
31105
31106
31107
31108
31109
31110
31111
31112
31113
31114
31115
31116
31117
31118
31119
31120
31121
31122
31123
31124
31125
31126
31127
31128
31129
31130
31131
31132
31133
31134
31135
31136
31137
31138
31139
31140
31141
31142
31143
31144
31145
31146
31147
31148
31149
31150
31151
31152
31153
31154
31155
31156
31157
31158
31159
31160
31161
31162
31163
31164
31165
31166
31167
31168
31169
31170
31171
31172
31173
31174
31175
31176
31177
31178
31179
31180
31181
31182
31183
31184
31185
31186
31187
31188
31189
31190
31191
31192
31193
31194
31195
31196
31197
31198
31199
31200
31201
31202
31203
31204
31205
31206
31207
31208
31209
31210
31211
31212
31213
31214
31215
31216
31217
31218
31219
31220
31221
31222
31223
31224
31225
31226
31227
31228
31229
31230
31231
31232
31233
31234
31235
31236
31237
31238
31239
31240
31241
31242
31243
31244
31245
31246
31247
31248
31249
31250
31251
31252
31253
31254
31255
31256
31257
31258
31259
31260
31261
31262
31263
31264
31265
31266
31267
31268
31269
31270
31271
31272
31273
31274
31275
31276
31277
31278
31279
31280
31281
31282
31283
31284
31285
31286
31287
31288
31289
31290
31291
31292
31293
31294
31295
31296
31297
31298
31299
31300
31301
31302
31303
31304
31305
31306
31307
31308
31309
31310
31311
31312
31313
31314
31315
31316
31317
31318
31319
31320
31321
31322
31323
31324
31325
31326
31327
31328
31329
31330
31331
31332
31333
31334
31335
31336
31337
31338
31339
31340
31341
31342
31343
31344
31345
31346
31347
31348
31349
31350
31351
31352
31353
31354
31355
31356
31357
31358
31359
31360
31361
31362
31363
31364
31365
31366
31367
31368
31369
31370
31371
31372
31373
31374
31375
31376
31377
31378
31379
31380
31381
31382
31383
31384
31385
31386
31387
31388
31389
31390
31391
31392
31393
31394
31395
31396
31397
31398
31399
31400
31401
31402
31403
31404
31405
31406
31407
31408
31409
31410
31411
31412
31413
31414
31415
31416
31417
31418
31419
31420
31421
31422
31423
31424
31425
31426
31427
31428
31429
31430
31431
31432
31433
31434
31435
31436
31437
31438
31439
31440
31441
31442
31443
31444
31445
31446
31447
31448
31449
31450
31451
31452
31453
31454
31455
31456
31457
31458
31459
31460
31461
31462
31463
31464
31465
31466
31467
31468
31469
31470
31471
31472
31473
31474
31475
31476
31477
31478
31479
31480
31481
31482
31483
31484
31485
31486
31487
31488
31489
31490
31491
31492
31493
31494
31495
31496
31497
31498
31499
31500
31501
31502
31503
31504
31505
31506
31507
31508
31509
31510
31511
31512
31513
31514
31515
31516
31517
31518
31519
31520
31521
31522
31523
31524
31525
31526
31527
31528
31529
31530
31531
31532
31533
31534
31535
31536
31537
31538
31539
31540
31541
31542
31543
31544
31545
31546
31547
31548
31549
31550
31551
31552
31553
31554
31555
31556
31557
31558
31559
31560
31561
31562
31563
31564
31565
31566
31567
31568
31569
31570
31571
31572
31573
31574
31575
31576
31577
31578
31579
31580
31581
31582
31583
31584
31585
31586
31587
31588
31589
31590
31591
31592
31593
31594
31595
31596
31597
31598
31599
31600
31601
31602
31603
31604
31605
31606
31607
31608
31609
31610
31611
31612
31613
31614
31615
31616
31617
31618
31619
31620
31621
31622
31623
31624
31625
31626
31627
31628
31629
31630
31631
31632
31633
31634
31635
31636
31637
31638
31639
31640
31641
31642
31643
31644
31645
31646
31647
31648
31649
31650
31651
31652
31653
31654
31655
31656
31657
31658
31659
31660
31661
31662
31663
31664
31665
31666
31667
31668
31669
31670
31671
31672
31673
31674
31675
31676
31677
31678
31679
31680
31681
31682
31683
31684
31685
31686
31687
31688
31689
31690
31691
31692
31693
31694
31695
31696
31697
31698
31699
31700
31701
31702
31703
31704
31705
31706
31707
31708
31709
31710
31711
31712
31713
31714
31715
31716
31717
31718
31719
31720
31721
31722
31723
31724
31725
31726
31727
31728
31729
31730
31731
31732
31733
31734
31735
31736
31737
31738
31739
31740
31741
31742
31743
31744
31745
31746
31747
31748
31749
31750
31751
31752
31753
31754
31755
31756
31757
31758
31759
31760
31761
31762
31763
31764
31765
31766
31767
31768
31769
31770
31771
31772
31773
31774
31775
31776
31777
31778
31779
31780
31781
31782
31783
31784
31785
31786
31787
31788
31789
31790
31791
31792
31793
31794
31795
31796
31797
31798
31799
31800
31801
31802
31803
31804
31805
31806
31807
31808
31809
31810
31811
31812
31813
31814
31815
31816
31817
31818
31819
31820
31821
31822
31823
31824
31825
31826
31827
31828
31829
31830
31831
31832
31833
31834
31835
31836
31837
31838
31839
31840
31841
31842
31843
31844
31845
31846
31847
31848
31849
31850
31851
31852
31853
31854
31855
31856
31857
31858
31859
31860
31861
31862
31863
31864
31865
31866
31867
31868
31869
31870
31871
31872
31873
31874
31875
31876
31877
31878
31879
31880
31881
31882
31883
31884
31885
31886
31887
31888
31889
31890
31891
31892
31893
31894
31895
31896
31897
31898
31899
31900
31901
31902
31903
31904
31905
31906
31907
31908
31909
31910
31911
31912
31913
31914
31915
31916
31917
31918
31919
31920
31921
31922
31923
31924
31925
31926
31927
31928
31929
31930
31931
31932
31933
31934
31935
31936
31937
31938
31939
31940
31941
31942
31943
31944
31945
31946
31947
31948
31949
31950
31951
31952
31953
31954
31955
31956
31957
31958
31959
31960
31961
31962
31963
31964
31965
31966
31967
31968
31969
31970
31971
31972
31973
31974
31975
31976
31977
31978
31979
31980
31981
31982
31983
31984
31985
31986
31987
31988
31989
31990
31991
31992
31993
31994
31995
31996
31997
31998
31999
32000
32001
32002
32003
32004
32005
32006
32007
32008
32009
32010
32011
32012
32013
32014
32015
32016
32017
32018
32019
32020
32021
32022
32023
32024
32025
32026
32027
32028
32029
32030
32031
32032
32033
32034
32035
32036
32037
32038
32039
32040
32041
32042
32043
32044
32045
32046
32047
32048
32049
32050
32051
32052
32053
32054
32055
32056
32057
32058
32059
32060
32061
32062
32063
32064
32065
32066
32067
32068
32069
32070
32071
32072
32073
32074
32075
32076
32077
32078
32079
32080
32081
32082
32083
32084
32085
32086
32087
32088
32089
32090
32091
32092
32093
32094
32095
32096
32097
32098
32099
32100
32101
32102
32103
32104
32105
32106
32107
32108
32109
32110
32111
32112
32113
32114
32115
32116
32117
32118
32119
32120
32121
32122
32123
32124
32125
32126
32127
32128
32129
32130
32131
32132
32133
32134
32135
32136
32137
32138
32139
32140
32141
32142
32143
32144
32145
32146
32147
32148
32149
32150
32151
32152
32153
32154
32155
32156
32157
32158
32159
32160
32161
32162
32163
32164
32165
32166
32167
32168
32169
32170
32171
32172
32173
32174
32175
32176
32177
32178
32179
32180
32181
32182
32183
32184
32185
32186
32187
32188
32189
32190
32191
32192
32193
32194
32195
32196
32197
32198
32199
32200
32201
32202
32203
32204
32205
32206
32207
32208
32209
32210
32211
32212
32213
32214
32215
32216
32217
32218
32219
32220
32221
32222
32223
32224
32225
32226
32227
32228
32229
32230
32231
32232
32233
32234
32235
32236
32237
32238
32239
32240
32241
32242
32243
32244
32245
32246
32247
32248
32249
32250
32251
32252
32253
32254
32255
32256
32257
32258
32259
32260
32261
32262
32263
32264
32265
32266
32267
32268
32269
32270
32271
32272
32273
32274
32275
32276
32277
32278
32279
32280
32281
32282
32283
32284
32285
32286
32287
32288
32289
32290
32291
32292
32293
32294
32295
32296
32297
32298
32299
32300
32301
32302
32303
32304
32305
32306
32307
32308
32309
32310
32311
32312
32313
32314
32315
32316
32317
32318
32319
32320
32321
32322
32323
32324
32325
32326
32327
32328
32329
32330
32331
32332
32333
32334
32335
32336
32337
32338
32339
32340
32341
32342
32343
32344
32345
32346
32347
32348
32349
32350
32351
32352
32353
32354
32355
32356
32357
32358
32359
32360
32361
32362
32363
32364
32365
32366
32367
32368
32369
32370
32371
32372
32373
32374
32375
32376
32377
32378
32379
32380
32381
32382
32383
32384
32385
32386
32387
32388
32389
32390
32391
32392
32393
32394
32395
32396
32397
32398
32399
32400
32401
32402
32403
32404
32405
32406
32407
32408
32409
32410
32411
32412
32413
32414
32415
32416
32417
32418
32419
32420
32421
32422
32423
32424
32425
32426
32427
32428
32429
32430
32431
32432
32433
32434
32435
32436
32437
32438
32439
32440
32441
32442
32443
32444
32445
32446
32447
32448
32449
32450
32451
32452
32453
32454
32455
32456
32457
32458
32459
32460
32461
32462
32463
32464
32465
32466
32467
32468
32469
32470
32471
32472
32473
32474
32475
32476
32477
32478
32479
32480
32481
32482
32483
32484
32485
32486
32487
32488
32489
32490
32491
32492
32493
32494
32495
32496
32497
32498
32499
32500
32501
32502
32503
32504
32505
32506
32507
32508
32509
32510
32511
32512
32513
32514
32515
32516
32517
32518
32519
32520
32521
32522
32523
32524
32525
32526
32527
32528
32529
32530
32531
32532
32533
32534
32535
32536
32537
32538
32539
32540
32541
32542
32543
32544
32545
32546
32547
32548
32549
32550
32551
32552
32553
32554
32555
32556
32557
32558
32559
32560
32561
32562
32563
32564
32565
32566
32567
32568
32569
32570
32571
32572
32573
32574
32575
32576
32577
32578
32579
32580
32581
32582
32583
32584
32585
32586
32587
32588
32589
32590
32591
32592
32593
32594
32595
32596
32597
32598
32599
32600
32601
32602
32603
32604
32605
32606
32607
32608
32609
32610
32611
32612
32613
32614
32615
32616
32617
32618
32619
32620
32621
32622
32623
32624
32625
32626
32627
32628
32629
32630
32631
32632
32633
32634
32635
32636
32637
32638
32639
32640
32641
32642
32643
32644
32645
32646
32647
32648
32649
32650
32651
32652
32653
32654
32655
32656
32657
32658
32659
32660
32661
32662
32663
32664
32665
32666
32667
32668
32669
32670
32671
32672
32673
32674
32675
32676
32677
32678
32679
32680
32681
32682
32683
32684
32685
32686
32687
32688
32689
32690
32691
32692
32693
32694
32695
32696
32697
32698
32699
32700
32701
32702
32703
32704
32705
32706
32707
32708
32709
32710
32711
32712
32713
32714
32715
32716
32717
32718
32719
32720
32721
32722
32723
32724
32725
32726
32727
32728
32729
32730
32731
32732
32733
32734
32735
32736
32737
32738
32739
32740
32741
32742
32743
32744
32745
32746
32747
32748
32749
32750
32751
32752
32753
32754
32755
32756
32757
32758
32759
32760
32761
32762
32763
32764
32765
32766
32767
32768
32769
32770
32771
32772
32773
32774
32775
32776
32777
32778
32779
32780
32781
32782
32783
32784
32785
32786
32787
32788
32789
32790
32791
32792
32793
32794
32795
32796
32797
32798
32799
32800
32801
32802
32803
32804
32805
32806
32807
32808
32809
32810
32811
32812
32813
32814
32815
32816
32817
32818
32819
32820
32821
32822
32823
32824
32825
32826
32827
32828
32829
32830
32831
32832
32833
32834
32835
32836
32837
32838
32839
32840
32841
32842
32843
32844
32845
32846
32847
32848
32849
32850
32851
32852
32853
32854
32855
32856
32857
32858
32859
32860
32861
32862
32863
32864
32865
32866
32867
32868
32869
32870
32871
32872
32873
32874
32875
32876
32877
32878
32879
32880
32881
32882
32883
32884
32885
32886
32887
32888
32889
32890
32891
32892
32893
32894
32895
32896
32897
32898
32899
32900
32901
32902
32903
32904
32905
32906
32907
32908
32909
32910
32911
32912
32913
32914
32915
32916
32917
32918
32919
32920
32921
32922
32923
32924
32925
32926
32927
32928
32929
32930
32931
32932
32933
32934
32935
32936
32937
32938
32939
32940
32941
32942
32943
32944
32945
32946
32947
32948
32949
32950
32951
32952
32953
32954
32955
32956
32957
32958
32959
32960
32961
32962
32963
32964
32965
32966
32967
32968
32969
32970
32971
32972
32973
32974
32975
32976
32977
32978
32979
32980
32981
32982
32983
32984
32985
32986
32987
32988
32989
32990
32991
32992
32993
32994
32995
32996
32997
32998
32999
33000
33001
33002
33003
33004
33005
33006
33007
33008
33009
33010
33011
33012
33013
33014
33015
33016
33017
33018
33019
33020
33021
33022
33023
33024
33025
33026
33027
33028
33029
33030
33031
33032
33033
33034
33035
33036
33037
33038
33039
33040
33041
33042
33043
33044
33045
33046
33047
33048
33049
33050
33051
33052
33053
33054
33055
33056
33057
33058
33059
33060
33061
33062
33063
33064
33065
33066
33067
33068
33069
33070
33071
33072
33073
33074
33075
33076
33077
33078
33079
33080
33081
33082
33083
33084
33085
33086
33087
33088
33089
33090
33091
33092
33093
33094
33095
33096
33097
33098
33099
33100
33101
33102
33103
33104
33105
33106
33107
33108
33109
33110
33111
33112
33113
33114
33115
33116
33117
33118
33119
33120
33121
33122
33123
33124
33125
33126
33127
33128
33129
33130
33131
33132
33133
33134
33135
33136
33137
33138
33139
33140
33141
33142
33143
33144
33145
33146
33147
33148
33149
33150
33151
33152
33153
33154
33155
33156
33157
33158
33159
33160
33161
33162
33163
33164
33165
33166
33167
33168
33169
33170
33171
33172
33173
33174
33175
33176
33177
33178
33179
33180
33181
33182
33183
33184
33185
33186
33187
33188
33189
33190
33191
33192
33193
33194
33195
33196
33197
33198
33199
33200
33201
33202
33203
33204
33205
33206
33207
33208
33209
33210
33211
33212
33213
33214
33215
33216
33217
33218
33219
33220
33221
33222
33223
33224
33225
33226
33227
33228
33229
33230
33231
33232
33233
33234
33235
33236
33237
33238
33239
33240
33241
33242
33243
33244
33245
33246
33247
33248
33249
33250
33251
33252
33253
33254
33255
33256
33257
33258
33259
33260
33261
33262
33263
33264
33265
33266
33267
33268
33269
33270
33271
33272
33273
33274
33275
33276
33277
33278
33279
33280
33281
33282
33283
33284
33285
33286
33287
33288
33289
33290
33291
33292
33293
33294
33295
33296
33297
33298
33299
33300
33301
33302
33303
33304
33305
33306
33307
33308
33309
33310
33311
33312
33313
33314
33315
33316
33317
33318
33319
33320
33321
33322
33323
33324
33325
33326
33327
33328
33329
33330
33331
33332
33333
33334
33335
33336
33337
33338
33339
33340
33341
33342
33343
33344
33345
33346
33347
33348
33349
33350
33351
33352
33353
33354
33355
33356
33357
33358
33359
33360
33361
33362
33363
33364
33365
33366
33367
33368
33369
33370
33371
33372
33373
33374
33375
33376
33377
33378
33379
33380
33381
33382
33383
33384
33385
33386
33387
33388
33389
33390
33391
33392
33393
33394
33395
33396
33397
33398
33399
33400
33401
33402
33403
33404
33405
33406
33407
33408
33409
33410
33411
33412
33413
33414
33415
33416
33417
33418
33419
33420
33421
33422
33423
33424
33425
33426
33427
33428
33429
33430
33431
33432
33433
33434
33435
33436
33437
33438
33439
33440
33441
33442
33443
33444
33445
33446
33447
33448
33449
33450
33451
33452
33453
33454
33455
33456
33457
33458
33459
33460
33461
33462
33463
33464
33465
33466
33467
33468
33469
33470
33471
33472
33473
33474
33475
33476
33477
33478
33479
33480
33481
33482
33483
33484
33485
33486
33487
33488
33489
33490
33491
33492
33493
33494
33495
33496
33497
33498
33499
33500
33501
33502
33503
33504
33505
33506
33507
33508
33509
33510
33511
33512
33513
33514
33515
33516
33517
33518
33519
33520
33521
33522
33523
33524
33525
33526
33527
33528
33529
33530
33531
33532
33533
33534
33535
33536
33537
33538
33539
33540
33541
33542
33543
33544
33545
33546
33547
33548
33549
33550
33551
33552
33553
33554
33555
33556
33557
33558
33559
33560
33561
33562
33563
33564
33565
33566
33567
33568
33569
33570
33571
33572
33573
33574
33575
33576
33577
33578
33579
33580
33581
33582
33583
33584
33585
33586
33587
33588
33589
33590
33591
33592
33593
33594
33595
33596
33597
33598
33599
33600
33601
33602
33603
33604
33605
33606
33607
33608
33609
33610
33611
33612
33613
33614
33615
33616
33617
33618
33619
33620
33621
33622
33623
33624
33625
33626
33627
33628
33629
33630
33631
33632
33633
33634
33635
33636
33637
33638
33639
33640
33641
33642
33643
33644
33645
33646
33647
33648
33649
33650
33651
33652
33653
33654
33655
33656
33657
33658
33659
33660
33661
33662
33663
33664
33665
33666
33667
33668
33669
33670
33671
33672
33673
33674
33675
33676
33677
33678
33679
33680
33681
33682
33683
33684
33685
33686
33687
33688
33689
33690
33691
33692
33693
33694
33695
33696
33697
33698
33699
33700
33701
33702
33703
33704
33705
33706
33707
33708
33709
33710
33711
33712
33713
33714
33715
33716
33717
33718
33719
33720
33721
33722
33723
33724
33725
33726
33727
33728
33729
33730
33731
33732
33733
33734
33735
33736
33737
33738
33739
33740
33741
33742
33743
33744
33745
33746
33747
33748
33749
33750
33751
33752
33753
33754
33755
33756
33757
33758
33759
33760
33761
33762
33763
33764
33765
33766
33767
33768
33769
33770
33771
33772
33773
33774
33775
33776
33777
33778
33779
33780
33781
33782
33783
33784
33785
33786
33787
33788
33789
33790
33791
33792
33793
33794
33795
33796
33797
33798
33799
33800
33801
33802
33803
33804
33805
33806
33807
33808
33809
33810
33811
33812
33813
33814
33815
33816
33817
33818
33819
33820
33821
33822
33823
33824
33825
33826
33827
33828
33829
33830
33831
33832
33833
33834
33835
33836
33837
33838
33839
33840
33841
33842
33843
33844
33845
33846
33847
33848
33849
33850
33851
33852
33853
33854
33855
33856
33857
33858
33859
33860
33861
33862
33863
33864
33865
33866
33867
33868
33869
33870
33871
33872
33873
33874
33875
33876
33877
33878
33879
33880
33881
33882
33883
33884
33885
33886
33887
33888
33889
33890
33891
33892
33893
33894
33895
33896
33897
33898
33899
33900
33901
33902
33903
33904
33905
33906
33907
33908
33909
33910
33911
33912
33913
33914
33915
33916
33917
33918
33919
33920
33921
33922
33923
33924
33925
33926
33927
33928
33929
33930
33931
33932
33933
33934
33935
33936
33937
33938
33939
33940
33941
33942
33943
33944
33945
33946
33947
33948
33949
33950
33951
33952
33953
33954
33955
33956
33957
33958
33959
33960
33961
33962
33963
33964
33965
33966
33967
33968
33969
33970
33971
33972
33973
33974
33975
33976
33977
33978
33979
33980
33981
33982
33983
33984
33985
33986
33987
33988
33989
33990
33991
33992
33993
33994
33995
33996
33997
33998
33999
34000
34001
34002
34003
34004
34005
34006
34007
34008
34009
34010
34011
34012
34013
34014
34015
34016
34017
34018
34019
34020
34021
34022
34023
34024
34025
34026
34027
34028
34029
34030
34031
34032
34033
34034
34035
34036
34037
34038
34039
34040
34041
34042
34043
34044
34045
34046
34047
34048
34049
34050
34051
34052
34053
34054
34055
34056
34057
34058
34059
34060
34061
34062
34063
34064
34065
34066
34067
34068
34069
34070
34071
34072
34073
34074
34075
34076
34077
34078
34079
34080
34081
34082
34083
34084
34085
34086
34087
34088
34089
34090
34091
34092
34093
34094
34095
34096
34097
34098
34099
34100
34101
34102
34103
34104
34105
34106
34107
34108
34109
34110
34111
34112
34113
34114
34115
34116
34117
34118
34119
34120
34121
34122
34123
34124
34125
34126
34127
34128
34129
34130
34131
34132
34133
34134
34135
34136
34137
34138
34139
34140
34141
34142
34143
34144
34145
34146
34147
34148
34149
34150
34151
34152
34153
34154
34155
34156
34157
34158
34159
34160
34161
34162
34163
34164
34165
34166
34167
34168
34169
34170
34171
34172
34173
34174
34175
34176
34177
34178
34179
34180
34181
34182
34183
34184
34185
34186
34187
34188
34189
34190
34191
34192
34193
34194
34195
34196
34197
34198
34199
34200
34201
34202
34203
34204
34205
34206
34207
34208
34209
34210
34211
34212
34213
34214
34215
34216
34217
34218
34219
34220
34221
34222
34223
34224
34225
34226
34227
34228
34229
34230
34231
34232
34233
34234
34235
34236
34237
34238
34239
34240
34241
34242
34243
34244
34245
34246
34247
34248
34249
34250
34251
34252
34253
34254
34255
34256
34257
34258
34259
34260
34261
34262
34263
34264
34265
34266
34267
34268
34269
34270
34271
34272
34273
34274
34275
34276
34277
34278
34279
34280
34281
34282
34283
34284
34285
34286
34287
34288
34289
34290
34291
34292
34293
34294
34295
34296
34297
34298
34299
34300
34301
34302
34303
34304
34305
34306
34307
34308
34309
34310
34311
34312
34313
34314
34315
34316
34317
34318
34319
34320
34321
34322
34323
34324
34325
34326
34327
34328
34329
34330
34331
34332
34333
34334
34335
34336
34337
34338
34339
34340
34341
34342
34343
34344
34345
34346
34347
34348
34349
34350
34351
34352
34353
34354
34355
34356
34357
34358
34359
34360
34361
34362
34363
34364
34365
34366
34367
34368
34369
34370
34371
34372
34373
34374
34375
34376
34377
34378
34379
34380
34381
34382
34383
34384
34385
34386
34387
34388
34389
34390
34391
34392
34393
34394
34395
34396
34397
34398
34399
34400
34401
34402
34403
34404
34405
34406
34407
34408
34409
34410
34411
34412
34413
34414
34415
34416
34417
34418
34419
34420
34421
34422
34423
34424
34425
34426
34427
34428
34429
34430
34431
34432
34433
34434
34435
34436
34437
34438
34439
34440
34441
34442
34443
34444
34445
34446
34447
34448
34449
34450
34451
34452
34453
34454
34455
34456
34457
34458
34459
34460
34461
34462
34463
34464
34465
34466
34467
34468
34469
34470
34471
34472
34473
34474
34475
34476
34477
34478
34479
34480
34481
34482
34483
34484
34485
34486
34487
34488
34489
34490
34491
34492
34493
34494
34495
34496
34497
34498
34499
34500
34501
34502
34503
34504
34505
34506
34507
34508
34509
34510
34511
34512
34513
34514
34515
34516
34517
34518
34519
34520
34521
34522
34523
34524
34525
34526
34527
34528
34529
34530
34531
34532
34533
34534
34535
34536
34537
34538
34539
34540
34541
34542
34543
34544
34545
34546
34547
34548
34549
34550
34551
34552
34553
34554
34555
34556
34557
34558
34559
34560
34561
34562
34563
34564
34565
34566
34567
34568
34569
34570
34571
34572
34573
34574
34575
34576
34577
34578
34579
34580
34581
34582
34583
34584
34585
34586
34587
34588
34589
34590
34591
34592
34593
34594
34595
34596
34597
34598
34599
34600
34601
34602
34603
34604
34605
34606
34607
34608
34609
34610
34611
34612
34613
34614
34615
34616
34617
34618
34619
34620
34621
34622
34623
34624
34625
34626
34627
34628
34629
34630
34631
34632
34633
34634
34635
34636
34637
34638
34639
34640
34641
34642
34643
34644
34645
34646
34647
34648
34649
34650
34651
34652
34653
34654
34655
34656
34657
34658
34659
34660
34661
34662
34663
34664
34665
34666
34667
34668
34669
34670
34671
34672
34673
34674
34675
34676
34677
34678
34679
34680
34681
34682
34683
34684
34685
34686
34687
34688
34689
34690
34691
34692
34693
34694
34695
34696
34697
34698
34699
34700
34701
34702
34703
34704
34705
34706
34707
34708
34709
34710
34711
34712
34713
34714
34715
34716
34717
34718
34719
34720
34721
34722
34723
34724
34725
34726
34727
34728
34729
34730
34731
34732
34733
34734
34735
34736
34737
34738
34739
34740
34741
34742
34743
34744
34745
34746
34747
34748
34749
34750
34751
34752
34753
34754
34755
34756
34757
34758
34759
34760
34761
34762
34763
34764
34765
34766
34767
34768
34769
34770
34771
34772
34773
34774
34775
34776
34777
34778
34779
34780
34781
34782
34783
34784
34785
34786
34787
34788
34789
34790
34791
34792
34793
34794
34795
34796
34797
34798
34799
34800
34801
34802
34803
34804
34805
34806
34807
34808
34809
34810
34811
34812
34813
34814
34815
34816
34817
34818
34819
34820
34821
34822
34823
34824
34825
34826
34827
34828
34829
34830
34831
34832
34833
34834
34835
34836
34837
34838
34839
34840
34841
34842
34843
34844
34845
34846
34847
34848
34849
34850
34851
34852
34853
34854
34855
34856
34857
34858
34859
34860
34861
34862
34863
34864
34865
34866
34867
34868
34869
34870
34871
34872
34873
34874
34875
34876
34877
34878
34879
34880
34881
34882
34883
34884
34885
34886
34887
34888
34889
34890
34891
34892
34893
34894
34895
34896
34897
34898
34899
34900
34901
34902
34903
34904
34905
34906
34907
34908
34909
34910
34911
34912
34913
34914
34915
34916
34917
34918
34919
34920
34921
34922
34923
34924
34925
34926
34927
34928
34929
34930
34931
34932
34933
34934
34935
34936
34937
34938
34939
34940
34941
34942
34943
34944
34945
34946
34947
34948
34949
34950
34951
34952
34953
34954
34955
34956
34957
34958
34959
34960
34961
34962
34963
34964
34965
34966
34967
34968
34969
34970
34971
34972
34973
34974
34975
34976
34977
34978
34979
34980
34981
34982
34983
34984
34985
34986
34987
34988
34989
34990
34991
34992
34993
34994
34995
34996
34997
34998
34999
35000
35001
35002
35003
35004
35005
35006
35007
35008
35009
35010
35011
35012
35013
35014
35015
35016
35017
35018
35019
35020
35021
35022
35023
35024
35025
35026
35027
35028
35029
35030
35031
35032
35033
35034
35035
35036
35037
35038
35039
35040
35041
35042
35043
35044
35045
35046
35047
35048
35049
35050
35051
35052
35053
35054
35055
35056
35057
35058
35059
35060
35061
35062
35063
35064
35065
35066
35067
35068
35069
35070
35071
35072
35073
35074
35075
35076
35077
35078
35079
35080
35081
35082
35083
35084
35085
35086
35087
35088
35089
35090
35091
35092
35093
35094
35095
35096
35097
35098
35099
35100
35101
35102
35103
35104
35105
35106
35107
35108
35109
35110
35111
35112
35113
35114
35115
35116
35117
35118
35119
35120
35121
35122
35123
35124
35125
35126
35127
35128
35129
35130
35131
35132
35133
35134
35135
35136
35137
35138
35139
35140
35141
35142
35143
35144
35145
35146
35147
35148
35149
35150
35151
35152
35153
35154
35155
35156
35157
35158
35159
35160
35161
35162
35163
35164
35165
35166
35167
35168
35169
35170
35171
35172
35173
35174
35175
35176
35177
35178
35179
35180
35181
35182
35183
35184
35185
35186
35187
35188
35189
35190
35191
35192
35193
35194
35195
35196
35197
35198
35199
35200
35201
35202
35203
35204
35205
35206
35207
35208
35209
35210
35211
35212
35213
35214
35215
35216
35217
35218
35219
35220
35221
35222
35223
35224
35225
35226
35227
35228
35229
35230
35231
35232
35233
35234
35235
35236
35237
35238
35239
35240
35241
35242
35243
35244
35245
35246
35247
35248
35249
35250
35251
35252
35253
35254
35255
35256
35257
35258
35259
35260
35261
35262
35263
35264
35265
35266
35267
35268
35269
35270
35271
35272
35273
35274
35275
35276
35277
35278
35279
35280
35281
35282
35283
35284
35285
35286
35287
35288
35289
35290
35291
35292
35293
35294
35295
35296
35297
35298
35299
35300
35301
35302
35303
35304
35305
35306
35307
35308
35309
35310
35311
35312
35313
35314
35315
35316
35317
35318
35319
35320
35321
35322
35323
35324
35325
35326
35327
35328
35329
35330
35331
35332
35333
35334
35335
35336
35337
35338
35339
35340
35341
35342
35343
35344
35345
35346
35347
35348
35349
35350
35351
35352
35353
35354
35355
35356
35357
35358
35359
35360
35361
35362
35363
35364
35365
35366
35367
35368
35369
35370
35371
35372
35373
35374
35375
35376
35377
35378
35379
35380
35381
35382
35383
35384
35385
35386
35387
35388
35389
35390
35391
35392
35393
35394
35395
35396
35397
35398
35399
35400
35401
35402
35403
35404
35405
35406
35407
35408
35409
35410
35411
35412
35413
35414
35415
35416
35417
35418
35419
35420
35421
35422
35423
35424
35425
35426
35427
35428
35429
35430
35431
35432
35433
35434
35435
35436
35437
35438
35439
35440
35441
35442
35443
35444
35445
35446
35447
35448
35449
35450
35451
35452
35453
35454
35455
35456
35457
35458
35459
35460
35461
35462
35463
35464
35465
35466
35467
35468
35469
35470
35471
35472
35473
35474
35475
35476
35477
35478
35479
35480
35481
35482
35483
35484
35485
35486
35487
35488
35489
35490
35491
35492
35493
35494
35495
35496
35497
35498
35499
35500
35501
35502
35503
35504
35505
35506
35507
35508
35509
35510
35511
35512
35513
35514
35515
35516
35517
35518
35519
35520
35521
35522
35523
35524
35525
35526
35527
35528
35529
35530
35531
35532
35533
35534
35535
35536
35537
35538
35539
35540
35541
35542
35543
35544
35545
35546
35547
35548
35549
35550
35551
35552
35553
35554
35555
35556
35557
35558
35559
35560
35561
35562
35563
35564
35565
35566
35567
35568
35569
35570
35571
35572
35573
35574
35575
35576
35577
35578
35579
35580
35581
35582
35583
35584
35585
35586
35587
35588
35589
35590
35591
35592
35593
35594
35595
35596
35597
35598
35599
35600
35601
35602
35603
35604
35605
35606
35607
35608
35609
35610
35611
35612
35613
35614
35615
35616
35617
35618
35619
35620
35621
35622
35623
35624
35625
35626
35627
35628
35629
35630
35631
35632
35633
35634
35635
35636
35637
35638
35639
35640
35641
35642
35643
35644
35645
35646
35647
35648
35649
35650
35651
35652
35653
35654
35655
35656
35657
35658
35659
35660
35661
35662
35663
35664
35665
35666
35667
35668
35669
35670
35671
35672
35673
35674
35675
35676
35677
35678
35679
35680
35681
35682
35683
35684
35685
35686
35687
35688
35689
35690
35691
35692
35693
35694
35695
35696
35697
35698
35699
35700
35701
35702
35703
35704
35705
35706
35707
35708
35709
35710
35711
35712
35713
35714
35715
35716
35717
35718
35719
35720
35721
35722
35723
35724
35725
35726
35727
35728
35729
35730
35731
35732
35733
35734
35735
35736
35737
35738
35739
35740
35741
35742
35743
35744
35745
35746
35747
35748
35749
35750
35751
35752
35753
35754
35755
35756
35757
35758
35759
35760
35761
35762
35763
35764
35765
35766
35767
35768
35769
35770
35771
35772
35773
35774
35775
35776
35777
35778
35779
35780
35781
35782
35783
35784
35785
35786
35787
35788
35789
35790
35791
35792
35793
35794
35795
35796
35797
35798
35799
35800
35801
35802
35803
35804
35805
35806
35807
35808
35809
35810
35811
35812
35813
35814
35815
35816
35817
35818
35819
35820
35821
35822
35823
35824
35825
35826
35827
35828
35829
35830
35831
35832
35833
35834
35835
35836
35837
35838
35839
35840
35841
35842
35843
35844
35845
35846
35847
35848
35849
35850
35851
35852
35853
35854
35855
35856
35857
35858
35859
35860
35861
35862
35863
35864
35865
35866
35867
35868
35869
35870
35871
35872
35873
35874
35875
35876
35877
35878
35879
35880
35881
35882
35883
35884
35885
35886
35887
35888
35889
35890
35891
35892
35893
35894
35895
35896
35897
35898
35899
35900
35901
35902
35903
35904
35905
35906
35907
35908
35909
35910
35911
35912
35913
35914
35915
35916
35917
35918
35919
35920
35921
35922
35923
35924
35925
35926
35927
35928
35929
35930
35931
35932
35933
35934
35935
35936
35937
35938
35939
35940
35941
35942
35943
35944
35945
35946
35947
35948
35949
35950
35951
35952
35953
35954
35955
35956
35957
35958
35959
35960
35961
35962
35963
35964
35965
35966
35967
35968
35969
35970
35971
35972
35973
35974
35975
35976
35977
35978
35979
35980
35981
35982
35983
35984
35985
35986
35987
35988
35989
35990
35991
35992
35993
35994
35995
35996
35997
35998
35999
36000
36001
36002
36003
36004
36005
36006
36007
36008
36009
36010
36011
36012
36013
36014
36015
36016
36017
36018
36019
36020
36021
36022
36023
36024
36025
36026
36027
36028
36029
36030
36031
36032
36033
36034
36035
36036
36037
36038
36039
36040
36041
36042
36043
36044
36045
36046
36047
36048
36049
36050
36051
36052
36053
36054
36055
36056
36057
36058
36059
36060
36061
36062
36063
36064
36065
36066
36067
36068
36069
36070
36071
36072
36073
36074
36075
36076
36077
36078
36079
36080
36081
36082
36083
36084
36085
36086
36087
36088
36089
36090
36091
36092
36093
36094
36095
36096
36097
36098
36099
36100
36101
36102
36103
36104
36105
36106
36107
36108
36109
36110
36111
36112
36113
36114
36115
36116
36117
36118
36119
36120
36121
36122
36123
36124
36125
36126
36127
36128
36129
36130
36131
36132
36133
36134
36135
36136
36137
36138
36139
36140
36141
36142
36143
36144
36145
36146
36147
36148
36149
36150
36151
36152
36153
36154
36155
36156
36157
36158
36159
36160
36161
36162
36163
36164
36165
36166
36167
36168
36169
36170
36171
36172
36173
36174
36175
36176
36177
36178
36179
36180
36181
36182
36183
36184
36185
36186
36187
36188
36189
36190
36191
36192
36193
36194
36195
36196
36197
36198
36199
36200
36201
36202
36203
36204
36205
36206
36207
36208
36209
36210
36211
36212
36213
36214
36215
36216
36217
36218
36219
36220
36221
36222
36223
36224
36225
36226
36227
36228
36229
36230
36231
36232
36233
36234
36235
36236
36237
36238
36239
36240
36241
36242
36243
36244
36245
36246
36247
36248
36249
36250
36251
36252
36253
36254
36255
36256
36257
36258
36259
36260
36261
36262
36263
36264
36265
36266
36267
36268
36269
36270
36271
36272
36273
36274
36275
36276
36277
36278
36279
36280
36281
36282
36283
36284
36285
36286
36287
36288
36289
36290
36291
36292
36293
36294
36295
36296
36297
36298
36299
36300
36301
36302
36303
36304
36305
36306
36307
36308
36309
36310
36311
36312
36313
36314
36315
36316
36317
36318
36319
36320
36321
36322
36323
36324
36325
36326
36327
36328
36329
36330
36331
36332
36333
36334
36335
36336
36337
36338
36339
36340
36341
36342
36343
36344
36345
36346
36347
36348
36349
36350
36351
36352
36353
36354
36355
36356
36357
36358
36359
36360
36361
36362
36363
36364
36365
36366
36367
36368
36369
36370
36371
36372
36373
36374
36375
36376
36377
36378
36379
36380
36381
36382
36383
36384
36385
36386
36387
36388
36389
36390
36391
36392
36393
36394
36395
36396
36397
36398
36399
36400
36401
36402
36403
36404
36405
36406
36407
36408
36409
36410
36411
36412
36413
36414
36415
36416
36417
36418
36419
36420
36421
36422
36423
36424
36425
36426
36427
36428
36429
36430
36431
36432
36433
36434
36435
36436
36437
36438
36439
36440
36441
36442
36443
36444
36445
36446
36447
36448
36449
36450
36451
36452
36453
36454
36455
36456
36457
36458
36459
36460
36461
36462
36463
36464
36465
36466
36467
36468
36469
36470
36471
36472
36473
36474
36475
36476
36477
36478
36479
36480
36481
36482
36483
36484
36485
36486
36487
36488
36489
36490
36491
36492
36493
36494
36495
36496
36497
36498
36499
36500
36501
36502
36503
36504
36505
36506
36507
36508
36509
36510
36511
36512
36513
36514
36515
36516
36517
36518
36519
36520
36521
36522
36523
36524
36525
36526
36527
36528
36529
36530
36531
36532
36533
36534
36535
36536
36537
36538
36539
36540
36541
36542
36543
36544
36545
36546
36547
36548
36549
36550
36551
36552
36553
36554
36555
36556
36557
36558
36559
36560
36561
36562
36563
36564
36565
36566
36567
36568
36569
36570
36571
36572
36573
36574
36575
36576
36577
36578
36579
36580
36581
36582
36583
36584
36585
36586
36587
36588
36589
36590
36591
36592
36593
36594
36595
36596
36597
36598
36599
36600
36601
36602
36603
36604
36605
36606
36607
36608
36609
36610
36611
36612
36613
36614
36615
36616
36617
36618
36619
36620
36621
36622
36623
36624
36625
36626
36627
36628
36629
36630
36631
36632
36633
36634
36635
36636
36637
36638
36639
36640
36641
36642
36643
36644
36645
36646
36647
36648
36649
36650
36651
36652
36653
36654
36655
36656
36657
36658
36659
36660
36661
36662
36663
36664
36665
36666
36667
36668
36669
36670
36671
36672
36673
36674
36675
36676
36677
36678
36679
36680
36681
36682
36683
36684
36685
36686
36687
36688
36689
36690
36691
36692
36693
36694
36695
36696
36697
36698
36699
36700
36701
36702
36703
36704
36705
36706
36707
36708
36709
36710
36711
36712
36713
36714
36715
36716
36717
36718
36719
36720
36721
36722
36723
36724
36725
36726
36727
36728
36729
36730
36731
36732
36733
36734
36735
36736
36737
36738
36739
36740
36741
36742
36743
36744
36745
36746
36747
36748
36749
36750
36751
36752
36753
36754
36755
36756
36757
36758
36759
36760
36761
36762
36763
36764
36765
36766
36767
36768
36769
36770
36771
36772
36773
36774
36775
36776
36777
36778
36779
36780
36781
36782
36783
36784
36785
36786
36787
36788
36789
36790
36791
36792
36793
36794
36795
36796
36797
36798
36799
36800
36801
36802
36803
36804
36805
36806
36807
36808
36809
36810
36811
36812
36813
36814
36815
36816
36817
36818
36819
36820
36821
36822
36823
36824
36825
36826
36827
36828
36829
36830
36831
36832
36833
36834
36835
36836
36837
36838
36839
36840
36841
36842
36843
36844
36845
36846
36847
36848
36849
36850
36851
36852
36853
36854
36855
36856
36857
36858
36859
36860
36861
36862
36863
36864
36865
36866
36867
36868
36869
36870
36871
36872
36873
36874
36875
36876
36877
36878
36879
36880
36881
36882
36883
36884
36885
36886
36887
36888
36889
36890
36891
36892
36893
36894
36895
36896
36897
36898
36899
36900
36901
36902
36903
36904
36905
36906
36907
36908
36909
36910
36911
36912
36913
36914
36915
36916
36917
36918
36919
36920
36921
36922
36923
36924
36925
36926
36927
36928
36929
36930
36931
36932
36933
36934
36935
36936
36937
36938
36939
36940
36941
36942
36943
36944
36945
36946
36947
36948
36949
36950
36951
36952
36953
36954
36955
36956
36957
36958
36959
36960
36961
36962
36963
36964
36965
36966
36967
36968
36969
36970
36971
36972
36973
36974
36975
36976
36977
36978
36979
36980
36981
36982
36983
36984
36985
36986
36987
36988
36989
36990
36991
36992
36993
36994
36995
36996
36997
36998
36999
37000
37001
37002
37003
37004
37005
37006
37007
37008
37009
37010
37011
37012
37013
37014
37015
37016
37017
37018
37019
37020
37021
37022
37023
37024
37025
37026
37027
37028
37029
37030
37031
37032
37033
37034
37035
37036
37037
37038
37039
37040
37041
37042
37043
37044
37045
37046
37047
37048
37049
37050
37051
37052
37053
37054
37055
37056
37057
37058
37059
37060
37061
37062
37063
37064
37065
37066
37067
37068
37069
37070
37071
37072
37073
37074
37075
37076
37077
37078
37079
37080
37081
37082
37083
37084
37085
37086
37087
37088
37089
37090
37091
37092
37093
37094
37095
37096
37097
37098
37099
37100
37101
37102
37103
37104
37105
37106
37107
37108
37109
37110
37111
37112
37113
37114
37115
37116
37117
37118
37119
37120
37121
37122
37123
37124
37125
37126
37127
37128
37129
37130
37131
37132
37133
37134
37135
37136
37137
37138
37139
37140
37141
37142
37143
37144
37145
37146
37147
37148
37149
37150
37151
37152
37153
37154
37155
37156
37157
37158
37159
37160
37161
37162
37163
37164
37165
37166
37167
37168
37169
37170
37171
37172
37173
37174
37175
37176
37177
37178
37179
37180
37181
37182
37183
37184
37185
37186
37187
37188
37189
37190
37191
37192
37193
37194
37195
37196
37197
37198
37199
37200
37201
37202
37203
37204
37205
37206
37207
37208
37209
37210
37211
37212
37213
37214
37215
37216
37217
37218
37219
37220
37221
37222
37223
37224
37225
37226
37227
37228
37229
37230
37231
37232
37233
37234
37235
37236
37237
37238
37239
37240
37241
37242
37243
37244
37245
37246
37247
37248
37249
37250
37251
37252
37253
37254
37255
37256
37257
37258
37259
37260
37261
37262
37263
37264
37265
37266
37267
37268
37269
37270
37271
37272
37273
37274
37275
37276
37277
37278
37279
37280
37281
37282
37283
37284
37285
37286
37287
37288
37289
37290
37291
37292
37293
37294
37295
37296
37297
37298
37299
37300
37301
37302
37303
37304
37305
37306
37307
37308
37309
37310
37311
37312
37313
37314
37315
37316
37317
37318
37319
37320
37321
37322
37323
37324
37325
37326
37327
37328
37329
37330
37331
37332
37333
37334
37335
37336
37337
37338
37339
37340
37341
37342
37343
37344
37345
37346
37347
37348
37349
37350
37351
37352
37353
37354
37355
37356
37357
37358
37359
37360
37361
37362
37363
37364
37365
37366
37367
37368
37369
37370
37371
37372
37373
37374
37375
37376
37377
37378
37379
37380
37381
37382
37383
37384
37385
37386
37387
37388
37389
37390
37391
37392
37393
37394
37395
37396
37397
37398
37399
37400
37401
37402
37403
37404
37405
37406
37407
37408
37409
37410
37411
37412
37413
37414
37415
37416
37417
37418
37419
37420
37421
37422
37423
37424
37425
37426
37427
37428
37429
37430
37431
37432
37433
37434
37435
37436
37437
37438
37439
37440
37441
37442
37443
37444
37445
37446
37447
37448
37449
37450
37451
37452
37453
37454
37455
37456
37457
37458
37459
37460
37461
37462
37463
37464
37465
37466
37467
37468
37469
37470
37471
37472
37473
37474
37475
37476
37477
37478
37479
37480
37481
37482
37483
37484
37485
37486
37487
37488
37489
37490
37491
37492
37493
37494
37495
37496
37497
37498
37499
37500
37501
37502
37503
37504
37505
37506
37507
37508
37509
37510
37511
37512
37513
37514
37515
37516
37517
37518
37519
37520
37521
37522
37523
37524
37525
37526
37527
37528
37529
37530
37531
37532
37533
37534
37535
37536
37537
37538
37539
37540
37541
37542
37543
37544
37545
37546
37547
37548
37549
37550
37551
37552
37553
37554
37555
37556
37557
37558
37559
37560
37561
37562
37563
37564
37565
37566
37567
37568
37569
37570
37571
37572
37573
37574
37575
37576
37577
37578
37579
37580
37581
37582
37583
37584
37585
37586
37587
37588
37589
37590
37591
37592
37593
37594
37595
37596
37597
37598
37599
37600
37601
37602
37603
37604
37605
37606
37607
37608
37609
37610
37611
37612
37613
37614
37615
37616
37617
37618
37619
37620
37621
37622
37623
37624
37625
37626
37627
37628
37629
37630
37631
37632
37633
37634
37635
37636
37637
37638
37639
37640
37641
37642
37643
37644
37645
37646
37647
37648
37649
37650
37651
37652
37653
37654
37655
37656
37657
37658
37659
37660
37661
37662
37663
37664
37665
37666
37667
37668
37669
37670
37671
37672
37673
37674
37675
37676
37677
37678
37679
37680
37681
37682
37683
37684
37685
37686
37687
37688
37689
37690
37691
37692
37693
37694
37695
37696
37697
37698
37699
37700
37701
37702
37703
37704
37705
37706
37707
37708
37709
37710
37711
37712
37713
37714
37715
37716
37717
37718
37719
37720
37721
37722
37723
37724
37725
37726
37727
37728
37729
37730
37731
37732
37733
37734
37735
37736
37737
37738
37739
37740
37741
37742
37743
37744
37745
37746
37747
37748
37749
37750
37751
37752
37753
37754
37755
37756
37757
37758
37759
37760
37761
37762
37763
37764
37765
37766
37767
37768
37769
37770
37771
37772
37773
37774
37775
37776
37777
37778
37779
37780
37781
37782
37783
37784
37785
37786
37787
37788
37789
37790
37791
37792
37793
37794
37795
37796
37797
37798
37799
37800
37801
37802
37803
37804
37805
37806
37807
37808
37809
37810
37811
37812
37813
37814
37815
37816
37817
37818
37819
37820
37821
37822
37823
37824
37825
37826
37827
37828
37829
37830
37831
37832
37833
37834
37835
37836
37837
37838
37839
37840
37841
37842
37843
37844
37845
37846
37847
37848
37849
37850
37851
37852
37853
37854
37855
37856
37857
37858
37859
37860
37861
37862
37863
37864
37865
37866
37867
37868
37869
37870
37871
37872
37873
37874
37875
37876
37877
37878
37879
37880
37881
37882
37883
37884
37885
37886
37887
37888
37889
37890
37891
37892
37893
37894
37895
37896
37897
37898
37899
37900
37901
37902
37903
37904
37905
37906
37907
37908
37909
37910
37911
37912
37913
37914
37915
37916
37917
37918
37919
37920
37921
37922
37923
37924
37925
37926
37927
37928
37929
37930
37931
37932
37933
37934
37935
37936
37937
37938
37939
37940
37941
37942
37943
37944
37945
37946
37947
37948
37949
37950
37951
37952
37953
37954
37955
37956
37957
37958
37959
37960
37961
37962
37963
37964
37965
37966
37967
37968
37969
37970
37971
37972
37973
37974
37975
37976
37977
37978
37979
37980
37981
37982
37983
37984
37985
37986
37987
37988
37989
37990
37991
37992
37993
37994
37995
37996
37997
37998
37999
38000
38001
38002
38003
38004
38005
38006
38007
38008
38009
38010
38011
38012
38013
38014
38015
38016
38017
38018
38019
38020
38021
38022
38023
38024
38025
38026
38027
38028
38029
38030
38031
38032
38033
38034
38035
38036
38037
38038
38039
38040
38041
38042
38043
38044
38045
38046
38047
38048
38049
38050
38051
38052
38053
38054
38055
38056
38057
38058
38059
38060
38061
38062
38063
38064
38065
38066
38067
38068
38069
38070
38071
38072
38073
38074
38075
38076
38077
38078
38079
38080
38081
38082
38083
38084
38085
38086
38087
38088
38089
38090
38091
38092
38093
38094
38095
38096
38097
38098
38099
38100
38101
38102
38103
38104
38105
38106
38107
38108
38109
38110
38111
38112
38113
38114
38115
38116
38117
38118
38119
38120
38121
38122
38123
38124
38125
38126
38127
38128
38129
38130
38131
38132
38133
38134
38135
38136
38137
38138
38139
38140
38141
38142
38143
38144
38145
38146
38147
38148
38149
38150
38151
38152
38153
38154
38155
38156
38157
38158
38159
38160
38161
38162
38163
38164
38165
38166
38167
38168
38169
38170
38171
38172
38173
38174
38175
38176
38177
38178
38179
38180
38181
38182
38183
38184
38185
38186
38187
38188
38189
38190
38191
38192
38193
38194
38195
38196
38197
38198
38199
38200
38201
38202
38203
38204
38205
38206
38207
38208
38209
38210
38211
38212
38213
38214
38215
38216
38217
38218
38219
38220
38221
38222
38223
38224
38225
38226
38227
38228
38229
38230
38231
38232
38233
38234
38235
38236
38237
38238
38239
38240
38241
38242
38243
38244
38245
38246
38247
38248
38249
38250
38251
38252
38253
38254
38255
38256
38257
38258
38259
38260
38261
38262
38263
38264
38265
38266
38267
38268
38269
38270
38271
38272
38273
38274
38275
38276
38277
38278
38279
38280
38281
38282
38283
38284
38285
38286
38287
38288
38289
38290
38291
38292
38293
38294
38295
38296
38297
38298
38299
38300
38301
38302
38303
38304
38305
38306
38307
38308
38309
38310
38311
38312
38313
38314
38315
38316
38317
38318
38319
38320
38321
38322
38323
38324
38325
38326
38327
38328
38329
38330
38331
38332
38333
38334
38335
38336
38337
38338
38339
38340
38341
38342
38343
38344
38345
38346
38347
38348
38349
38350
38351
38352
38353
38354
38355
38356
38357
38358
38359
38360
38361
38362
38363
38364
38365
38366
38367
38368
38369
38370
38371
38372
38373
38374
38375
38376
38377
38378
38379
38380
38381
38382
38383
38384
38385
38386
38387
38388
38389
38390
38391
38392
38393
38394
38395
38396
38397
38398
38399
38400
38401
38402
38403
38404
38405
38406
38407
38408
38409
38410
38411
38412
38413
38414
38415
38416
38417
38418
38419
38420
38421
38422
38423
38424
38425
38426
38427
38428
38429
38430
38431
38432
38433
38434
38435
38436
38437
38438
38439
38440
38441
38442
38443
38444
38445
38446
38447
38448
38449
38450
38451
38452
38453
38454
38455
38456
38457
38458
38459
38460
38461
38462
38463
38464
38465
38466
38467
38468
38469
38470
38471
38472
38473
38474
38475
38476
38477
38478
38479
38480
38481
38482
38483
38484
38485
38486
38487
38488
38489
38490
38491
38492
38493
38494
38495
38496
38497
38498
38499
38500
38501
38502
38503
38504
38505
38506
38507
38508
38509
38510
38511
38512
38513
38514
38515
38516
38517
38518
38519
38520
38521
38522
38523
38524
38525
38526
38527
38528
38529
38530
38531
38532
38533
38534
38535
38536
38537
38538
38539
38540
38541
38542
38543
38544
38545
38546
38547
38548
38549
38550
38551
38552
38553
38554
38555
38556
38557
38558
38559
38560
38561
38562
38563
38564
38565
38566
38567
38568
38569
38570
38571
38572
38573
38574
38575
38576
38577
38578
38579
38580
38581
38582
38583
38584
38585
38586
38587
38588
38589
38590
38591
38592
38593
38594
38595
38596
38597
38598
38599
38600
38601
38602
38603
38604
38605
38606
38607
38608
38609
38610
38611
38612
38613
38614
38615
38616
38617
38618
38619
38620
38621
38622
38623
38624
38625
38626
38627
38628
38629
38630
38631
38632
38633
38634
38635
38636
38637
38638
38639
38640
38641
38642
38643
38644
38645
38646
38647
38648
38649
38650
38651
38652
38653
38654
38655
38656
38657
38658
38659
38660
38661
38662
38663
38664
38665
38666
38667
38668
38669
38670
38671
38672
38673
38674
38675
38676
38677
38678
38679
38680
38681
38682
38683
38684
38685
38686
38687
38688
38689
38690
38691
38692
38693
38694
38695
38696
38697
38698
38699
38700
38701
38702
38703
38704
38705
38706
38707
38708
38709
38710
38711
38712
38713
38714
38715
38716
38717
38718
38719
38720
38721
38722
38723
38724
38725
38726
38727
38728
38729
38730
38731
38732
38733
38734
38735
38736
38737
38738
38739
38740
38741
38742
38743
38744
38745
38746
38747
38748
38749
38750
38751
38752
38753
38754
38755
38756
38757
38758
38759
38760
38761
38762
38763
38764
38765
38766
38767
38768
38769
38770
38771
38772
38773
38774
38775
38776
38777
38778
38779
38780
38781
38782
38783
38784
38785
38786
38787
38788
38789
38790
38791
38792
38793
38794
38795
38796
38797
38798
38799
38800
38801
38802
38803
38804
38805
38806
38807
38808
38809
38810
38811
38812
38813
38814
38815
38816
38817
38818
38819
38820
38821
38822
38823
38824
38825
38826
38827
38828
38829
38830
38831
38832
38833
38834
38835
38836
38837
38838
38839
38840
38841
38842
38843
38844
38845
38846
38847
38848
38849
38850
38851
38852
38853
38854
38855
38856
38857
38858
38859
38860
38861
38862
38863
38864
38865
38866
38867
38868
38869
38870
38871
38872
38873
38874
38875
38876
38877
38878
38879
38880
38881
38882
38883
38884
38885
38886
38887
38888
38889
38890
38891
38892
38893
38894
38895
38896
38897
38898
38899
38900
38901
38902
38903
38904
38905
38906
38907
38908
38909
38910
38911
38912
38913
38914
38915
38916
38917
38918
38919
38920
38921
38922
38923
38924
38925
38926
38927
38928
38929
38930
38931
38932
38933
38934
38935
38936
38937
38938
38939
38940
38941
38942
38943
38944
38945
38946
38947
38948
38949
38950
38951
38952
38953
38954
38955
38956
38957
38958
38959
38960
38961
38962
38963
38964
38965
38966
38967
38968
38969
38970
38971
38972
38973
38974
38975
38976
38977
38978
38979
38980
38981
38982
38983
38984
38985
38986
38987
38988
38989
38990
38991
38992
38993
38994
38995
38996
38997
38998
38999
39000
39001
39002
39003
39004
39005
39006
39007
39008
39009
39010
39011
39012
39013
39014
39015
39016
39017
39018
39019
39020
39021
39022
39023
39024
39025
39026
39027
39028
39029
39030
39031
39032
39033
39034
39035
39036
39037
39038
39039
39040
39041
39042
39043
39044
39045
39046
39047
39048
39049
39050
39051
39052
39053
39054
39055
39056
39057
39058
39059
39060
39061
39062
39063
39064
39065
39066
39067
39068
39069
39070
39071
39072
39073
39074
39075
39076
39077
39078
39079
39080
39081
39082
39083
39084
39085
39086
39087
39088
39089
39090
39091
39092
39093
39094
39095
39096
39097
39098
39099
39100
39101
39102
39103
39104
39105
39106
39107
39108
39109
39110
39111
39112
39113
39114
39115
39116
39117
39118
39119
39120
39121
39122
39123
39124
39125
39126
39127
39128
39129
39130
39131
39132
39133
39134
39135
39136
39137
39138
39139
39140
39141
39142
39143
39144
39145
39146
39147
39148
39149
39150
39151
39152
39153
39154
39155
39156
39157
39158
39159
39160
39161
39162
39163
39164
39165
39166
39167
39168
39169
39170
39171
39172
39173
39174
39175
39176
39177
39178
39179
39180
39181
39182
39183
39184
39185
39186
39187
39188
39189
39190
39191
39192
39193
39194
39195
39196
39197
39198
39199
39200
39201
39202
39203
39204
39205
39206
39207
39208
39209
39210
39211
39212
39213
39214
39215
39216
39217
39218
39219
39220
39221
39222
39223
39224
39225
39226
39227
39228
39229
39230
39231
39232
39233
39234
39235
39236
39237
39238
39239
39240
39241
39242
39243
39244
39245
39246
39247
39248
39249
39250
39251
39252
39253
39254
39255
39256
39257
39258
39259
39260
39261
39262
//! Concord v2 service — the stateful orchestration binding the pure v2 modules
//! to storage + transport. Free functions, `std::sync::Arc<crate::db::Session>`-gated at every write
//! (a `swap_session` can land at any await — see CLAUDE.md).
//!
//! Signing + NIP-44 flow through the active [`VectorSigner`](crate::signer::VectorSigner) (`active_signer()`):
//! the live client's signer for a NIP-46 bunker / NIP-55 offline account, else the
//! local vault. Every identity op in v2 is `sign_event` / `nip44_encrypt` /
//! `nip44_decrypt` — a remote signer's whole surface — so create, send, join,
//! invite, moderate, rotate, and refound all work keylessly (CORD-06 D1/D5 made the
//! rekey locator public + its blobs pairwise NIP-44, so there is no raw-ECDH
//! exception).

use nostr_sdk::prelude::{Event, Keys, PublicKey, Timestamp};

use super::super::transport::{Query, Transport};
use super::super::{version, ChannelId, Epoch};
use super::chat::{self, ChatEvent};
use super::community::{ChannelV2, CommunityV2};
use super::control;
use super::derive::{base_rekey_group_key, channel_group_key, channel_rekey_group_key, GroupKey};
use super::invite::{self, CommunityInvite};
use super::rekey::{self, Continuity, RekeyScope};
use super::{guestbook, stream, vsk};
use crate::community::edition::ParsedEdition;

mod audit;
pub use audit::{audit_log, AuditEntry, AuditLog};
mod inspect;
pub use inspect::{inspect_bundle, inspect_public_link, InspectedChannel, InspectedMessage, InspectedPlane, Inspection, MessageRead};
mod relocate;
pub use relocate::{check_relays, move_relays, RelayCheck, RelayMove, RETIRED_RELAY_GRACE_MS};
pub(crate) use relocate::{clean_relays, relays_moved, resume_relay_copy, retired_relays};
pub(crate) use audit::{note_moderation_delete, note_voice_directive};
mod outbox;
pub use outbox::{confirm_in, discard_unconfirmed, retry_unconfirmed};
mod purge;
mod writing;
mod sealing;
mod control_store;
mod control_sync;
mod guestbook_reads;
mod guestbook_store;
mod plane_store;
pub use writing::{can_post, collect_writers, outbound_rumor, WriterDuty};
pub(crate) use writing::live_writer as live_writer_of;
pub(crate) use writing::{owe_if_departed, retract_by, hold as writing_hold, judge_arrival, rejudge_held, owe_if_moved, rejudge_page, retract_since, writers_head, sort_arrival, Arrival, Judge};

/// The active signer for v2 authority actions: the live client's signer — which
/// covers a NIP-46 bunker / NIP-55 offline signer — falling back to the local
/// vault keys when there is no client or no signer attached (local accounts,
/// headless/CLI paths, and tests). Every v2 seal, rekey blob, and control edition
/// signs / NIP-44-wraps through this, so a keyless account can create AND
/// administer a community. v2's rekey locator is public + its blobs are pairwise
/// NIP-44 (CORD-06 D1/D5), so there is no raw-ECDH exception.
/// The active identity's public key for addressing/tags — authoritative (set at
/// login), no signer round-trip. Used everywhere v2 needs "who am I" so a keyless
/// account (empty vault) still resolves its own identity.
fn me_pk() -> Result<PublicKey, String> {
    crate::state::my_public_key().ok_or_else(|| "no active identity".to_string())
}

pub(crate) fn now_ms() -> u64 {
    crate::clock::now_ms()
}

/// `now_ms`, but never twice the same value in this process.
///
/// Ordering is by the `ms` tag, and two sends can finish inside one millisecond
/// — so a sender's own back-to-back messages carried IDENTICAL stamps and fell
/// through to the reader's tiebreak, which is content-derived and therefore
/// indifferent to which was typed first. Bumping past the last stamp keeps a
/// single sender's sequence self-consistent; readers still tiebreak across
/// senders. Drifts at most a few ms ahead of the clock under a burst, and only
/// until the clock catches up.
fn next_send_ms() -> u64 {
    use std::sync::atomic::{AtomicU64, Ordering};
    static LAST: AtomicU64 = AtomicU64::new(0);
    let now = now_ms();
    // fetch_update: its rename, try_update, is newer than the toolchains Vector builds with.
    #[allow(deprecated)]
    let prev = LAST.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |last| Some(now.max(last + 1)));
    prev.map(|last| now.max(last + 1)).unwrap_or(now)
}

/// Create a fresh v2 community owned by the local identity: mint the genesis
/// (self-certifying id + the two owner editions), persist, publish the genesis
/// control editions, and announce the owner's Guestbook Join. Returns the saved
/// community.
/// A new Community on Roles v2 from the start (CORD-04 §2): `@everyone` holds the defaults and the
/// genesis Channel is all the switch lists. A switch that can't land leaves it on the legacy Roster,
/// which the owner can still move from.
pub async fn create_community_on_roles_v2<T: Transport + ?Sized>(
    transport: &T,
    name: &str,
    relays: Vec<String>,
    description: Option<String>,
) -> Result<CommunityV2, String> {
    let community = create_community(transport, name, relays, description).await?;
    let mut last = String::new();
    for _ in 0..2 {
        match activate_roles_v2(transport, &community, super::roles::EVERYONE_DEFAULT).await {
            Ok(_) => {
                let _ = follow_control(transport, &community).await;
                return Ok(crate::db::community::load_community_v2(community.id())?.unwrap_or(community));
            }
            Err(e) => last = e,
        }
    }
    crate::log_warn!("[v2:create] the new community stays on the legacy roles: {last}");
    Ok(community)
}

pub async fn create_community<T: Transport + ?Sized>(
    transport: &T,
    name: &str,
    relays: Vec<String>,
    description: Option<String>,
) -> Result<CommunityV2, String> {
    crate::db::scoped(async move {
        let signer = crate::signer::active_signer()?;
        let owner_pk = me_pk()?;
        let at_ms = now_ms();

        let meta = control::CommunityMetadata {
            name: name.to_string(),
            description: description.clone(),
            relays: relays.clone(),
            ..Default::default()
        };
        let genesis = control::genesis_signed(owner_pk, &signer, meta, at_ms / 1000).await.map_err(|e| e.to_string())?;
        let community = CommunityV2::from_genesis(&genesis, name, description, relays.clone(), at_ms);

        // Save-before-publish: no peers exist yet so there's no
        // shared view to diverge from, and the fresh-random keys are irrecoverable
        // if a publish hiccup rolled them back. Re-check the session after the genesis
        // signing await (a bunker signs over the network) before the DB write.
        // Seed the genesis edition heads (v1) as the owner's refuse-downgrade floor, so a
        // later edit can't be rolled back by a relay serving only the genesis prefix. The
        // live control sub is replay-free (limit 0), so the owner won't re-fold its own
        // genesis to seed the floor otherwise. Floors land BEFORE the community row
        // (floors-then-state ordering).
        let control = control::ControlPlane::of(&community);
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        for wrap in &genesis.wraps {
            if let Ok(ed) = control.open_edition(wrap) {
                let entity_hex = crate::simd::hex::bytes_to_hex_32(&ed.entity_id);
                crate::db::community::set_family_head_at_epoch(&cid_hex, &entity_hex, ed.version, &ed.self_hash, &ed.inner_id, &ed.author.to_bytes(), community.root_epoch.0, floor_family(&ed.vsk))?;
            }
        }
        crate::db::community::save_community_v2(&community)?;
        // Archive the genesis root at epoch 0, so a later Refounding leaves this epoch's
        // Public-channel history readable (CORD-03 §3 multi-epoch read).
        let _ = crate::db::community::store_epoch_key(&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX, community.root_epoch.0, &community.community_root);

        // Publish the two genesis control editions at the epoch-0 control plane.
        // Durable, not single-shot: over a slow transport (Tor) one attempt is a coin
        // flip, and a lost genesis leaves a community that exists only locally. Durable
        // races every relay, returns on the first ACK, then heals stragglers in the bg.
        for wrap in &genesis.wraps {
            transport.publish_durable(wrap, &community.relays).await?;
            hold_wrap(&community, wrap);
        }

        // Announce the owner's Guestbook Join so they appear in the memberlist. Relays are
        // proven-alive by the genesis ACK above, so durable here just guarantees the owner's
        // own join lands (member count) without a real block risk.
        let gb_group = super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
        let join_rumor = guestbook::build_join_rumor(owner_pk, None, at_ms);
        if let Ok((join_wrap, _)) = guestbook::seal_guestbook_rumor_signed(&signer, owner_pk, &join_rumor, &gb_group, Timestamp::from_secs(at_ms / 1000)).await {
            if transport.publish_durable(&join_wrap, &community.relays).await.is_ok() {
                if let Ok(entry) = stream::open_wrap(&join_wrap, &gb_group).map_err(|e| e.to_string()).and_then(|o| guestbook::parse_guestbook_event(&o).map_err(|e| e.to_string())) {
                    if ingest_guestbook_event(&community, entry, join_wrap.created_at.as_secs()).is_ok() {
                        hold_guestbook_wrap(&community, &join_wrap);
                    }
                }
            }
        }

        // Sync the new membership across devices (CORD-02 §8), durably — see the join path.
        match republish_community_list(transport, Some(community.id())).await {
            Ok(true) => {}
            Ok(false) => republish_community_list_durable(Some(*community.id())),
            Err(e) => {
                crate::log_warn!("[CommunityList] failed to record this community across devices ({}) — retrying", e);
                republish_community_list_durable(Some(*community.id()));
            }
        }
        Ok(community)
    })
    .await
}

/// Send a text message to a channel. Derives the channel's Chat-Plane group key
/// (community_root for a Public channel, the channel key for a Private one),
/// seals it encrypted, and publishes. Returns the message's rumor id (hex).
pub async fn send_message<T: Transport + ?Sized>(
    transport: &T,
    community: &CommunityV2,
    channel_id: &ChannelId,
    content: &str,
) -> Result<String, String> {
    send_chat_message(transport, community, channel_id, content, None, &[], vec![]).await
}

/// Full chat send: threaded reply (NIP-C7 `q`, the parent's `(rumor_id, author)`
/// hex pair), NIP-30 custom-emoji pairs, and verbatim extra tags (NIP-92 `imeta`
/// attachments). Returns the message's rumor id (hex).
pub async fn send_chat_message<T: Transport + ?Sized>(
    transport: &T,
    community: &CommunityV2,
    channel_id: &ChannelId,
    content: &str,
    reply_to: Option<(&str, &str)>,
    emoji: &[(&str, &str)],
    extra_tags: Vec<nostr_sdk::prelude::Tag>,
) -> Result<String, String> {
    send_chat_message_at(transport, community, channel_id, content, reply_to, emoji, extra_tags, next_send_ms()).await
}

/// [`send_chat_message`] with an explicit event time. The rumor id is a pure
/// function of its inputs, so a GUI that picks `at_ms` can precompute the id for
/// its optimistic pending row — the in-process echo and the finalize then key
/// the SAME id (the pending → sent contract).
#[allow(clippy::too_many_arguments)]
pub async fn send_chat_message_at<T: Transport + ?Sized>(
    transport: &T,
    community: &CommunityV2,
    channel_id: &ChannelId,
    content: &str,
    reply_to: Option<(&str, &str)>,
    emoji: &[(&str, &str)],
    extra_tags: Vec<nostr_sdk::prelude::Tag>,
    at_ms: u64,
) -> Result<String, String> {
    let (author_pk, group, epoch) = chat_send_context(community, channel_id)?;
    refuse_while_timed_out(community, &author_pk)?;
    // An honest client posts only where it holds Send Messages (CORD-04 §8).
    let roster = crate::db::community::get_community_roles(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap_or_default();
    let owner = community.owner().ok().map(|o| o.to_hex());
    if roster.everyone.is_some()
        && !roster
            .channel_permissions(owner.as_deref(), &author_pk.to_hex(), &crate::simd::hex::bytes_to_hex_32(&channel_id.0), community.channel(channel_id).is_some_and(|c| c.private))
            .contains(crate::community::roles::Permissions::SEND_MESSAGES)
    {
        return Err("you can't send messages in this channel".to_string());
    }
    let rumor = chat::build_message_rumor(author_pk, channel_id, epoch, content, reply_to, emoji, extra_tags, at_ms);
    publish_chat(transport, community, &group, author_pk, channel_id, epoch, rumor, at_ms, false).await
}

/// A member timed out doesn't post, edit or react until it ends (CORD-04 §8).
fn refuse_while_timed_out(community: &CommunityV2, author: &PublicKey) -> Result<(), String> {
    match community_timeouts(community)?.get(author) {
        Some((_, until)) => Err(format!("you're timed out here until {until}")),
        None => Ok(()),
    }
}

/// Refuse a reaction the Roster doesn't let `author` make in `channel_id`: readers don't count
/// it. Nothing to judge on the legacy roster.
fn refuse_unless_reacting(community: &CommunityV2, channel_id: &ChannelId, author: &PublicKey) -> Result<(), String> {
    use crate::community::roles::Permissions;
    let roster = crate::db::community::get_community_roles(&crate::simd::hex::bytes_to_hex_32(&community.id().0))?;
    if roster.everyone.is_none() {
        return Ok(());
    }
    let ch = community.channel(channel_id).ok_or("no such channel in this community")?;
    let held = roster.channel_permissions(Some(&community.owner()?.to_hex()), &author.to_hex(), &crate::simd::hex::bytes_to_hex_32(&channel_id.0), ch.private);
    if held.contains(Permissions::ADD_REACTIONS) { Ok(()) } else { Err("you can't react in this channel".to_string()) }
}

/// React to a channel message (kind 7, NIP-25 shape). `target_id_hex` /
/// `target_author_hex` name the reacted-to message; `target_kind` is its rumor
/// kind (`kind::MESSAGE`, or `kind::COMMENT` for a threaded reply); `emoji`
/// carries the NIP-30 pair when `emoji_content` is a custom `:shortcode:`.
#[allow(clippy::too_many_arguments)]
pub async fn send_reaction<T: Transport + ?Sized>(
    transport: &T,
    community: &CommunityV2,
    channel_id: &ChannelId,
    target_id_hex: &str,
    target_author_hex: &str,
    target_kind: u16,
    emoji_content: &str,
    emoji: Option<(&str, &str)>,
) -> Result<String, String> {
    let (author_pk, group, epoch) = chat_send_context(community, channel_id)?;
    refuse_while_timed_out(community, &author_pk)?;
    refuse_unless_reacting(community, channel_id, &author_pk)?;
    let at_ms = next_send_ms();
    let rumor =
        chat::build_reaction_rumor(author_pk, channel_id, epoch, target_id_hex, target_author_hex, target_kind, emoji_content, emoji, at_ms);
    publish_chat(transport, community, &group, author_pk, channel_id, epoch, rumor, at_ms, false).await
}

/// Edit one of your own messages (kind 3302): peers re-render `target_id_hex`
/// with the replacement text. Author-enforced on the read side — only the
/// original author's edit folds. Carries the target's own expiry, if it has one.
pub async fn send_edit<T: Transport + ?Sized>(
    transport: &T,
    community: &CommunityV2,
    channel_id: &ChannelId,
    target_id_hex: &str,
    new_content: &str,
    emoji: &[(&str, &str)],
) -> Result<String, String> {
    send_edit_tagged(transport, community, channel_id, target_id_hex, new_content, emoji, Vec::new()).await
}

/// [`send_edit`] carrying extra tags verbatim (the edit's colour spans).
pub async fn send_edit_tagged<T: Transport + ?Sized>(
    transport: &T,
    community: &CommunityV2,
    channel_id: &ChannelId,
    target_id_hex: &str,
    new_content: &str,
    emoji: &[(&str, &str)],
    extra_tags: Vec<nostr_sdk::prelude::Tag>,
) -> Result<String, String> {
    let (author_pk, group, epoch) = chat_send_context(community, channel_id)?;
    refuse_while_timed_out(community, &author_pk)?;
    let expiration = crate::self_destruct::edit_expiry(target_id_hex).await?;
    let at_ms = next_send_ms();
    let rumor = chat::build_edit_rumor_tagged(author_pk, channel_id, epoch, target_id_hex, new_content, emoji, expiration, extra_tags, at_ms);
    publish_chat(transport, community, &group, author_pk, channel_id, epoch, rumor, at_ms, false).await
}

/// Cooperative in-plane delete (kind 5, NIP-09 semantics): peers stop rendering
/// `target_id_hex`, and relays drop it at `expiration`. The wrap itself leaves relays
/// separately, by the keys kept for it ([`crate::community::message_delete::scrub_own`]).
pub async fn send_delete<T: Transport + ?Sized>(
    transport: &T,
    community: &CommunityV2,
    channel_id: &ChannelId,
    target_id_hex: &str,
    target_kind: u16,
    expiration: Option<u64>,
) -> Result<String, String> {
    let (author_pk, group, epoch) = chat_send_context(community, channel_id)?;
    let at_ms = next_send_ms();
    let rumor = chat::build_delete_rumor_until(author_pk, channel_id, epoch, target_id_hex, target_kind, at_ms, None, expiration);
    let id = publish_chat(transport, community, &group, author_pk, channel_id, epoch, rumor, at_ms, false).await?;
    // §7: deleting one's own pinned message obliges the immediate omitting
    // edition. Hooked HERE and not only at ingest — the local delete drops the
    // row before the relay echo returns, so the echo can't re-authorize and
    // the ingest hook never sees an own delete.
    let ch_hex = crate::simd::hex::bytes_to_hex_32(&channel_id.0);
    spawn_pin_duty(&ch_hex, target_id_hex, None);
    Ok(id)
}

/// Delete my own message (or reaction) in `channel_id`: its wraps off the relays by the keys
/// kept for them, then the in-plane delete, which leaves relays in time once their copies are
/// gone everywhere.
pub async fn delete_own<T: Transport + ?Sized>(
    transport: &T,
    community: &CommunityV2,
    channel_id: &ChannelId,
    target_id_hex: &str,
    target_kind: u16,
) -> Result<String, String> {
    // Asked first: scrubbing the relay copy for a delete that can't be sent splits what readers see.
    let (_, read, _) = chat_send_context(community, channel_id)?;
    if let Some(ch) = community.channel(channel_id) {
        writing::send_group(community, ch, &read, super::kind::DELETE)?;
    }
    let scrubbed = crate::community::message_delete::scrub_own(transport, &community.relays, target_id_hex)
        .await
        .unwrap_or_else(|e| {
            crate::log_warn!("[Community] relay delete of {target_id_hex} failed, in-plane delete only: {e}");
            Default::default()
        });
    let expiration = crate::community::message_delete::in_plane_delete_expiry(target_id_hex, scrubbed).await;
    send_delete(transport, community, channel_id, target_id_hex, target_kind, expiration).await
}

/// Moderation-hide: remove SOMEONE ELSE's message under `MANAGE_MESSAGES`
/// (CORD-04 §3/§5). Same kind-5 the author's own delete uses — CORD defines no
/// separate hide, the authority is what differs, and every reader re-derives it
/// from the seal's real npub against the folded Roster.
///
/// Gated locally against the same predicate peers enforce, so the button can't
/// promise what the plane will refuse; a non-owner cites the Grant it acts under.
/// `target_author` comes from the caller's resident copy — you can only moderate
/// a message you can see.
pub async fn moderation_delete<T: Transport + ?Sized>(
    transport: &T,
    community: &CommunityV2,
    channel_id: &ChannelId,
    target_id_hex: &str,
    target_kind: u16,
    target_author: &PublicKey,
) -> Result<String, String> {
    let (author_pk, group, epoch) = chat_send_context(community, channel_id)?;
    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
    if crate::db::community::get_community_dissolved(&cid_hex).unwrap_or(false) {
        return Err("this community is dissolved — it accepts no new moderation actions".to_string());
    }
    let owner_hex = community.owner()?.to_hex();
    let roster = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
    let private = community.channel(channel_id).is_some_and(|c| c.private);
    if !crate::community::moderation::can_hide_in_channel(
        Some(&owner_hex),
        &roster,
        &author_pk.to_hex(),
        &target_author.to_hex(),
        &crate::simd::hex::bytes_to_hex_32(&channel_id.0),
        private,
    ) {
        return Err("you can't hide that message in this channel".to_string());
    }
    let at_ms = next_send_ms();
    let citation = required_authority_citation(community, &author_pk)?;
    let rumor = chat::build_delete_rumor(author_pk, channel_id, epoch, target_id_hex, target_kind, at_ms, citation.as_ref());
    let id = publish_chat(transport, community, &group, author_pk, channel_id, epoch, rumor, at_ms, false).await?;
    // §7: a moderation-hide of a pinned message obliges the omission too, and
    // the moderator here provably holds the bit's neighbourhood (MANAGE_MESSAGES
    // curators usually hold PIN_MESSAGES); the duty itself re-checks.
    let ch_hex = crate::simd::hex::bytes_to_hex_32(&channel_id.0);
    spawn_pin_duty(&ch_hex, target_id_hex, None);
    Ok(id)
}

/// WebXDC realtime peer signal (kind 3310): the shared content shape, sealed on the
/// channel's chat plane, DURABLE (a reopening peer backfills a recent ad).
/// Signed by the member's real identity — a member can't forge another
/// player's presence. Failure is non-fatal to callers (the next re-advertise
/// covers a missed ad).
pub async fn send_webxdc_signal<T: Transport + ?Sized>(
    transport: &T,
    community: &CommunityV2,
    channel_id: &ChannelId,
    topic_id: &str,
    node_addr: Option<&str>,
) -> Result<(), String> {
    let (author_pk, group, epoch) = chat_send_context(community, channel_id)?;
    let at_ms = now_ms();
    let content = crate::webxdc::peer_signal_content(topic_id, node_addr);
    let rumor = chat::build_webxdc_rumor(author_pk, channel_id, epoch, &content, vec![], at_ms);
    publish_chat(transport, community, &group, author_pk, channel_id, epoch, rumor, at_ms, false).await.map(|_| ())
}

/// Voice presence (CORD-07 §4): `Some(endpoint)` is a `joined` heartbeat over iroh, None a `left`.
/// Ephemeral, at the Channel's read address: being in a call is CONNECT, whatever its writers.
pub async fn send_voice_presence<T: Transport + ?Sized>(
    transport: &T,
    community: &CommunityV2,
    channel_id: &ChannelId,
    endpoint: Option<([u8; 32], Option<String>)>,
    showing: super::voice::Showing,
) -> Result<(), String> {
    let (author_pk, group, epoch) = chat_send_context(community, channel_id)?;
    let at_ms = now_ms();
    let rumor = chat::build_voice_presence_rumor(author_pk, channel_id, epoch, endpoint.as_ref().map(|(e, r)| (e, r.as_deref())), showing, at_ms);
    publish_chat(transport, community, &group, author_pk, channel_id, epoch, rumor, at_ms, true).await?;
    let channel = crate::simd::hex::bytes_to_hex_32(&channel_id.0);
    super::voice::note(&channel, author_pk, at_ms, super::voice::Heard::announcing(endpoint, showing), at_ms);
    Ok(())
}

/// The mutes and deafens this device stands behind, per (Channel, target): re-sent whenever the
/// target comes back into the call, since a directive lasts only while they stay (CORD-07 §7).
struct StandingDirectives;
type Standing = std::collections::HashMap<(String, PublicKey), std::collections::BTreeSet<super::voice::Directive>>;

fn standing_directives() -> std::sync::Arc<std::sync::Mutex<Standing>> {
    crate::db::current_session().scoped::<StandingDirectives, _>()
}

/// Mute, deafen, move or disconnect `target` in a voice Channel's call (CORD-07 §7): the signer
/// holds the directive's bit and strictly outranks them, judged on today's Roster.
pub async fn send_voice_directive<T: Transport + ?Sized>(
    transport: &T,
    community: &CommunityV2,
    channel_id: &ChannelId,
    target: &PublicKey,
    directive: super::voice::Directive,
    to: Option<[u8; 32]>,
) -> Result<(), String> {
    use super::voice::Directive;
    let (author_pk, group, epoch) = chat_send_context(community, channel_id)?;
    let cid = crate::simd::hex::bytes_to_hex_32(&community.id().0);
    let owner = community.owner()?.to_hex();
    let roles = crate::db::community::get_community_roles(&cid).unwrap_or_default();
    let me = author_pk.to_hex();
    if !((me == owner && target.to_hex() != owner) || roles.can_act_on_member(&me, Some(&owner), &target.to_hex(), directive.permission())) {
        return Err("you can't do that to this member".into());
    }
    if directive == Directive::Move && to.is_none_or(|t| !community.channels.iter().any(|c| c.id.0 == t && c.view() == super::community::ChannelView::Voice)) {
        return Err("move them to a voice channel".into());
    }
    let at_ms = now_ms();
    let rumor = chat::build_voice_directive_rumor(author_pk, channel_id, epoch, target, directive, to.as_ref(), my_authority_citation(community, &author_pk).as_ref(), at_ms);
    let id = publish_chat(transport, community, &group, author_pk, channel_id, epoch, rumor, at_ms, true).await?;
    let channel = crate::simd::hex::bytes_to_hex_32(&channel_id.0);
    note_voice_directive(&cid, &id, at_ms, &me, &target.to_hex(), &channel, directive, to.as_ref());
    super::voice::apply_directive(&channel, target, directive, at_ms, at_ms);
    let standing = standing_directives();
    let mut held = standing.lock().unwrap_or_else(|e| e.into_inner());
    let set = held.entry((channel, *target)).or_default();
    match directive {
        Directive::Mute => {
            set.insert(Directive::Mute);
        }
        Directive::Unmute => {
            set.remove(&Directive::Mute);
        }
        Directive::Deafen => {
            set.insert(Directive::Deafen);
        }
        Directive::Undeafen => {
            set.remove(&Directive::Deafen);
        }
        Directive::Move | Directive::Disconnect => set.clear(),
    }
    Ok(())
}

/// A newer lift from any moderator ends what this device stood behind: re-asserting it on the
/// target's return would undo a decision made after ours.
pub(crate) fn yield_voice_directive(channel_hex: &str, target: &PublicKey, directive: super::voice::Directive) {
    use super::voice::Directive;
    let lifted = match directive {
        Directive::Unmute => Directive::Mute,
        Directive::Undeafen => Directive::Deafen,
        _ => return,
    };
    if let Some(set) = standing_directives().lock().unwrap_or_else(|e| e.into_inner()).get_mut(&(channel_hex.to_string(), *target)) {
        set.remove(&lifted);
    }
}

/// Re-send what this device stands behind against `target`, now back in the call.
pub fn reassert_voice_directives(community: &CommunityV2, channel_hex: &str, target: &PublicKey) {
    let standing: Vec<super::voice::Directive> = standing_directives()
        .lock()
        .unwrap_or_else(|e| e.into_inner())
        .get(&(channel_hex.to_string(), *target))
        .map(|s| s.iter().copied().collect())
        .unwrap_or_default();
    if standing.is_empty() || !crate::rt::can_spawn() {
        return;
    }
    let (community, target) = (community.clone(), *target);
    let Some(channel) = crate::community::id32_from_hex(channel_hex).map(ChannelId) else { return };
    crate::db::spawn_bound(async move {
        let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
        for d in standing {
            if let Err(e) = send_voice_directive(&transport, &community, &channel, &target, d, None).await {
                crate::log_warn!("[voice] re-asserting a {} failed: {e}", d.as_str());
            }
        }
    });
}

/// Ephemeral typing indicator (kind 23311 in a 21059 wrap — relays never store it).
pub async fn send_typing<T: Transport + ?Sized>(
    transport: &T,
    community: &CommunityV2,
    channel_id: &ChannelId,
) -> Result<(), String> {
    let (author_pk, group, epoch) = chat_send_context(community, channel_id)?;
    let at_ms = now_ms();
    let rumor = chat::build_typing_rumor(author_pk, channel_id, epoch, at_ms);
    publish_chat(transport, community, &group, author_pk, channel_id, epoch, rumor, at_ms, true).await.map(|_| ())
}

/// Everything a chat-plane send needs: local keys, the channel's group key +
/// epoch, and the session snapshot taken BEFORE any await. Refuses a dissolved
/// community (every honest member sealed it read-only) and a keyless Private
/// channel — deriving from the root would post to the public plane; its key
/// arrives over the rekey plane.
fn chat_send_context(community: &CommunityV2, channel_id: &ChannelId) -> Result<(PublicKey, GroupKey, Epoch), String> {
    let author_pk = me_pk()?;
    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
    if crate::db::community::get_community_dissolved(&cid_hex).unwrap_or(false) {
        return Err("this community has been dissolved".to_string());
    }
    // A self-ban: every honest peer drops our events (CORD-04 §4) and the send
    // echo would silently no-op, so fail loudly instead of a message that seems
    // to send but shows up nowhere.
    if crate::db::community::get_community_banlist(&cid_hex).unwrap_or_default().contains(&author_pk.to_hex()) {
        return Err("you are banned from this community".to_string());
    }
    let ch = community.channel(channel_id).ok_or("no such channel in this community")?;
    if ch.private && ch.key.is_none() {
        return Err("this private channel has no key yet (awaiting rekey delivery)".to_string());
    }
    let (secret, epoch) = community.channel_secret(ch);
    Ok((author_pk, channel_group_key(&secret, channel_id, epoch), epoch))
}

/// Seal one chat rumor, publish, and echo the send into the
/// shared store. Returns the rumor id (hex).
#[allow(clippy::too_many_arguments)]
/// §7: an OWN edit must refresh its pinned target's proof bundle from the SEND
/// side — the relay echo of an own send deduplicates against the local echo, so
/// the ingest hook never sees it (send_delete's omission duty, same reason).
/// Without this the author's pin lags behind their message while everyone
/// else's follows. Returns the duty's arguments when the echo applied an edit.
fn own_echo_pin_duty(
    outcome: &super::inbound::ChatPersist,
    event: &ChatEvent,
) -> Option<(String, super::stream::OpenedStream)> {
    match (outcome, event) {
        (super::inbound::ChatPersist::Updated { .. }, ChatEvent::Edit { opened, target, .. }) => {
            Some((crate::simd::hex::bytes_to_hex_32(target), opened.clone()))
        }
        _ => None,
    }
}

#[allow(clippy::too_many_arguments)]
async fn publish_chat<T: Transport + ?Sized>(
    transport: &T,
    community: &CommunityV2,
    group: &GroupKey,
    author_pk: PublicKey,
    channel_id: &ChannelId,
    epoch: Epoch,
    rumor: nostr_sdk::prelude::UnsignedEvent,
    at_ms: u64,
    ephemeral: bool,
) -> Result<String, String> {
    crate::db::scoped(async move {
        let ch = community.channel(channel_id).ok_or("no such channel in this community")?;
        let (sending, wepoch) = writing::send_group(community, ch, group, rumor.kind.as_u16())?;
        let group = &sending;
        let rumor = match wepoch {
            Some(w) => writing::as_writer(community, ch, rumor, w),
            None => rumor,
        };
        let rumor_event_id = rumor.id.ok_or("rumor has no id")?;
        let rumor_id = rumor_event_id.to_hex();
        let owner = if ephemeral {
            Keys::generate()
        } else {
            crate::community::message_delete::own_wrap_owner(&author_pk, &group.pk(), &rumor_event_id)
        };
        let signer = crate::signer::active_signer()?;
        let wrap = chat::seal_chat_rumor_signed(&signer, author_pk, &rumor, group, Timestamp::from_secs(at_ms / 1000), ephemeral, &owner.public_key()).await
            .map_err(|e| e.to_string())?;
        // Both keys that can delete this wrap, frozen per message so a later rekey can't
        // strand them: its owner for relays following CORD-01, the plane key for the rest.
        // Kept before the publish: an unconfirmed send may still have landed.
        if !ephemeral {
            crate::db::community::store_wrap_owner(&rumor_id, &wrap.id.to_hex(), &owner, &community.relays)?;
            crate::db::community::store_message_key(&rumor_id, &wrap.id.to_hex(), group.keys(), &community.relays)?;
        }
        // Reactions are left out: one that lands long after the user moved on surprises.
        let kept = !ephemeral
            && matches!(rumor.kind.as_u16(), super::kind::MESSAGE | super::kind::COMMENT | super::kind::EDIT | super::kind::DELETE);
        if kept {
            outbox::keep(&rumor_id, &wrap);
        }
        if let Err(e) = transport.publish(&wrap, &community.relays).await {
            // No relay answered, which is not the same as none taking it: ask before failing.
            if !outbox::on_relays(transport, group.keys(), &wrap, &community.relays).await {
                if kept {
                    outbox::resend_later(rumor_id.clone());
                }
                return Err(e);
            }
        }
        if kept {
            outbox::release(&rumor_id);
        }
        // Local echo: open our OWN wrap through the exact inbound path so
        // send-then-read works with no listen loop, and the relay's re-delivery dedups
        // against this row instead of re-firing callbacks. Best-effort — the publish
        // already succeeded. Ephemeral kinds (typing) apply to nothing and skip out.
        if !ephemeral {
            let echo = match wepoch {
                Some(w) => chat::open_writer_chat_event(&wrap, &group.pk(), w, group.conv_key(), channel_id, epoch),
                None => chat::open_chat_event(&wrap, group, channel_id, epoch),
            };
            if let Ok(event) = echo {
                let channel_hex = crate::simd::hex::bytes_to_hex_32(&channel_id.0);
                super::inbound::hydrate_target(&event, &channel_hex).await;
                let outcome = {
                    let mut st = crate::state::STATE.lock().await;
                    super::inbound::apply_chat_to_state(&mut st, &event, &channel_hex, &author_pk)
                };
                if let Some(outcome) = outcome {
                    super::inbound::persist_chat(&channel_hex, &outcome).await;
                    if let Some((target_hex, opened)) = own_echo_pin_duty(&outcome, &event) {
                        spawn_pin_duty(&channel_hex, &target_hex, Some(opened));
                    }
                }
            }
        }
        Ok(rumor_id)
    })
    .await
}

/// A chat event opened from a channel fetch, tagged with the epoch its key
/// decrypted under.
pub struct FetchedEvent {
    pub event: ChatEvent,
    pub epoch: Epoch,
    /// The wrap it came in, so a later judgment can hold it.
    pub wrap: Option<nostr_sdk::prelude::Event>,
}

/// Keep the delete keys of an OWN wrap met on a relay: one sent from another device or
/// before they were kept. The UI caches full-vs-limited verdicts per message, so one that
/// just became fully deletable is told to re-resolve.
pub(crate) fn heal_own_wrap_key(event: &ChatEvent, wrap: &nostr_sdk::prelude::Event, plane: Option<&Keys>, relays: &[String]) {
    if crate::community::message_delete::heal_own_wrap(event, wrap, plane, relays) {
        crate::traits::emit_event("message_delete_meta_changed", &serde_json::json!({ "id": event.opened().rumor_id.to_hex() }));
    }
}

/// The key that signed `wrap` in `channel_id`, at its live read plane or a writer address,
/// when this device holds it.
pub(crate) fn plane_key_of(community: &CommunityV2, channel_id: &ChannelId, wrap: &nostr_sdk::prelude::Event) -> Option<Keys> {
    let ch = community.channel(channel_id)?;
    let (secret, epoch) = community.channel_secret(ch);
    let group = channel_group_key(&secret, &ch.id, epoch);
    if group.pk() == wrap.pubkey {
        return Some(group.keys().clone());
    }
    let (wepoch, ..) = ch.writers.as_ref()?.writers().find(|(_, pk, _)| *pk == wrap.pubkey.to_bytes())?;
    writing::writer_keys_at(community, ch, wepoch, &wrap.pubkey)
}

/// The most pages holding messages dated ahead one history read steps past for free.
const MAX_EARLY_PAGES: usize = 20;

/// Whether `event` is a message dated ahead of this device, now held for its time
/// ([`crate::early`]) instead of joining the page.
fn early_message(event: &ChatEvent, wrap: &nostr_sdk::prelude::Event) -> bool {
    let early = matches!(event, ChatEvent::Message { .. }) && crate::early::is_early(event.opened().at_ms);
    if early {
        crate::early::hold(wrap.clone(), crate::early::Via::Community, event.opened().at_ms);
    }
    early
}

/// One epoch a channel read covers: keyed, or a past epoch held read-only (CORD-03 §5).
enum ReadPlane {
    Keyed(GroupKey),
    View(PublicKey, nostr_sdk::prelude::nip44::v2::ConversationKey),
    /// A root plane a Private Channel used while it was public, which stands only for what was
    /// sent there before the Channel went private (unix ms).
    Public(GroupKey, u64),
}

impl ReadPlane {
    fn address(&self) -> PublicKey {
        match self {
            ReadPlane::Keyed(group) | ReadPlane::Public(group, _) => group.pk(),
            ReadPlane::View(address, _) => *address,
        }
    }

    fn conv(&self) -> &nostr_sdk::prelude::nip44::v2::ConversationKey {
        match self {
            ReadPlane::Keyed(group) | ReadPlane::Public(group, _) => group.conv_key(),
            ReadPlane::View(_, conv) => conv,
        }
    }

    /// The key a gated relay authenticates this plane by, when this device holds it.
    fn group(&self) -> Option<&GroupKey> {
        match self {
            ReadPlane::Keyed(group) | ReadPlane::Public(group, _) => Some(group),
            ReadPlane::View(..) => None,
        }
    }

    /// Whether an event sent at `at_ms` stands on this plane.
    fn holds(&self, at_ms: u64) -> bool {
        match self {
            ReadPlane::Public(_, until) => at_ms < *until,
            _ => true,
        }
    }

    fn open(&self, wrap: &Event, channel_id: &ChannelId, epoch: Epoch) -> Option<chat::ChatEvent> {
        let opened = match self {
            ReadPlane::Keyed(group) | ReadPlane::Public(group, _) => chat::open_chat_event(wrap, group, channel_id, epoch),
            ReadPlane::View(address, conv) => chat::open_chat_event_at(wrap, address, conv, channel_id, epoch),
        };
        opened.ok().filter(|ev| self.holds(ev.opened().at_ms))
    }
}

/// Every read plane this device holds for `ch`, with its epoch: a Public Channel's under every
/// held root, a Private one's under its own keys and the past epochs it may only read.
fn read_planes(community: &CommunityV2, ch: &ChannelV2) -> Vec<(ReadPlane, Epoch)> {
    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
    let coords: Vec<([u8; 32], Epoch)> = if ch.private {
        let Some(current) = ch.key else {
            return Vec::new();
        };
        let ch_hex = crate::simd::hex::bytes_to_hex_32(&ch.id.0);
        let mut held = crate::db::community::held_epoch_keys(&cid_hex, &ch_hex).unwrap_or_default();
        if !held.iter().any(|(ep, _)| *ep == ch.epoch) {
            held.push((ch.epoch, current));
        }
        // Only real grants are archived, but keep the invariant local: a private
        // plane is never read with the root value.
        held.into_iter().filter(|(_, k)| *k != community.community_root).map(|(ep, k)| (k, ep)).collect()
    } else {
        let mut roots = crate::db::community::held_epoch_keys(&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX).unwrap_or_default();
        if !roots.iter().any(|(ep, _)| *ep == community.root_epoch) {
            roots.push((community.root_epoch, community.community_root));
        }
        roots.into_iter().map(|(ep, root)| (root, ep)).collect()
    };
    let mut planes: Vec<(ReadPlane, Epoch)> = coords.into_iter().map(|(secret, epoch)| (ReadPlane::Keyed(channel_group_key(&secret, &ch.id, epoch)), epoch)).collect();
    if ch.private {
        // Past epochs delivered read-only with Read Message History (CORD-03 §5).
        let ch_hex = crate::simd::hex::bytes_to_hex_32(&ch.id.0);
        for (epoch, view) in crate::db::community::history_views(&cid_hex, &ch_hex).unwrap_or_default() {
            if planes.iter().any(|(_, e)| *e == epoch) {
                continue;
            }
            if let Ok(address) = PublicKey::from_slice(&view.address) {
                planes.push((ReadPlane::View(address, nostr_sdk::prelude::nip44::v2::ConversationKey::new(view.conv_key)), epoch));
            }
        }
        // What it said while public is its history too, read at the roots it used (CORD-03 §2).
        if let Some(until) = ch.public_until() {
            let mut roots = crate::db::community::held_epoch_keys(&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX).unwrap_or_default();
            if !roots.iter().any(|(ep, _)| *ep == community.root_epoch) {
                roots.push((community.root_epoch, community.community_root));
            }
            planes.extend(roots.into_iter().map(|(ep, root)| (ReadPlane::Public(channel_group_key(&root, &ch.id, ep), until), ep)));
        }
    }
    // The earlier planes its metadata publishes, last, so a live plane of the same epoch number
    // sorts ahead of them.
    for (epoch, group) in ch.published_history() {
        if !planes.iter().any(|(p, _)| p.address() == group.pk()) {
            planes.push((ReadPlane::Keyed(group), epoch));
        }
    }
    planes
}

/// Open `wrap` as a post in `ch` under `planes`, with the writer epoch whose address carried it.
fn open_on_planes(ch: &ChannelV2, planes: &[(ReadPlane, Epoch)], wrap: &Event) -> Option<(chat::ChatEvent, Option<Epoch>)> {
    if let Some((wepoch, ..)) = ch.writers.as_ref().and_then(|l| l.writers().find(|(_, pk, _)| *pk == wrap.pubkey.to_bytes())) {
        return planes.iter().find_map(|(plane, epoch)| chat::open_writer_chat_event(wrap, &wrap.pubkey, wepoch, plane.conv(), &ch.id, *epoch).ok().filter(|ev| plane.holds(ev.opened().at_ms))).map(|ev| (ev, Some(wepoch)));
    }
    let (plane, epoch) = planes.iter().find(|(p, _)| p.address() == wrap.pubkey)?;
    plane.open(wrap, &ch.id, *epoch).map(|ev| (ev, None))
}

/// How many of the newest held epochs a newest-first catch-up reads. One: a
/// rotation moves the conversation, so the live epoch is where it is. Rotated-past
/// epochs are reached by back-paging, when a reader actually scrolls for them.
const LIVE_COORD_EPOCHS: usize = 1;

/// Fetch a channel's newest messages — one page of [`fetch_channel_history`].
/// `limit` is one relay-side bound across the whole epoch-author OR-set, not
/// per epoch; deeper history pages backwards via the walk.
pub async fn fetch_channel<T: Transport + ?Sized>(
    transport: &T,
    community: &CommunityV2,
    channel_id: &ChannelId,
    limit: usize,
) -> Result<Vec<FetchedEvent>, String> {
    fetch_channel_history(transport, community, channel_id, limit, 1, None, None, crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await
}

/// Walk a channel's history newest-first (CORD-03 §3 "clients load a Channel
/// newest-first and paginate backwards"), querying every held epoch's Chat-Plane
/// address one `page`-sized query at a time until `max_pages`, a drained relay,
/// or `keep_paging` returns false for a page (the caller's "I already hold
/// these" early stop — consulted only on pages that opened something, so junk
/// at the address can't fake exhaustion). Pages step by INCLUSIVE `until` with
/// wrap-id dedup, so a page boundary landing mid-second can't skip siblings; a
/// full page of only-already-seen wraps is a same-second WALL (relay filters
/// are second-granular) and steps past it accepting that unseen same-second
/// siblings beyond the relay cap are unreachable — logged, and a protocol-level
/// limitation (the `ms` tag can't be filtered server-side).
///
/// Returns everything opened, deduped by rumor id, oldest→newest; `settled` wraps are not
/// opened and not returned.
#[allow(clippy::too_many_arguments)]
pub async fn fetch_channel_history<T: Transport + ?Sized>(
    transport: &T,
    community: &CommunityV2,
    channel_id: &ChannelId,
    page: usize,
    max_pages: usize,
    since: Option<u64>,
    // Unix-seconds upper bound for the FIRST page (inclusive) — the back-paging
    // cursor. `None` starts at the newest.
    start_until: Option<u64>,
    evidence: crate::community::transport::Evidence,
    // Given a page's opened events and how many of its wraps were `settled`.
    keep_paging: impl FnMut(&[FetchedEvent], usize) -> bool,
    // Of a page's wraps, those the caller already holds in full: skipped unopened, and counted
    // for `keep_paging`.
    settled: impl Fn(&[nostr_sdk::prelude::EventId]) -> std::collections::HashSet<nostr_sdk::prelude::EventId>,
) -> Result<Vec<FetchedEvent>, String> {
    let mut keep_paging = keep_paging;
    fetch_channel_history_paged(transport, community, channel_id, page, max_pages, since, start_until, evidence, |p, s, _| keep_paging(p, s), settled).await.map(|(events, ..)| events)
}

/// Whether a catch-up pages on past this page: while it holds a message we don't (`held` by
/// rumor id), or no message at all (reactions and edits decide nothing), or only held messages
/// but the next page (`next`) still starts above `floor`. Held rows up there may have arrived
/// live over a stretch nothing read.
pub fn catch_up_pages_on(page: &[FetchedEvent], settled: usize, next: Option<u64>, floor: Option<u64>, held: impl Fn(&str) -> bool) -> bool {
    let mut saw_message = settled > 0;
    for f in page {
        if matches!(&f.event, ChatEvent::Message { .. }) {
            saw_message = true;
            if !held(&f.event.opened().rumor_id.to_hex()) {
                return true;
            }
        }
    }
    !saw_message || floor.zip(next).is_some_and(|(f, n)| n > f)
}

/// [`fetch_channel_history`], with where to page on from (Unix seconds) when it stopped with
/// addresses still unread: every row it returns is at or above that, so a caller that pages
/// from there skips nothing, even after a page whose rows were all dropped. `keep_paging` is
/// also told where the next page would start (None: this one wasn't full, so none follows).
/// Last, whether every relay answered every plane read: only then is an absence proven.
#[allow(clippy::too_many_arguments)]
pub async fn fetch_channel_history_paged<T: Transport + ?Sized>(
    transport: &T,
    community: &CommunityV2,
    channel_id: &ChannelId,
    page: usize,
    max_pages: usize,
    since: Option<u64>,
    start_until: Option<u64>,
    evidence: crate::community::transport::Evidence,
    keep_paging: impl FnMut(&[FetchedEvent], usize, Option<u64>) -> bool,
    settled: impl Fn(&[nostr_sdk::prelude::EventId]) -> std::collections::HashSet<nostr_sdk::prelude::EventId>,
) -> Result<(Vec<FetchedEvent>, Option<u64>, bool), String> {
    fetch_channel_history_since_epoch(transport, community, channel_id, page, max_pages, since, start_until, evidence, keep_paging, settled, None, &[]).await
}

/// [`fetch_channel_history_paged`], where a newest-first walk also reads the Channel's epochs from
/// `past.0` up: the one a proof was read under from `since`, and each later one from `past.1`,
/// since no walk read those; and so too each published plane at an address in `unread`.
#[allow(clippy::too_many_arguments)]
pub async fn fetch_channel_history_since_epoch<T: Transport + ?Sized>(
    transport: &T,
    community: &CommunityV2,
    channel_id: &ChannelId,
    page: usize,
    max_pages: usize,
    since: Option<u64>,
    start_until: Option<u64>,
    evidence: crate::community::transport::Evidence,
    mut keep_paging: impl FnMut(&[FetchedEvent], usize, Option<u64>) -> bool,
    settled: impl Fn(&[nostr_sdk::prelude::EventId]) -> std::collections::HashSet<nostr_sdk::prelude::EventId>,
    past: Option<(Epoch, Option<u64>)>,
    unread: &[PublicKey],
) -> Result<(Vec<FetchedEvent>, Option<u64>, bool), String> {
    crate::db::scoped(async move {
        // Guards the opportunistic scrub-key heals below — the fetch loop straddles
        // network I/O, and an account swap must not write into the new account's DB.
        let ch = community.channel(channel_id).ok_or("no such channel in this community")?;
        // A Public channel reads across EVERY held base-root epoch, and a Private one
        // across its OWN held epochs (CORD-03 §3), so history spanning a rotation stays
        // continuous either way. A keyless Private channel is unreadable — never derived
        // from the root (that would address the public plane).
        let mut planes = read_planes(community, ch);
        if planes.is_empty() {
            return Ok((Vec::new(), None, true));
        }
        // Every epoch is its own address on this plane, so the full set costs one
        // fetch per held epoch per page and grows with the community's whole
        // rotation history. A newest-first catch-up wants the live epoch, which is
        // the only one anyone should be speaking on; reaching back through a
        // rotation is what back-paging (`start_until`) is for — the same division
        // the boot volley already draws.
        // A restricted Channel's writer addresses, opened under the read epochs above: those whose
        // window reaches what this read covers, or for a first look the live one and the one it closed.
        let windows: Vec<(PublicKey, Epoch, u64, Option<u64>)> = ch
            .writers
            .iter()
            .flat_map(|l| l.writers().map(move |(e, pk, end)| (e, pk, l.writer_start(e).unwrap_or(0), end)))
            .filter_map(|(e, pk, start, end)| PublicKey::from_slice(&pk).ok().map(|a| (a, e, start, end)))
            .collect();
        let mut writer_planes: Vec<(PublicKey, Epoch)> = match (start_until, since) {
            // A slow clock dates a post a little before its window opened.
            (Some(u), _) => windows.iter().filter(|w| w.2.saturating_sub(super::writers::HORIZON_MS) <= u.saturating_mul(1000)).map(|w| (w.0, w.1)).collect(),
            (None, Some(s)) => windows.iter().filter(|w| w.3.is_none_or(|end| end > s.saturating_mul(1000))).map(|w| (w.0, w.1)).collect(),
            (None, None) => windows.iter().map(|w| (w.0, w.1)).collect(),
        };
        if start_until.is_none() && since.is_none() {
            writer_planes.sort_by_key(|(_, e)| std::cmp::Reverse(e.0));
            writer_planes.truncate(2);
        }
        let live_writer = writing::live_writer(community, ch);
        let mut whole: std::collections::HashSet<PublicKey> = std::collections::HashSet::new();
        if start_until.is_none() {
            // Root epochs and the Channel's own count apart, so each keeps its newest.
            let (mut public, rest): (Vec<_>, Vec<_>) = planes.into_iter().partition(|(p, _)| matches!(p, ReadPlane::Public(..)));
            let (fresh, mut own): (Vec<_>, Vec<_>) = rest.into_iter().partition(|(p, _)| unread.contains(&p.address()));
            public.sort_by_key(|(_, e)| std::cmp::Reverse(e.0));
            public.truncate(LIVE_COORD_EPOCHS);
            own.sort_by_key(|(_, e)| std::cmp::Reverse(e.0));
            let kept = past.map_or(0, |(from, _)| own.iter().filter(|(_, e)| e.0 >= from.0).count());
            own.truncate(kept.max(LIVE_COORD_EPOCHS));
            if let Some((from, _)) = past {
                whole = own.iter().filter(|(_, e)| e.0 > from.0).map(|(p, _)| p.address()).collect();
            }
            whole.extend(fresh.iter().map(|(p, _)| p.address()));
            planes = own.into_iter().chain(fresh).chain(public).collect();
        }

        // The writers' rules judge what arrives: what they don't stand behind reaches only managers.
        let judge = writing::Judge::of(community, ch);
        // Below a seal the read address is read by the ids it names, never by date; above it, by
        // date in the stretches it took things in, never inside a quiet one.
        let seal = ch.writers.as_ref().and_then(|l| l.seal.clone());
        let mut walk = seal.as_ref().map(|s| sealing::SealWalk::new(s, start_until.map_or(u64::MAX, |u| u.saturating_mul(1000).saturating_add(999))));
        let mut seen_wraps: std::collections::HashSet<nostr_sdk::prelude::EventId> = std::collections::HashSet::new();
        // Read by date in seconds, a stretch's floor second also holds what was dated below it:
        // that stands only as the seal names it, and is read again when the seal does.
        let mut sealed_ids: std::collections::HashSet<nostr_sdk::prelude::EventId> = std::collections::HashSet::new();
        let mut unsealed: std::collections::HashSet<nostr_sdk::prelude::EventId> = std::collections::HashSet::new();
        let below_seal = |at_ms: u64| seal.as_ref().is_some_and(|s| at_ms < s.until);
        let mut seen_rumors = std::collections::HashSet::new();
        let mut out: Vec<(u64, FetchedEvent)> = Vec::new();
        let mut until: Option<u64> = start_until;
        let mut ended = false;
        let mut complete = true;
        let (mut pages_left, mut early_pages) = (max_pages, 0usize);
        while pages_left > 0 {
            pages_left -= 1;
            let mut early = 0usize;
            // Each address pages on its own: the next page starts below the newest bottom of the
            // ones that came back full, so a busy address never pushes a quiet one past a gap.
            let mut full_oldest: Option<u64> = None;
            let mut note_page = |evs: &[Event]| {
                if evs.len() >= page {
                    full_oldest = full_oldest.max(evs.iter().map(|e| e.created_at.as_secs()).min());
                }
            };
            // Fetch each held epoch's Chat-Plane AUTHED AS that plane key. AUTH-gating
            // relays (Ditto) require the connection authed as the author queried and
            // reject a multi-author REQ ("all authors must be authenticated"), so a
            // single merged fetch returns nothing there — the latest messages under a
            // freshly-adopted epoch never load. Per-plane authed fetches + union.
            let mut wraps: Vec<Event> = Vec::new();
            let mut wrap_ids: std::collections::HashSet<nostr_sdk::prelude::EventId> = std::collections::HashSet::new();
            // An empty page means drained only when a relay said so: silence everywhere is not the start.
            let mut answered = false;
            // The read address's stretch at or below this page's top, and where it goes on below it.
            let top_ms = until.map_or_else(now_ms, |u| u.saturating_mul(1000).saturating_add(999));
            let range = match ch.writers.as_ref() {
                Some(l) => l.read_range(top_ms),
                None => Some((0, top_ms)),
            };
            let (read_on, read_until) = match range {
                Some((_, t)) => (true, if t >= top_ms { until } else { Some(t / 1000) }),
                None => (false, until),
            };
            let read_since = since.max(range.map(|(f, _)| f / 1000).filter(|f| *f > 0));
            let whole_since = past.and_then(|(_, s)| s).max(range.map(|(f, _)| f / 1000).filter(|f| *f > 0));
            let below = range.and_then(|(f, _)| (f > 0).then(|| (f / 1000).checked_sub(1)).flatten()).filter(|b| since.is_none_or(|s| s <= *b));
            let mut read_full = false;
            let lowest_since = if whole.is_empty() { read_since } else { read_since.min(whole_since) };
            let read_planes_here: &[(ReadPlane, Epoch)] = if read_on && !lowest_since.zip(read_until).is_some_and(|(s, u)| s > u) { &planes } else { &[] };
            for (plane, _) in read_planes_here {
                let since = if whole.contains(&plane.address()) { whole_since } else { read_since };
                let q = Query { since, evidence, ..plane_page(plane.address().to_hex(), page, read_until) };
                // A read view holds no key to authenticate as the plane, so it asks plainly.
                let fetched = match plane.group() {
                    Some(group) => transport.fetch_plane(group.keys(), &q, &community.relays).await.map(|f| {
                        complete &= f.is_complete();
                        f.events
                    }),
                    None => transport.fetch(&q, &community.relays).await,
                };
                complete &= fetched.is_ok();
                if let Ok(evs) = fetched {
                    answered = true;
                    read_full |= evs.len() >= page;
                    note_page(&evs);
                    for e in evs {
                        if wrap_ids.insert(e.id) {
                            wraps.push(e);
                        }
                    }
                }
            }
            for (address, wepoch) in &writer_planes {
                let q = Query { since, evidence, ..plane_page(address.to_hex(), page, until) };
                // Only a writer can authenticate as the address.
                let fetched = match &live_writer {
                    Some((e, _, group)) if e == wepoch => transport.fetch_plane(group.keys(), &q, &community.relays).await.map(|f| {
                        complete &= f.is_complete();
                        f.events
                    }),
                    _ => transport.fetch(&q, &community.relays).await,
                };
                complete &= fetched.is_ok();
                let Ok(fetched) = fetched else { continue };
                answered = true;
                note_page(&fetched);
                for e in fetched {
                    if wrap_ids.insert(e.id) {
                        wraps.push(e);
                    }
                }
            }
            // A stretch run dry hands on to the one below it, or to the seal, rather than ending
            // the walk; below the seal its ids page on with the rest.
            let hand_on = below.filter(|_| !read_full);
            full_oldest = full_oldest.max(hand_on);
            let mut seal_on: Option<u64> = None;
            if let (Some(w), Some(s)) = (walk.as_mut(), seal.as_ref()) {
                if !read_on && since.is_none_or(|f| f.saturating_mul(1000) < s.until) && !w.done() {
                    match w.next(transport, community, ch, page).await {
                        Ok(step) => {
                            // A page owed and not served leaves what lies past it unread, not absent.
                            complete &= !w.broken();
                            let mut by_plane: Vec<(PublicKey, Vec<[u8; 32]>)> = Vec::new();
                            for (id, address) in step.ids {
                                match by_plane.iter_mut().find(|(a, _)| *a == address) {
                                    Some((_, ids)) => ids.push(id),
                                    None => by_plane.push((address, vec![id])),
                                }
                            }
                            for (address, ids) in by_plane {
                                let plane = planes.iter().find(|(p, _)| p.address() == address).and_then(|(p, _)| p.group());
                                match sealing::fetch_ids(transport, community, plane, &ids, evidence).await {
                                    Ok(evs) => {
                                        answered = true;
                                        for e in evs {
                                            sealed_ids.insert(e.id);
                                            if unsealed.remove(&e.id) {
                                                seen_wraps.remove(&e.id);
                                            }
                                            if wrap_ids.insert(e.id) {
                                                wraps.push(e);
                                            }
                                        }
                                    }
                                    Err(_) => complete = false,
                                }
                            }
                            // The walk goes on from its pages' own dates, whatever the ids came back as.
                            if !w.done() {
                                seal_on = step.bottom_ms.map(|b| b / 1000);
                                full_oldest = full_oldest.max(seal_on);
                            }
                        }
                        Err(_) => complete = false,
                    }
                }
            }
            if !answered {
                if out.is_empty() {
                    return Err("no relay answered".into());
                }
                break; // keeps `until` as the cursor: the walk goes on from here next time
            }
            if wraps.is_empty() {
                if let Some(next) = hand_on.or(seal_on) {
                    until = Some(next);
                    continue;
                }
                ended = true;
                break;
            }
            let mut fresh = 0usize;
            let mut held = 0usize;
            let unseen: Vec<_> = wraps.iter().map(|w| w.id).filter(|id| !seen_wraps.contains(id)).collect();
            let settled_here = if unseen.is_empty() { Default::default() } else { settled(&unseen) };
            let mut page_events: Vec<FetchedEvent> = Vec::new();
            // The page's signatures in one batch, each wrap under the keys the loop below opens it
            // with: a writer address under every read epoch (and its own signature checked), a
            // plane's under that plane's. The opens then confirm ids for what the batch vouched for.
            let every_plane: Vec<&nostr_sdk::prelude::nip44::v2::ConversationKey> = planes.iter().map(|(p, _)| p.conv()).collect();
            let to_open: Vec<(&Event, Vec<&nostr_sdk::prelude::nip44::v2::ConversationKey>, bool)> = wraps
                .iter()
                .filter(|w| !seen_wraps.contains(&w.id) && !settled_here.contains(&w.id))
                .filter_map(|w| {
                    if writer_planes.iter().any(|(a, _)| *a == w.pubkey) {
                        return Some((w, every_plane.clone(), true));
                    }
                    planes.iter().find(|(p, _)| p.address() == w.pubkey).map(|(p, _)| (w, vec![p.conv()], false))
                })
                .collect();
            let batch = stream::check_signatures_together(&to_open);
            for wrap in &wraps {
                if !seen_wraps.insert(wrap.id) {
                    continue;
                }
                fresh += 1;
                if settled_here.contains(&wrap.id) {
                    held += 1;
                    continue;
                }
                if let Some((address, wepoch)) = writer_planes.iter().find(|(a, _)| *a == wrap.pubkey) {
                    let opened = planes.iter().find_map(|(plane, epoch)| {
                        chat::open_writer_chat_event(wrap, address, *wepoch, plane.conv(), channel_id, *epoch).ok().filter(|ev| plane.holds(ev.opened().at_ms)).map(|ev| (ev, *epoch))
                    });
                    if opened.as_ref().is_some_and(|(ev, _)| early_message(ev, wrap)) {
                        early += 1;
                        continue;
                    }
                    if let Some((event, epoch)) = opened.and_then(|(ev, e)| writing::judge_arrival(judge.as_ref(), &community.id().0, channel_id, wrap, ev, Some(*wepoch)).map(|ev| (ev, e))) {
                        if seen_rumors.insert(event.opened().rumor_id) {
                            if crate::state::my_public_key() == Some(event.opened().author) {
                                let writer = community.channel(channel_id).and_then(|ch| writing::writer_keys_at(community, ch, *wepoch, address));
                                heal_own_wrap_key(&event, wrap, writer.as_ref(), &community.relays);
                            }
                            page_events.push(FetchedEvent { event, epoch, wrap: Some(wrap.clone()) });
                        }
                    }
                    continue;
                }
                // Select the epoch whose group key authored this wrap (no trial decrypt).
                for (plane, epoch) in &planes {
                    if wrap.pubkey != plane.address() {
                        continue;
                    }
                    let opened = plane.open(wrap, channel_id, *epoch);
                    if opened.as_ref().is_some_and(|ev| below_seal(ev.opened().at_ms)) && !sealed_ids.contains(&wrap.id) {
                        unsealed.insert(wrap.id);
                        break;
                    }
                    if opened.as_ref().is_some_and(|ev| early_message(ev, wrap)) {
                        early += 1;
                        break;
                    }
                    let opened = opened.and_then(|ev| writing::judge_arrival(judge.as_ref(), &community.id().0, channel_id, wrap, ev, None));
                    if let Some(event) = opened {
                        let id = event.opened().rumor_id;
                        if seen_rumors.insert(id) {
                            heal_own_wrap_key(&event, wrap, plane.group().map(GroupKey::keys), &community.relays);
                            page_events.push(FetchedEvent { event, epoch: *epoch, wrap: Some(wrap.clone()) });
                        }
                    }
                    break;
                }
            }
            drop(batch);
            // Messages dated ahead took page slots without joining the page, and their place in
            // it bounds what an older address may show: page again for free, or the caller could
            // read the end of history. Bounded, so a flood of them can't page forever.
            if early > 0 && early_pages < MAX_EARLY_PAGES {
                early_pages += 1;
                pages_left += 1;
            }
            if fresh == 0 {
                // A full page of already-seen wraps: a same-second WALL. Step past it;
                // same-second siblings beyond the relay's cap are unreachable by a
                // second-granular filter. No full page means drained.
                let Some(o) = full_oldest else {
                    ended = true;
                    break;
                };
                if o == 0 {
                    ended = true;
                    break;
                }
                crate::log_warn!("v2: same-second history wall at {o} — stepping past it (messages beyond the relay page cap in that second are unreachable)");
                until = Some(o - 1);
                continue;
            }
            let stop = (!page_events.is_empty() || held > 0) && !keep_paging(&page_events, held, full_oldest);
            out.extend(page_events.into_iter().map(|e| (e.event.opened().at_ms, e)));
            if stop {
                ended = true;
                break; // the caller holds everything from here back.
            }
            // Inclusive — wrap-id dedup absorbs the boundary overlap.
            let Some(next) = full_oldest else {
                ended = true;
                break;
            };
            until = Some(next);
        }
        // Out of pages with addresses still unread below the frontier: what a quieter one gave
        // below it would let a caller paging on from its oldest row skip the rest.
        let cursor = (!ended).then_some(until).flatten();
        if let Some(frontier) = cursor {
            out.retain(|(ms, _)| ms / 1000 >= frontier);
        }
        // Ties break on the content-derived rumor id, so every client orders a
        // same-millisecond pair identically. A bare `ms` sort left ties to whatever
        // order the relay happened to serve across pages, so two readers could show
        // the same two messages in opposite orders.
        out.sort_by(|a, b| {
            a.0.cmp(&b.0)
                .then_with(|| a.1.event.opened().rumor_id.as_bytes().cmp(b.1.event.opened().rumor_id.as_bytes()))
        });
        Ok((out.into_iter().map(|(_, e)| e).collect(), cursor, complete))
    })
    .await
}

// ── Invites (CORD-05) ────────────────────────────────────────────────────────

/// Who an invite bundle is FOR — which decides the Private-Channel keys it may
/// carry (CORD-05 §1 vs §2).
///
/// A **Link** has no recipient: "anyone the link reaches can join", so its
/// audience holds no Role by construction and is entitled to no Private Channel
/// at all. A **Member** is a specific npub whose entitlement is computable.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BundleAudience {
    /// A public link (33301 bundle event): public channels only.
    Link,
    /// A direct invite (3313) to this npub: may carry Private-Channel keys.
    Member(PublicKey),
}

/// Build the §1 invite bundle for this community, scoped to `audience`. A
/// Public channel carries the `community_root` as its "key" (the joiner derives
/// the real secret from the root); a Private one its own key — and only for a
/// Member the folded roster shows entitled. The bundle self-certifies the owner,
/// so the inviter's identity is irrelevant to trust.
pub fn bundle_of(
    community: &CommunityV2,
    audience: BundleAudience,
    creator: Option<PublicKey>,
    expires_at_ms: Option<u64>,
    label: Option<String>,
) -> CommunityInvite {
    bundle_of_with_overlay(community, audience, creator, expires_at_ms, label, &[], &[])
}

/// [`bundle_of`] settling entitlement against a Grant this client JUST published
/// (`with`/`without` role ids), since the fold lags its own publish. This is the
/// grant-vend path (CORD-03 "delivered on grant").
pub fn bundle_of_with_overlay(
    community: &CommunityV2,
    audience: BundleAudience,
    creator: Option<PublicKey>,
    expires_at_ms: Option<u64>,
    label: Option<String>,
    with: &[String],
    without: &[String],
) -> CommunityInvite {
    let hex = crate::simd::hex::bytes_to_hex_32;
    let cid_hex = hex(&community.identity.community_id.0);
    let roster = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
    let owner_hex = community.owner().ok().map(|o| o.to_hex());
    let recipient_hex = match audience {
        BundleAudience::Link => None,
        BundleAudience::Member(pk) => Some(pk.to_hex()),
    };
    let lane = match audience {
        BundleAudience::Link => invite::BundleLane::Link,
        BundleAudience::Member(_) => invite::BundleLane::Direct,
    };
    let channels = community
        .vendable_channels(&roster, owner_hex.as_deref(), recipient_hex.as_deref(), with, without)
        .into_iter()
        .map(|c| invite::ChannelGrant {
            id: hex(&c.id.0),
            key: hex(&c.key.unwrap_or(community.community_root)),
            epoch: c.epoch.0,
            name: c.name.clone(),
        })
        .collect();
    let mut bundle = CommunityInvite {
        community_id: hex(&community.identity.community_id.0),
        owner: hex(&community.identity.owner_xonly),
        owner_salt: hex(&community.identity.owner_salt),
        community_root: hex(&community.community_root),
        root_epoch: community.root_epoch.0,
        // Read access to the Control Plane, never write (CORD-02 §7); absent
        // on a legacy pre-split epoch.
        control_pk: community.control_pk.map(|p| p.to_hex()),
        channels,
        relays: community.relays.clone(),
        name: community.name.clone(),
        // Mint-time snapshot so a parked invite renders the real logo before any
        // fold; the Control Plane stays the authority after joining.
        icon: community.icon.clone(),
        expires_at: expires_at_ms,
        creator_npub: creator.map(|p| p.to_hex()),
        label: invite::clamp_label(label),
        extra: Default::default(),
    };
    bundle.fit(lane);
    bundle
}

/// Gift-wrap a Direct Invite (kind 3313) of this community straight to `recipient`
/// and publish it to the community relays. `expires_at_ms` (unix ms) optionally
/// bounds its shelf life; `label` is echoed in the joiner's Guestbook Join. The
/// bundle hands over the keys; the recipient consents by accepting (nothing joins
/// on receipt). Returns the wrap.
pub async fn send_direct_invite<T: Transport + ?Sized>(
    transport: &T,
    community: &CommunityV2,
    recipient: &PublicKey,
    expires_at_ms: Option<u64>,
    label: Option<String>,
) -> Result<Event, String> {
    crate::db::scoped(async move {
        // A stale bundle is worse than a stale edit: it hands the joiner keys to a
        // buried epoch, and their client later self-evicts on the rekey exclusion.
        assert_current_root(community)?;
        let signer = crate::signer::active_signer()?;
        let inviter_pk = me_pk()?;
        let bundle = bundle_of(community, BundleAudience::Member(*recipient), Some(inviter_pk), expires_at_ms, label);
        let wrap = invite::build_direct_invite_signed(&signer, inviter_pk, recipient, &bundle).await.map_err(|e| e.to_string())?;
        transport.publish(&wrap, &community.relays).await?;
        Ok(wrap)
    })
    .await
}

/// A minted public link: the shareable URL plus the addressable bundle event to
/// publish and the link keypair to retain (in the Invite List) for later refresh
/// or revocation.
#[derive(Clone)]
pub struct MintedLink {
    pub url: String,
    pub bundle_event: Event,
    pub link_signer: Keys,
    pub token: [u8; super::derive::TOKEN_LEN],
    /// Unix ms, mirrored from the bundle. The Invite List is the creator's only
    /// record of it, and the Registry prunes on it — the coordinate a member
    /// folds carries no expiry, so a lapsed link the creator never pruned reads
    /// as a live door forever (CORD-05 §4/§5).
    pub expires_at_ms: Option<u64>,
    pub label: Option<String>,
}

/// Mint a public invite link for this community: a fresh token + link keypair, the
/// bundle encrypted under the token key and published at `(33301, link_signer,
/// "")`, and the `base/invite/<naddr>#<fragment>` URL. `base` is the deep-link
/// domain (e.g. `https://vectorapp.io`); the fragment carries the token + bootstrap
/// relays and never reaches a server.
pub async fn mint_public_link<T: Transport + ?Sized>(
    transport: &T,
    community: &CommunityV2,
    base: &str,
    expires_at_ms: Option<u64>,
    label: Option<String>,
) -> Result<MintedLink, String> {
    crate::db::scoped(async move {
        let minted = publish_public_link(transport, community, base, expires_at_ms, label).await?;
        // Best-effort: the link works without the sync.
        let _ = record_minted_link(transport, community, &minted).await;
        Ok(minted)
    })
    .await
}

/// [`mint_public_link`] for a caller waiting to show the link: it returns once the bundle is
/// durable, and the cross-device record finishes on a task bound to this account.
pub async fn mint_public_link_sync_later(
    community: &CommunityV2,
    base: &str,
    expires_at_ms: Option<u64>,
    label: Option<String>,
) -> Result<MintedLink, String> {
    crate::db::scoped(async move {
        let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
        let minted = publish_public_link(&transport, community, base, expires_at_ms, label).await?;
        if !crate::rt::can_spawn() {
            let _ = record_minted_link(&transport, community, &minted).await;
            return Ok(minted);
        }
        let (community, record) = (community.clone(), minted.clone());
        crate::db::spawn_bound(async move {
            if let Err(e) = record_minted_link(&transport, &community, &record).await {
                crate::log_warn!("[Invites] syncing a new link across devices failed: {e}");
            }
        });
        Ok(minted)
    })
    .await
}

/// Mint and publish a link's bundle, and mirror it locally; the Invite List and Registry are
/// [`record_minted_link`]'s.
async fn publish_public_link<T: Transport + ?Sized>(
    transport: &T,
    community: &CommunityV2,
    base: &str,
    expires_at_ms: Option<u64>,
    label: Option<String>,
) -> Result<MintedLink, String> {
    crate::db::scoped(async move {
        // Readers ignore a registry whose author lacks CREATE_INVITE (it can't even
        // flip the community Public) — refuse before minting a link nobody honors.
        ensure_folded_permission(community, &me_pk()?, crate::community::roles::Permissions::CREATE_INVITE, "minting a public invite link")?;
        let label = invite::clamp_label(label);
        let mut token = [0u8; super::derive::TOKEN_LEN];
        token.copy_from_slice(&super::super::random_32()[..super::derive::TOKEN_LEN]);
        let link_signer = Keys::generate();
        let bundle = bundle_of(community, BundleAudience::Link, Some(me_pk()?), expires_at_ms, label.clone());
        let bundle_key = super::derive::invite_bundle_key(&token);
        let bundle_event = invite::build_bundle_event(&link_signer, &bundle, &bundle_key).map_err(|e| e.to_string())?;
        let url = invite::build_invite_url(base, &link_signer.public_key(), &token, &community.relays).map_err(|e| e.to_string())?;
        let minted = MintedLink { url, bundle_event, link_signer, token, expires_at_ms, label: label.clone() };
        // A link the Invite List can't sync is one no other device can retire: refuse it up front.
        {
            let gate = invite_list_gate();
            let _held = gate.lock().await;
            if let Some(mut list) = fetch_invite_list(transport, &invite_list_relays(community).await).await? {
                list.prune_expired(now_ms());
                list.entries.push(link_entry(community, &minted));
                if !list.fits() {
                    return Err("Too many invite links to sync: revoke some, or let them expire, first".into());
                }
            }
        }

        transport.publish_durable(&minted.bundle_event, &community.relays).await?;
        // Local mirror so `list_public_invites` stays a sync local read;
        // the 13303 list remains the cross-device record.
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let token_hex = crate::simd::hex::bytes_to_hex_16(&minted.token);
        let _ = crate::db::community::save_public_invite(&token_hex, &cid_hex, &minted.url, expires_at_ms.map(|e| e as i64), label.as_deref());
        Ok(minted)
    })
    .await
}

// ── The Invite Registry (vsk 8) + Invite List (13303), CORD-05 §4/§5 ──────────

/// Fetch the creator's own 13303 Invite List from `relays` (newest wins; a
/// decrypt/parse failure is "no news", never a clobber of the local mirror).
/// Transport failure is Err, NOT None: the 13303 is REPLACEABLE, so a caller
/// that mistakes "couldn't reach the relays" for "no list yet" and publishes a
/// fresh one wipes every link minted on other devices. Full evidence for the
/// same reason — this read feeds replaceable-event writes.
async fn fetch_invite_list<T: Transport + ?Sized>(
    transport: &T,
    relays: &[String],
) -> Result<Option<invite::InviteList>, String> {
    Ok(read_invite_list(transport, relays).await?.map(|(l, _)| l))
}

/// Every copy of this account's Invite List (CORD-05 §4) merged, with the newest copy's
/// `created_at`. A copy that won't open is an error, never an empty list: it may hold the only
/// secret of a live link, and a write built without it would lose that link for good.
async fn read_invite_list<T: Transport + ?Sized>(transport: &T, relays: &[String]) -> Result<Option<(invite::InviteList, u64)>, String> {
    read_invite_list_with(transport, relays, true).await
}

/// [`read_invite_list`], `strict` refusing on a copy that won't open (a writer), or skipping it (a reader).
async fn read_invite_list_with<T: Transport + ?Sized>(transport: &T, relays: &[String], strict: bool) -> Result<Option<(invite::InviteList, u64)>, String> {
    let signer = crate::signer::active_signer()?;
    let my_pk = me_pk()?;
    let query = Query {
        kinds: vec![super::kind::INVITE_LIST],
        authors: vec![my_pk.to_hex()],
        limit: Some(16),
        evidence: crate::community::transport::Evidence::Full,
        ..Default::default()
    };
    let events = transport.fetch(&query, relays).await?;
    let mut merged: Option<(invite::InviteList, u64)> = None;
    let mut seen = std::collections::HashSet::new();
    for e in events {
        // A relay may answer with anything signed; only this account's own list is a copy of it.
        if e.pubkey != my_pk || e.kind.as_u16() != super::kind::INVITE_LIST || !seen.insert(e.id) {
            continue;
        }
        let l = match invite::parse_invite_list_event_signed(&signer, my_pk, &e).await {
            Ok(l) => l,
            Err(_) if !strict => continue,
            Err(err) => return Err(format!("a copy of your invite list couldn't be read, so it isn't written over: {err}")),
        };
        let at = e.created_at.as_secs();
        merged = Some(match merged {
            None => (l, at),
            Some((held, newest)) => (invite::merge_invite_lists(held, l), newest.max(at)),
        });
    }
    Ok(merged)
}

/// Where this account's Invite List lives (CORD-05 §4): its own write relays and the stock set,
/// as for the Community List, and the Community's, where earlier builds kept it.
async fn invite_list_relays(community: &CommunityV2) -> Vec<String> {
    let mut set = own_list_relays().await;
    set.extend(invite::stock_relays());
    set.extend(community.relays.iter().cloned());
    set.sort();
    set.dedup();
    set
}

/// Publish this account's Invite List, dated after the newest copy it read.
async fn publish_invite_list<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, list: &invite::InviteList, newest: Option<u64>) -> Result<(), String> {
    let signer = crate::signer::active_signer()?;
    let my_pk = me_pk()?;
    let at = (now_ms() / 1000).max(newest.map_or(0, |n| n + 1));
    let event = invite::build_invite_list_event_at(&signer, my_pk, list, at).await.map_err(|e| e.to_string())?;
    transport.publish(&event, &invite_list_relays(community).await).await
}

/// The creator's LIVE link-signer pubkeys for one community — the Registry's
/// content (CORD-05 §5), derived from the stored link secrets.
///
/// Live means neither tombstoned nor EXPIRED. An expired link cannot be joined
/// (`InviteBundle::expired`, CORD-05 §1), so leaving it in the Registry states
/// a door that isn't there: the aggregate never empties, the community reads
/// Public forever, and every gate hanging off that reading silently inverts.
fn live_signers_for(list: &invite::InviteList, community_id_hex: &str, now_ms: u64) -> Vec<PublicKey> {
    let dead: std::collections::HashSet<&str> = list.tombstones.iter().map(|t| t.token.as_str()).collect();
    list.entries
        .iter()
        .filter(|e| e.community_id == community_id_hex && !dead.contains(e.token.as_str()))
        .filter(|e| e.expires_at_ms().is_none_or(|exp| now_ms <= exp))
        .filter_map(|e| Keys::parse(&e.signer_sk).ok().map(|k| k.public_key()))
        .collect()
}

/// Publish the creator's Registry (vsk-8) edition — their live link signers for this
/// community — so members fold it into the Public/Private source of truth (a
/// non-empty aggregate = Public).
async fn publish_invite_registry<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, __session: &std::sync::Arc<crate::db::Session>, live_signers: &[PublicKey]) -> Result<(), String> {
    let my_pk = me_pk()?;
    let eid = super::derive::invite_links_locator(community.id(), &my_pk.to_bytes());
    let content = invite::build_registry_content(live_signers);
    publish_control_edition(transport, community, vsk::INVITE_LINKS, &eid, &content).await?;
    // Refresh the cache from the PLANE, not from `live_signers`: the column aggregates
    // every creator, so writing only mine would clobber theirs, and a union could never
    // shrink — retiring the last link would leave the community reading Public forever.
    refresh_invite_registry_cache(transport, community).await;
    Ok(())
}

/// Re-fold the whole invite Registry and cache it, so Public/Private stays a sync
/// LOCAL read. Silent no-op when the plane can't be read whole — a partial fold
/// would under-state Public, leaving a live link open behind a ban.
async fn refresh_invite_registry_cache<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) {
    crate::db::scoped(async move {
        let Ok(owner) = community.owner() else { return };
        let Some(editions) = fetch_control_plane_whole(transport, community).await else { return };
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let floors: Floors = crate::db::community::get_all_edition_heads_full(&cid_hex)
            .unwrap_or_default()
            .into_iter()
            .filter(|(_, f)| f.0 == community.root_epoch.0)
            .map(|(entity, f)| (entity, (f.1, f.2, f.3, f.4, f.5)))
            .collect();
        let authority = fold_authority(community, &editions, &floors);
        let sets = live_invite_link_sets(community.id(), &owner.to_hex(), &editions, &authority, &floors);
        let _ = crate::db::community::set_community_invite_registry(&cid_hex, &flatten_link_sets(&sets));
        let _ = crate::db::community::replace_invite_link_sets(&cid_hex, &sets);
    })
    .await
}

/// A minted link's Invite List entry (CORD-05 §4).
fn link_entry(community: &CommunityV2, minted: &MintedLink) -> invite::InviteEntry {
    invite::InviteEntry {
        token: crate::simd::hex::bytes_to_hex_16(&minted.token),
        signer_sk: minted.link_signer.secret_key().to_secret_hex(),
        community_id: crate::simd::hex::bytes_to_hex_32(&community.id().0),
        url: minted.url.clone(),
        label: minted.label.clone(),
        created_at: now_ms() / 1000,
        expires_at: minted.expires_at_ms.map(|ms| ms / 1000),
        epoch: Some(community.root_epoch.0),
        extra: Default::default(),
    }
}

/// Bring this device's list of my public links in line with the Invite List every device writes
/// (CORD-05 §4): a link minted on another joins it, one retired on another leaves it. Returns
/// whether anything changed.
pub async fn adopt_invite_list<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> Result<bool, String> {
    crate::db::scoped(async move {
        let Some(mut list) = fetch_invite_list(transport, &invite_list_relays(community).await).await? else { return Ok(false) };
        list.prune_expired(now_ms());
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let held: std::collections::HashSet<String> = crate::db::community::list_public_invites(&cid_hex)?.into_iter().map(|r| r.token).collect();
        let retired: std::collections::HashSet<&str> = list.tombstones.iter().filter(|t| t.community_id == cid_hex).map(|t| t.token.as_str()).collect();
        let mut changed = false;
        for token in held.iter().filter(|t| retired.contains(t.as_str())) {
            crate::db::community::delete_public_invite(token)?;
            changed = true;
        }
        for e in list.entries.iter().filter(|e| e.community_id == cid_hex && !held.contains(&e.token) && !retired.contains(e.token.as_str())) {
            let expires = e.expires_at_ms().map(|ms| ms as i64);
            crate::db::community::adopt_public_invite(&e.token, &cid_hex, &e.url, expires, e.label.as_deref(), e.created_at as i64)?;
            changed = true;
        }
        Ok(changed)
    })
    .await
}

struct InviteListWrite;

/// Held across each Invite List read-modify-publish: the 13303 is replaceable, so two at once
/// drop one's change, and a revoke must see a link whose record is still in flight.
fn invite_list_gate() -> std::sync::Arc<tokio::sync::Mutex<()>> {
    crate::db::current_session().scoped::<InviteListWrite, _>()
}

/// Record a freshly-minted public link across the creator's devices: append it to the
/// 13303 Invite List and refresh the Registry (CORD-05 §4/§5).
async fn record_minted_link<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, minted: &MintedLink) -> Result<(), String> {
    crate::db::scoped(async move {
        let gate = invite_list_gate();
        let _held = gate.lock().await;
        let session = crate::db::current_session();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let token_hex = crate::simd::hex::bytes_to_hex_16(&minted.token);
        // Err aborts the sync half (the link's bundle already published durably;
        // a retry re-records it) — an unreachable relay set must never be mistaken
        // for "no list yet" and clobber the replaceable 13303. Ok(None) IS a fresh
        // creator's honest first list.
        let (mut list, newest) = read_invite_list(transport, &invite_list_relays(community).await).await?.map_or((Default::default(), None), |(l, n)| (l, Some(n)));
        list.prune_expired(now_ms());
        if !list.entries.iter().any(|e| e.token == token_hex) {
            list.entries.push(link_entry(community, minted));
        }
        publish_invite_list(transport, community, &list, newest).await?;
        let signers = live_signers_for(&list, &cid_hex, now_ms());
        publish_invite_registry(transport, community, &session, &signers).await
    })
    .await
}

/// Revoke a public link by its token hex (CORD-05 §2/§5): re-post its coordinate as a
/// revocation tombstone (retiring the bundle behind the URL, so a fetcher finds the
/// grave), tombstone the Invite List entry, and refresh the Registry. Retiring the
/// LAST live link empties the Registry → the community reads Private (a Refounding is
/// the owner's separate read-cut).
pub async fn revoke_public_link<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, token_hex: &str) -> Result<(), String> {
    crate::db::scoped(async move {
        let gate = invite_list_gate();
        let held = gate.lock().await;
        let session = crate::db::current_session();
        let my_pk = me_pk()?;
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let (mut list, newest) = read_invite_list(transport, &invite_list_relays(community).await).await?.map(|(l, n)| (l, Some(n))).ok_or("no invite list found to revoke from")?;
        let entry = list.entries.iter().find(|e| e.token == token_hex && e.community_id == cid_hex).cloned();
        let Some(entry) = entry else {
            // The list is OURS and was positively fetched; a token it neither vends is a
            // husk — a local row kept past a revocation or privatize performed elsewhere
            // (another device, Armada). The row carries no signer_sk, so no revocation
            // can EVER be built from it: erroring here just leaves an entry the owner can
            // neither use nor remove. Pruning the local record is the only completion.
            // (Ok(None) above still errors — an unreadable list is not proof of absence.)
            let tombstoned = list.tombstones.iter().any(|t| t.token == token_hex && t.community_id == cid_hex);
            crate::log_warn!(
                "[Invites] link {} is not in the fetched invite list ({}) — pruning the local record",
                &token_hex[..token_hex.len().min(8)],
                if tombstoned { "already tombstoned" } else { "retired elsewhere" }
            );
            let _ = crate::db::community::delete_public_invite(token_hex);
            return Ok(());
        };
        // Re-post the bundle coordinate as a revocation tombstone (creator-signed).
        let link_signer = Keys::parse(&entry.signer_sk).map_err(|_| "malformed link signer")?;
        let revocation = invite::build_revocation(&link_signer).map_err(|e| e.to_string())?;
        transport.publish_durable(&revocation, &community.relays).await?;
        // Tombstone the Invite List entry (permanent — a stale device can't resurrect it).
        list.tombstones.push(invite::InviteTombstone::of(&entry));
        list.entries.retain(|e| e.token != token_hex);
        list.prune_expired(now_ms());
        publish_invite_list(transport, community, &list, newest).await?;
        let signers = live_signers_for(&list, &cid_hex, now_ms());
        // Does anyone ELSE still vend a live link? Folded BEFORE our own registry
        // republish: a fold taken after it would race relay propagation and read our
        // own stale (pre-revoke) registry, so the privatize decision would flip to
        // "still public" almost every time. Links are per-creator (CORD-05 §5), so
        // only the other creators' sets matter here — ours is `signers`.
        let others_vend = if signers.is_empty() {
            match fetch_control_plane_whole(transport, community).await {
                Some(editions) => {
                    let floors: Floors = crate::db::community::get_all_edition_heads_full(&cid_hex)
                        .unwrap_or_default()
                        .into_iter()
                        .filter(|(_, f)| f.0 == community.root_epoch.0)
                        .map(|(entity, f)| (entity, (f.1, f.2, f.3, f.4, f.5)))
                        .collect();
                    let owner_hex = community.owner().map(|o| o.to_hex()).unwrap_or_default();
                    let authority = fold_authority(community, &editions, &floors);
                    live_invite_link_sets(community.id(), &owner_hex, &editions, &authority, &floors)
                        .iter()
                        .any(|s| s.creator_hex != my_pk.to_hex())
                }
                // Unreadable plane: assume someone else still vends. Rotating on a
                // guess would burn an epoch (and strand pre-split clients) over a
                // transport blip; the community simply stays public until a read
                // that succeeds says otherwise.
                None => true,
            }
        } else {
            false
        };
        publish_invite_registry(transport, community, &session, &signers).await?;
        let _ = crate::db::community::delete_public_invite(token_hex);
        // Released before the Refounding, which severs links under this same gate.
        drop(held);
        // CORD-06 §3: converting a Public Community to Private is a Refounding
        // trigger. Revoking only stops NEW acquisitions — everyone who already
        // fetched the bundle keeps the `community_root` until it rolls, so without
        // this the community reads Private while every past link-holder retains
        // read access forever.
        //
        // Best-effort and retried, NEVER the revocation's verdict: the tombstone has
        // already landed, and reporting failure here would read as "the link is
        // still live" — the opposite of the truth — while a retry would fail anyway
        // (its list entry is gone). A Refounding needs BAN, so a link creator who
        // holds only CREATE_INVITE legitimately can't rotate; that surfaces as a
        // logged warning, not a broken revoke.
        if signers.is_empty() && !others_vend {
            let mut rotated = false;
            for attempt in 0..3u8 {
                match refound_community(transport, community, &[]).await {
                    Ok(_) => {
                        rotated = true;
                        break;
                    }
                    Err(e) if attempt == 2 => {
                        crate::log_warn!(
                            "[v2] privatizing {} could not rotate the base key ({e}); the community reads Private but everyone who took a link keeps read access until it rotates",
                            &cid_hex[..8.min(cid_hex.len())]
                        );
                        crate::emit_event(
                            "community_privatize_rotation_failed",
                            &serde_json::json!({ "community_id": cid_hex, "error": e }),
                        );
                    }
                    Err(_) => continue,
                }
            }
            if rotated {
                crate::log_info!("[v2] {} privatized: base key rotated so link-joined readers are cut off", &cid_hex[..8.min(cid_hex.len())]);
            }
        }
        Ok(())
    })
    .await
}

// ── Severing containment (CORD-06 Severing Refounding) ──────────────────────

/// Persisted sever marks for a community: `root_epoch -> rotation at_secs`.
/// A mark means "epoch E was a containment": link severance retries against it
/// on every follow pass, and a rescue extension of that hop re-stamps the tag.
pub(crate) fn sever_marks(cid_hex: &str) -> std::collections::BTreeMap<u64, u64> {
    crate::db::settings::get_sql_setting(format!("v2_sever:{cid_hex}"))
        .ok()
        .flatten()
        .and_then(|v| serde_json::from_str(&v).ok())
        .unwrap_or_default()
}

/// Who minted each epoch: `root_epoch -> rotator hex`. CORD-02 §5 honors a
/// Guestbook snapshot "only from the npub whose Refounding minted that epoch",
/// so the fold has to remember which npub that was — the owner is only the
/// answer when the owner did the refounding.
pub(crate) fn epoch_minters(cid_hex: &str) -> std::collections::BTreeMap<u64, String> {
    crate::db::settings::get_sql_setting(format!("v2_minter:{cid_hex}"))
        .ok()
        .flatten()
        .and_then(|v| serde_json::from_str(&v).ok())
        .unwrap_or_default()
}

/// Remember the rotator that minted `epoch`. Recorded at ADOPTION (and by the
/// refounder for its own mint), so it is always an npub this device verified as
/// an authorized rotator — never one a snapshot claims for itself.
pub(crate) fn record_epoch_minter(cid_hex: &str, epoch: u64, rotator_hex: &str) {
    let mut m = epoch_minters(cid_hex);
    if m.get(&epoch).is_some_and(|held| held == rotator_hex) {
        return;
    }
    m.insert(epoch, rotator_hex.to_string());
    if let Ok(v) = serde_json::to_string(&m) {
        let _ = crate::db::settings::set_sql_setting(format!("v2_minter:{cid_hex}"), v);
    }
}

/// Keep `epoch`'s Control Plane address, so its history reads back once the plane has moved on.
pub(crate) fn archive_control_address(cid_hex: &str, epoch: u64, control_pk: Option<&PublicKey>) {
    let Some(pk) = control_pk else { return };
    if let Err(e) = crate::db::community::store_epoch_key(cid_hex, crate::community::CONTROL_PK_SCOPE, epoch, &pk.to_bytes()) {
        crate::log_warn!("v2: control address archive failed (that epoch's audit history may not read back): {e}");
    }
}

/// Record a severed rotation. Idempotent; marks only accumulate — the row is a
/// few bytes and clearing one would let a failed severance read as done (B4).
pub(crate) fn add_sever_mark(cid_hex: &str, epoch: u64, at_secs: u64) {
    let mut marks = sever_marks(cid_hex);
    marks.insert(epoch, at_secs);
    if let Ok(v) = serde_json::to_string(&marks) {
        let _ = crate::db::settings::set_sql_setting(format!("v2_sever:{cid_hex}"), v);
    }
}

/// Sever MY OWN condemned public links: revoke (not refresh) every live link of
/// mine for this community whose minted-at epoch sits below the highest severed
/// epoch. The epoch is the discriminator — deterministic on every device, so a
/// second device adopting the containment late can never eat the fresh link the
/// owner minted to re-open (it carries the post-raid epoch), while a link minted
/// mid-raid by a not-yet-adopted device carries the raid-era epoch and dies.
/// Batched: every tombstone publishes, then ONE 13303 republish and ONE registry
/// edition for the whole set. Deliberately WITHOUT `revoke_public_link`'s
/// last-link refound escalation: every caller here sits inside a rotation
/// (refound or follow), where that escalation self-deadlocks on `follow_lock` —
/// and the severed rotation IS the read-cut the escalation exists to provide.
/// Returns the number revoked; `Ok(0)` when there is nothing of mine to sever.
async fn sever_own_links<T: Transport + ?Sized>(
    transport: &T,
    community: &CommunityV2,
) -> Result<usize, String> {
    crate::db::scoped(async move {
        let session = crate::db::current_session();
        let my_pk = me_pk()?;
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let Some(condemn_below) = sever_marks(&cid_hex).keys().copied().max() else {
            return Ok(0); // no containment on record — nothing is condemned.
        };
        // Local fast-path: the folded Registry names every creator with a live
        // link, and my own mints also leave local rows. Neither names me → no
        // 13303 fetch; a plain member pays nothing here.
        let maybe_mine = crate::db::community::invite_link_set_creators(&cid_hex)
            .map(|cs| cs.contains(&my_pk.to_hex()))
            .unwrap_or(true)
            || !crate::db::community::list_public_invites(&cid_hex).unwrap_or_default().is_empty();
        if !maybe_mine {
            return Ok(0);
        }
        let gate = invite_list_gate();
        let _held = gate.lock().await;
        let Some((mut list, newest)) = read_invite_list(transport, &invite_list_relays(community).await).await?.map(|(l, n)| (l, Some(n))) else {
            return Ok(0); // no list ever published — nothing of mine exists.
        };
        let dead: std::collections::HashSet<&str> = list.tombstones.iter().map(|t| t.token.as_str()).collect();
        let victims: Vec<invite::InviteEntry> = list
            .entries
            .iter()
            .filter(|e| e.community_id == cid_hex && !dead.contains(e.token.as_str()) && e.epoch.unwrap_or(0) < condemn_below)
            .cloned()
            .collect();
        if victims.is_empty() {
            return Ok(0);
        }
        let mut revoked_tokens: Vec<String> = Vec::with_capacity(victims.len());
        for entry in &victims {
            // One corrupt entry must not wedge the batch (and with it the
            // community's Public/Private reading) forever: tombstone the husk —
            // no revocation can ever be built from it anyway.
            match Keys::parse(&entry.signer_sk) {
                Ok(link_signer) => {
                    let revocation = invite::build_revocation(&link_signer).map_err(|e| e.to_string())?;
                    transport.publish_durable(&revocation, &community.relays).await?;
                }
                Err(_) => crate::log_warn!("[Sever] link {} carries a malformed signer — tombstoning the husk", &entry.token[..entry.token.len().min(8)]),
            }
            list.tombstones.push(invite::InviteTombstone::of(entry));
            revoked_tokens.push(entry.token.clone());
        }
        list.entries.retain(|e| !revoked_tokens.contains(&e.token));
        list.prune_expired(now_ms());
        publish_invite_list(transport, community, &list, newest).await?;
        let signers = live_signers_for(&list, &cid_hex, now_ms());
        publish_invite_registry(transport, community, &session, &signers).await?;
        for token in &revoked_tokens {
            let _ = crate::db::community::delete_public_invite(token);
        }
        crate::log_info!("[Sever] revoked {} own public link(s) (containment)", revoked_tokens.len());
        Ok(revoked_tokens.len())
    })
    .await
}

/// The follow-pass severance retry (B4): while a sever mark exists and I still
/// hold live links at-or-below its line, re-attempt. A miss here is load-bearing
/// — a stale registry keeps the community reading Public, which silently skips
/// every future ban's refound — so this runs on every follow until it drains.
pub(crate) async fn retry_pending_severance<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) {
    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
    if sever_marks(&cid_hex).is_empty() {
        return;
    }
    if let Err(e) = sever_own_links(transport, community).await {
        crate::log_warn!("[Sever] pending link severance retry failed (will retry next follow): {e}");
    }
}

/// Refresh every live public link's bundle behind its stable URL (CORD-05 §2) — e.g.
/// after a Rekey/Refounding rolled the keys — by re-posting the bundle at the same
/// coordinate with the CURRENT community state, so a link shared once keeps working
/// across rotations. Best-effort.
pub async fn refresh_public_links<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> Result<(), String> {
    crate::db::scoped(async move {
        let session = crate::db::current_session();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        // A transport failure propagates, so a post-Refounding refresh retries rather than leave
        // live links serving the old root. Refreshing writes no list, so a copy that won't open
        // is skipped here, never written over.
        let my_pk = me_pk()?;
        let Some((list, _)) = read_invite_list_with(transport, &invite_list_relays(community).await, false).await? else {
            return Ok(());
        };
        let creator = my_pk;
        let now = now_ms();
        let dead: std::collections::HashSet<&str> = list.tombstones.iter().map(|t| t.token.as_str()).collect();
        // A containment condemns every link below its epoch. Refreshing one would
        // RE-ARM the exact door the severing rotation closed (with the new root,
        // no less) — and once re-armed, no retry could tell it from a legitimate
        // link. Skip here; the severance retry owns their burial.
        let condemn_below = sever_marks(&cid_hex).keys().copied().max().unwrap_or(0);
        for entry in &list.entries {
            if entry.community_id != cid_hex || dead.contains(entry.token.as_str()) || entry.token.len() != 2 * super::derive::TOKEN_LEN {
                continue;
            }
            if entry.epoch.unwrap_or(0) < condemn_below {
                continue;
            }
            // An expired link can't be joined, so refreshing it just re-states a
            // door that isn't there (CORD-05 §1/§5).
            if entry.expires_at_ms().is_some_and(|exp| now > exp) {
                continue;
            }
            let Ok(link_signer) = Keys::parse(&entry.signer_sk) else { continue };
            let token = crate::simd::hex::hex_to_bytes_16(&entry.token);
            let bundle = bundle_of(community, BundleAudience::Link, Some(creator), entry.expires_at_ms(), entry.label.clone());
            let bundle_key = super::derive::invite_bundle_key(&token);
            if let Ok(event) = invite::build_bundle_event(&link_signer, &bundle, &bundle_key) {
                let _ = transport.publish_durable(&event, &community.relays).await;
            }
        }
        // Republish the Registry from the same pruned view. Expiry is the one way a
        // link dies with no user action, so without a heal point here the aggregate
        // never empties and the community reads Public long after its last door
        // shut (CORD-05 §5). Idempotent when nothing lapsed.
        //
        // Only for a creator who actually minted here: one Invite List spans every
        // community, so a member holding links ELSEWHERE would otherwise publish an
        // empty Registry edition into this one on every rotation they adopt — a
        // control-plane write, and a version bump, for a coordinate they never owned.
        let mine_here = list.entries.iter().any(|e| e.community_id == cid_hex);
        if !mine_here {
            return Ok(());
        }
        let signers = live_signers_for(&list, &cid_hex, now);
        let _ = publish_invite_registry(transport, community, &session, &signers).await;
        Ok(())
    })
    .await
}

/// Whether this community is PUBLIC (CORD-05 §5): fold every creator's Registry
/// (vsk-8) that its author is authorized for (`CREATE_INVITE`, bound to their
/// coordinate) into an aggregate live-link set — non-empty ⇒ a live link exists ⇒
/// Public; empty ⇒ Private. Retiring the last link is what flips it back.
pub async fn community_is_public<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> bool {
    let Ok(owner) = community.owner() else { return false };
    // Truncation fails toward Public: over-stating it only makes a caller take the
    // stronger remedy (privatise + re-found + reissue), while under-stating it
    // leaves a live link open behind a ban.
    let Some(editions) = fetch_control_plane_whole(transport, community).await else { return true };
    let cid = community.id();
    let cid_hex = crate::simd::hex::bytes_to_hex_32(&cid.0);
    let floors: Floors = crate::db::community::get_all_edition_heads_full(&cid_hex)
        .unwrap_or_default()
        .into_iter()
        .filter(|(_, f)| f.0 == community.root_epoch.0)
        .map(|(entity, f)| (entity, (f.1, f.2, f.3, f.4, f.5)))
        .collect();
    let authority = fold_authority(community, &editions, &floors);
    !live_invite_link_sets(cid, &owner.to_hex(), &editions, &authority, &floors).is_empty()
}

/// What this client's control fold makes of the plane now, saving none of it: whether
/// authority settles, and per entity the held floor against the newest edition served.
/// For a device whose view froze. Structure only (entity prefixes, versions, verdicts, signers
/// by role, ages in days): no content, keys or exact times, so a private community's can be shared.
pub async fn debug_control_report(community: &CommunityV2) -> Result<serde_json::Value, String> {
    let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(15));
    let ControlRead { floors, editions, authority, fold, truncated, pages_read, healed, refusals } = read_control(&transport, community).await?;
    let hex = crate::simd::hex::bytes_to_hex_32;
    let short = |h: &str| h[..12.min(h.len())].to_string();
    // Signers by role, never by key: a key prefix would name a private community's staff.
    let owner = community.owner().ok().map(|o| o.to_hex());
    let me = crate::state::my_public_key().map(|m| m.to_hex());
    let mut signers: Vec<String> = Vec::new();
    let mut signer = |pk: &str| -> String {
        if owner.as_deref() == Some(pk) {
            return "owner".into();
        }
        if me.as_deref() == Some(pk) {
            return "me".into();
        }
        let n = signers.iter().position(|s| s == pk).unwrap_or_else(|| {
            signers.push(pk.to_string());
            signers.len() - 1
        });
        format!("signer {}", n + 1)
    };
    let now = now_ms() / 1000;
    let mine = crate::state::my_public_key().map(|me| hex(&super::derive::grant_locator(community.id(), &me.to_bytes())));
    let folded: std::collections::HashMap<&str, &FoldedHead> =
        fold.heads.iter().chain(authority.heads.iter()).map(|h| (h.entity_hex.as_str(), h)).collect();
    let mut by_entity: std::collections::BTreeMap<String, Vec<&ParsedEdition>> = Default::default();
    for e in &editions {
        by_entity.entry(hex(&e.entity_id)).or_default().push(e);
    }
    // A held entity the relays serve nothing for is part of the picture too.
    for held in floors.keys() {
        by_entity.entry(held.clone()).or_default();
    }
    let rows: Vec<serde_json::Value> = by_entity
        .iter()
        .map(|(eid, eds)| {
            let newest = eds.iter().max_by_key(|e| (e.version, e.created_at));
            let floor = floors.get(eid);
            let mut served: Vec<u64> = eds.iter().map(|e| e.version).collect();
            served.sort_unstable();
            served.dedup();
            serde_json::json!({
                "entity": short(eid),
                "kind": newest.map(|e| e.vsk.clone()),
                "mine": mine.as_deref() == Some(eid.as_str()),
                "served": served,
                "newest": newest.map(|e| serde_json::json!({
                    "version": e.version,
                    "age_days": now.saturating_sub(e.created_at) / 86_400,
                    "author": signer(&e.author.to_hex()),
                    "admitted": fold.admitted.contains(&e.inner_id) || authority.admitted.contains(&e.inner_id),
                    "is_floor": floor.is_some_and(|f| f.1 == e.self_hash),
                    "extends_floor": floor.filter(|f| f.1 != e.self_hash).map(|f| e.prev_hash == Some(f.1)),
                })),
                "floor": floor.map(|f| serde_json::json!({ "version": f.0, "served": eds.iter().any(|e| e.self_hash == f.1) })),
                "folds_to": folded.get(eid.as_str()).map(|h| serde_json::json!({ "version": h.version, "rebased": h.rebased })),
                "refused": refusals.get(eid).copied().or_else(|| authority.refused.contains(eid).then_some("refused")),
                "carried": authority.carried.contains(eid),
                "kept": fold.kept.contains(eid),
            })
        })
        .collect();
    Ok(serde_json::json!({
        "root_epoch": community.root_epoch.0,
        "converged": authority.converged,
        "complete": authority.complete,
        "activated": authority.activated,
        "authority_gapped": authority.gapped,
        "fold_gapped": fold.gapped,
        "truncated": truncated,
        "pages_read": pages_read,
        "editions": editions.len(),
        "would_update": fold.updated.is_some(),
        "healed": healed.iter().map(|h| short(&h.entity_hex)).collect::<Vec<_>>(),
        "entities": rows,
    }))
}

/// Page the WHOLE control plane, not the newest window: a registry pushed out of a
/// single page reads as retired, and any member can push it out since the plane key
/// comes from the community root they hold. `None` = it could NOT be read whole
/// (transport failure, same-second wall, pager depth), so a caller must not mistake
/// an empty fold for absence.
/// Every Control edition on the relays, newest first, for forensics: who wrote what, and
/// whether this client's fold kept a head for it. Content is cut short; it holds no secret.
pub async fn debug_control_editions(community: &CommunityV2) -> Result<serde_json::Value, String> {
    let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(15));
    let mut editions = fetch_control_plane_whole(&transport, community).await.ok_or("the Control Plane couldn't be read whole")?;
    editions.sort_by(|a, b| b.created_at.cmp(&a.created_at));
    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
    let heads: std::collections::HashMap<String, (u64, [u8; 32])> = crate::db::community::get_all_edition_heads_full(&cid_hex)
        .unwrap_or_default()
        .into_iter()
        .map(|(entity, f)| (entity, (f.1, f.2)))
        .collect();
    let rows: Vec<serde_json::Value> = editions
        .iter()
        .map(|e| {
            let eid = crate::simd::hex::bytes_to_hex_32(&e.entity_id);
            let head = heads.get(&eid);
            serde_json::json!({
                "at": e.created_at,
                "vsk": e.vsk,
                "entity": &eid[..12],
                "version": e.version,
                "author": &e.author.to_hex()[..12],
                "marked": e.binding.is_some(),
                "cites": e.authority.is_some(),
                "is_head": head.is_some_and(|h| h.1 == e.self_hash),
                "head_version": head.map(|h| h.0),
                "content": e.content.chars().take(240).collect::<String>(),
            })
        })
        .collect();
    let owner = community.owner().map(|o| o.to_hex()).unwrap_or_default();
    Ok(serde_json::json!({ "owner": owner, "control_pk": community.control_pk.map(|p| p.to_hex()), "editions": rows }))
}

/// Every edition on the Control Plane, or `None` when it could not be read whole: through the
/// wraps held once the store is on, else page by page off the relays.
async fn fetch_control_plane_whole<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> Option<Vec<ParsedEdition>> {
    match control_store::mode() {
        control_store::Mode::Off => fetch_control_plane_whole_paged(transport, community).await,
        control_store::Mode::On => match whole_held(transport, community).await {
            Ok(editions) => editions,
            Err(why) => {
                crate::log_debug!("[v2:control {}] whole read by pages ({why})", &community.id().to_hex()[..8]);
                fetch_control_plane_whole_paged(transport, community).await
            }
        },
        control_store::Mode::Shadow => {
            let paged = fetch_control_plane_whole_paged(transport, community).await;
            if let (Some(paged), Ok(Some(held))) = (&paged, whole_held(transport, community).await) {
                let held: std::collections::HashSet<[u8; 32]> = held.iter().map(|e| e.inner_id).collect();
                let pages: std::collections::HashSet<[u8; 32]> = paged.iter().map(|e| e.inner_id).collect();
                let (lost, more) = (pages.difference(&held).count(), held.difference(&pages).count());
                if lost > 0 || more > 0 {
                    #[cfg(test)]
                    if std::env::var("VECTOR_CONTROL_SHADOW_STRICT").is_ok() {
                        panic!("the whole read through the store differs from the paged one: {lost} edition(s) lost, {more} more");
                    }
                    crate::log_warn!("[v2:control {}] shadow: the whole read through the store differs: {lost} lost, {more} more", &community.id().to_hex()[..8]);
                }
            }
            paged
        }
    }
}

/// [`fetch_control_plane_whole`] through the wraps held, every relay heard first. `Err` when the
/// wraps held cannot serve it and the pages must.
async fn whole_held<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> Result<Option<Vec<ParsedEdition>>, String> {
    let Some(wraps) = whole_wraps_held(transport, community).await? else { return Ok(None) };
    let control = control::ControlPlane::of(community);
    let mut editions = Vec::with_capacity(wraps.len());
    for page in wraps.chunks(FOLLOW_PAGE) {
        let _batch = control.check_page(&page.iter().collect::<Vec<_>>());
        editions.extend(page.iter().filter_map(|w| control.open_edition(w).ok()));
    }
    Ok(Some(editions))
}

/// Every wrap held of the Control Plane once it is known whole, newest first: see [`whole_held`].
async fn whole_wraps_held<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> Result<Option<Vec<Event>>, String> {
    use control_sync::{sync_plane, Unsynced, Wait};
    crate::db::scoped(async move {
        let kept = || match crate::db::community::community_held(community.id()) {
            Ok(true) => Ok(()),
            _ => Err("the community is not held".to_string()),
        };
        kept()?;
        let view = control_store::View::of(community);
        if control_sync::flooded(community, &view) {
            return Err("more wraps than a pass reads".into());
        }
        let sync = match sync_plane(transport, community, &view, Wait::All).await {
            Ok(sync) if sync.flooded => return Err("more wraps than a pass reads".into()),
            Ok(sync) => sync,
            Err(Unsynced::NoRelay(_)) => return Ok(None),
            Err(Unsynced::Store(e)) => return Err(e),
        };
        kept()?;
        if sync.unread {
            return Ok(None);
        }
        // A whole read is what the relays hold now. A wrap only this device still has is left
        // out, as their pages would leave it out, and telling which needs each relay's whole
        // set: with one read by pages (where a second can be walled) the pages serve it.
        let Some(unserved) = control_sync::unserved_by_all(transport, &view, &sync).await else { return Err("a relay's whole set is not known".into()) };
        let mut all: Vec<Event> = Vec::new();
        let mut below: Option<(u64, nostr_sdk::prelude::EventId)> = None;
        loop {
            let wraps = view.page(below, FOLLOW_PAGE)?;
            let Some(last) = wraps.last() else { break };
            below = Some((last.created_at.as_secs(), last.id));
            all.extend(wraps.into_iter().filter(|w| !unserved.contains(&w.id)));
        }
        Ok(Some(all))
    })
    .await
}

async fn fetch_control_plane_whole_paged<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> Option<Vec<ParsedEdition>> {
    let control = control::ControlPlane::of(community);
    let mut editions: Vec<ParsedEdition> = Vec::new();
    let mut seen_wraps: std::collections::HashSet<nostr_sdk::prelude::EventId> = std::collections::HashSet::new();
    let mut oldest: Option<u64> = None;
    let mut until: Option<u64> = None;
    for page in 0..COMPACT_MAX_PAGES {
        // Full, not Quorum: `None` here means "could not be read whole", and a
        // majority that simply lacks another creator's Registry answers as fast as
        // one that has it — so a Quorum read returns Some(empty) and the plane reads
        // link-free. The ban path turns that into a Refounding of a PUBLIC community,
        // which CORD-05 §5 forbids: the link refresh re-posts the bundle behind the
        // same URL, so the rotation severs nothing and buries foreign-link joiners.
        let query = Query { evidence: crate::community::transport::Evidence::Full, ..plane_page(control.pk_hex(), FOLLOW_PAGE, until) };
        let Ok(wraps) = transport.fetch(&query, &community.relays).await else { return None };
        let mut fresh = 0usize;
        let _batch = control.check_page(&wraps.iter().filter(|w| !seen_wraps.contains(&w.id)).collect::<Vec<_>>());
        for w in &wraps {
            if !seen_wraps.insert(w.id) {
                continue;
            }
            fresh += 1;
            let at = w.created_at.as_secs();
            if oldest.is_none_or(|o| at < o) {
                oldest = Some(at);
            }
            if let Ok(ed) = control.open_edition(w) {
                editions.push(ed);
            }
        }
        if fresh == 0 {
            if wraps.len() >= FOLLOW_PAGE {
                return None; // same-second wall: the plane can't be read whole
            }
            return Some(editions);
        }
        until = oldest;
        if page + 1 == COMPACT_MAX_PAGES {
            return None;
        }
    }
    Some(editions)
}

/// The live link coordinates PER AUTHORISED CREATOR across every Registry (vsk-8);
/// non-empty ⇒ the Community is Public, and the per-creator split is what drives
/// "X has N active invite links". Pure over an already-fetched edition set so the
/// on-demand probe and the control follow fold it identically.
fn live_invite_link_sets(
    cid: &crate::community::CommunityId,
    owner_hex: &str,
    editions: &[ParsedEdition],
    authority: &AuthoritySet,
    floors: &Floors,
) -> Vec<crate::db::community::InviteLinkSetRow> {
    use crate::community::roles::Permissions;
    use std::collections::BTreeMap;
    let mut by_eid: BTreeMap<[u8; 32], Vec<&ParsedEdition>> = BTreeMap::new();
    for e in editions {
        if e.vsk == vsk::INVITE_LINKS {
            by_eid.entry(e.entity_id).or_default().push(e);
        }
    }
    let mut sets: Vec<crate::db::community::InviteLinkSetRow> = Vec::new();
    for (eid, group) in &by_eid {
        // Authority BEFORE the fold, matching `apply_control_fold`. `fold_head`
        // picks an equal-version winner author-blind (lowest inner id, which an
        // author can grind), so folding first would let any member occupy the head
        // slot and have the whole registry dropped by the check below — silently
        // retiring a live invite link, i.e. flipping the community to Private.
        let authed: Vec<&ParsedEdition> = group
            .iter()
            .copied()
            .filter(|p| {
                let author = p.author.to_hex();
                // The creator must hold CREATE_INVITE, not be banned, AND own this coordinate.
                !authority.banned.contains(&author)
                    && authority.roles.is_authorized(&author, Some(owner_hex), Permissions::CREATE_INVITE)
                    && super::derive::invite_links_locator(cid, &p.author.to_bytes()) == *eid
            })
            .collect();
        if authed.is_empty() {
            continue;
        }
        let fold_eds: Vec<version::Edition> = authed.iter().map(|p| p.to_fold_edition()).collect();
        let (Some(hi), _) = fold_head(&fold_eds, floors.get(&crate::simd::hex::bytes_to_hex_32(eid)), &|_| 0) else { continue };
        if let Ok(signers) = invite::parse_registry_content(&authed[hi].content) {
            if signers.is_empty() {
                continue; // a creator who retired every link is absent, not a zero row
            }
            sets.push(crate::db::community::InviteLinkSetRow {
                creator_hex: authed[hi].author.to_hex(),
                locators: signers.iter().map(|p| p.to_hex()).collect(),
            });
        }
    }
    sets
}

/// Flatten per-creator sets into the aggregate the `invite_registry` column holds.
fn flatten_link_sets(sets: &[crate::db::community::InviteLinkSetRow]) -> Vec<String> {
    let mut flat: Vec<String> = sets.iter().flat_map(|s| s.locators.iter().cloned()).collect();
    flat.sort();
    flat.dedup();
    flat
}

/// Accept an already-unwrapped bundle: verify the owner commitment AND that the
/// delivered community_root is genuinely the owner's, persist the community, and
/// announce a Guestbook Join (with invite attribution). Shared tail of both accept
/// paths. Takes the caller's `std::sync::Arc<crate::db::Session>` (captured BEFORE any network fetch the
/// caller did) so the whole operation stays with one account across that I/O.
///
/// `member_since` is `None` for a join made now, or the membership time of keys the account
/// already holds elsewhere (a List adoption): the hold is stamped with it, so a removal made
/// after that membership still outranks the copy.
async fn accept_bundle<T: Transport + ?Sized>(
    transport: &T,
    bundle: &CommunityInvite,
    invited_by: Option<PublicKey>,
    member_since: Option<u64>,
) -> Result<CommunityV2, String> {
    crate::db::scoped(async move {
        let signer = crate::signer::active_signer()?;
        let my_pk = me_pk()?;
        let at_ms = now_ms();
        let announce_join = member_since.is_none();
        let held_since = member_since.filter(|&t| t > 0).map_or(at_ms, |t| t.min(at_ms));
        // Expiry gate: a past invite still previews but must not join (CORD-05 §1).
        if bundle.expired(at_ms) {
            return Err("this invite has expired".to_string());
        }
        // `from_bundle` re-validates bounds + the owner commitment fail-closed.
        let community = CommunityV2::from_bundle(bundle, held_since)?;
        // Captured before the save below: a re-accept of a held community must not
        // re-announce a membership this account already declared.
        let already_held = crate::db::community::load_community_v2(community.id()).ok().flatten().is_some();
        // A seat taken anew is owed every delivery again: one back after leaving, in the same
        // session, would otherwise find each already opened and never look at it twice.
        if !already_held {
            forget_opened_deliveries();
        }

        // Authenticate the delivered community_root before trusting it. The owner
        // commitment proves WHO the owner is, but community_root (and channel keys) are
        // NOT in that commitment, so a forged invite can pair a real (id, owner, salt)
        // with an attacker-chosen root and silently partition the joiner onto planes
        // only the attacker controls. Requiring the owner's genesis to open under the
        // delivered root closes that eclipse; also reconciles channel classification.
        // A preview verified the SAME (id, root) moments ago → reuse its fold instead
        // of re-walking the plane (the bundle re-fetch above kept the revocation gate).
        let handoff = VERIFIED_PREVIEW.lock().unwrap().take().filter(|v| {
            v.session.upgrade().is_some_and(|s| s.is_live())
                && v.at.elapsed() < VERIFIED_PREVIEW_TTL
                && v.community_id == community.id().0
                && v.community_root == community.community_root
        });
        let (community, join_heads, join_banlist, (join_pins, join_writers), join_banlist_content, join_roles, join_authority_heads) =
            match handoff {
                Some(v) => {
                    let mut c = v.folded;
                    // The preview holds no acquisition time — stamp the JOIN's.
                    c.created_at_ms = held_since;
                    (c, v.heads, v.banned, (v.pins, v.writers), v.banlist_persist, v.roles, v.authority_heads)
                }
                None => {
                    let vj = verify_owner_root_and_reconcile(transport, community).await?;
                    (vj.community, vj.heads, vj.banned, (vj.pins, vj.writers), vj.banlist_persist, vj.roles, vj.authority_heads)
                }
            };

        // A dissolved community is a grave (CORD-02 §9): refuse to join it.
        if is_dissolved(transport, &community).await {
            return Err(ERR_DISSOLVED.to_string());
        }

        // Join-time ban gate (CORD-04 §4, Armada parity): an honest client refuses to join a
        // community whose authorized banlist names it — before the Guestbook Join publishes
        // and before any local write. Every door funnels through here (direct invite, parked,
        // public link, migration), so none of them needs its own exclusion.
        if join_banlist.contains(&my_pk.to_hex()) {
            return Err("you are banned from this community".to_string());
        }

        // The account must not have swapped since the guard was captured (which was
        // before any fetch the caller / the verify above performed) — else we'd write
        // A's join into B.
        // Seed the verified heads as the initial refuse-downgrade floor BEFORE the
        // community row lands (floors-then-state, so a mid-seed error can't leave saved
        // state outrunning its floor); the first post-join follow then can't persist a
        // state below what this join already showed.
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let families = join_heads.iter().map(|h| (h, crate::db::community::FLOOR_CONTROL)).chain(join_authority_heads.iter().map(|h| (h, crate::db::community::FLOOR_AUTHORITY)));
        for (h, family) in families {
            crate::db::community::set_family_head_at_epoch(&cid_hex, &h.entity_hex, h.version, &h.self_hash, &h.inner_id, &h.author, community.root_epoch.0, family)?;
        }
        crate::db::community::save_community_v2(&community)?;
        // Archive the joined root at its epoch, so this member reads Public-channel
        // history from their join epoch onward across later Refoundings (CORD-03 §3).
        let _ = crate::db::community::store_epoch_key(&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX, community.root_epoch.0, &community.community_root);
        // Same for each granted Private-channel key: the archive is what lets its
        // history stay readable after the channel rotates away from this key.
        for ch in &community.channels {
            if let (true, Some(key)) = (ch.private, ch.key) {
                let _ = crate::db::community::store_epoch_key(&cid_hex, &crate::simd::hex::bytes_to_hex_32(&ch.id.0), ch.epoch.0, &key);
            }
        }
        // Persist what the verification walk already folded: the control plane WAS
        // read, so making the fresh member wait for the follow worker's queued
        // re-walk to see pins or enforce bans is pure lag (it read 20-30s on a busy
        // queue). The system "modified the Pins" line still arrives via that first
        // follow — a join backfills state, it doesn't announce edits.
        if let Some((banned_list, version)) = &join_banlist_content {
            store_banlist(&cid_hex, banned_list, *version as i64);
        }
        // The ROSTER, same rule as the banlist and pins above: the walk already
        // paid for it. Persisted BEFORE the channels register, because the first
        // history ingest reads it to honor moderation hides — an empty roster
        // authorizes nobody, so every admin-hidden message would render to the
        // fresh member until the follow worker's queued re-walk landed.
        if let Some((roles, at)) = &join_roles {
            let _ = crate::db::community::set_community_roles(&cid_hex, roles, *at);
        }
        for (channel_hex, content, version, _) in &join_writers {
            persist_writers(&cid_hex, channel_hex, content, *version, true);
        }
        for (channel_hex, content, version, _author, _at) in &join_pins {
            if matches!(
                crate::db::community::set_community_pins(&cid_hex, channel_hex, content, *version as i64),
                Ok(true)
            ) {
                crate::emit_event(
                    "community_pins_updated",
                    &serde_json::json!({ "community_id": cid_hex, "channel_id": channel_hex }),
                );
            }
        }

        // Announce our Guestbook Join, echoing the invite attribution when present.
        // Only an ACTUAL join speaks: a re-accept of a held community, or a
        // cross-device key sync (`member_since` set), is not a membership event —
        // the account's original Join already stands in the guestbook, and every
        // re-publish renders as "<user> has joined" spam for the whole community.
        if announce_join && !already_held {
            let (bundle_creator, bundle_label) = bundle.attribution();
            let attribution = invited_by
                .map(|p| p.to_hex())
                .or_else(|| bundle_creator.map(str::to_string))
                .zip(Some(bundle_label.unwrap_or_default().to_string()));
            let attr_ref = attribution.as_ref().map(|(c, l)| (c.as_str(), l.as_str()));
            let gb_group = super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
            let join_rumor = guestbook::build_join_rumor(my_pk, attr_ref, at_ms);
            if let Ok((join_wrap, _)) = guestbook::seal_guestbook_rumor_signed(&signer, my_pk, &join_rumor, &gb_group, Timestamp::from_secs(at_ms / 1000)).await {
                publish_my_join(transport, &community, join_wrap).await;
            }
        }

        // Record the membership across devices (CORD-02 §8). The inline attempt covers the
        // happy path; anything else hands off to the durable retry, because an unrecorded
        // join is what strands a community behind a stale tombstone.
        //
        // Only for a REAL join. A `member_since` is the list-sync adoption path,
        // and those entries were just read FROM this list — republishing it re-records what
        // it already holds. A device adopting N entries would otherwise rebuild and publish
        // the whole document N times, concurrently, every copy identical, on the boot path
        // that is already the slowest thing the app does.
        if announce_join {
            match republish_community_list(transport, Some(community.id())).await {
                Ok(true) => {}
                Ok(false) => republish_community_list_durable(Some(*community.id())),
                Err(e) => {
                    crate::log_warn!("[CommunityList] failed to record this join across devices ({}) — retrying", e);
                    republish_community_list_durable(Some(*community.id()));
                }
            }
        }
        Ok(community)
    })
    .await
}

/// Prove the delivered `community_root` is genuinely the owner's, and reconcile
/// channel classification from the owner's editions. `community_id` commits only
/// to `(owner_xonly, owner_salt)` — both semi-public (they ride every bundle and
/// every synced Community List) — so a forged invite can present a real community's
/// id/owner/salt with an attacker-chosen root; every plane then derives from that
/// root, silently eclipsing the joiner onto attacker-controlled addresses while the
/// owner commitment still "verifies". The defense: the owner's genesis metadata
/// edition (vsk-0, `eid == community_id`) only opens under the AUTHENTIC root — an
/// attacker can't forge the owner's seal — so its presence on the control plane
/// derived from the delivered root proves that root. On a ROTATED plane (epoch > 0)
/// the compaction may have carried an admin-signed metadata head instead (CORD-06
/// re-wraps heads with their original signatures), so the anchor there is the
/// community-bound metadata head plus any owner-signed edition under the same root.
/// Fail-closed: no anchor (forged invite, or relays unreachable) → refuse to join.
/// On success, folds the owner's authoritative editions to heal a bundle that
/// misclassified a channel.
/// Everything the join-time verification walk folded, handed to the accept path so
/// what the join VERIFIED is also what it PERSISTS. The walk already paid for the
/// control plane read; deferring persistence to the first post-join follow re-pays
/// the network cost and leaves the fresh member pins-blind and banlist-blind for
/// the whole follow-queue delay.
struct VerifiedJoin {
    community: CommunityV2,
    heads: Vec<FoldedHead>,
    /// The join-gate banlist (authorized fold over the any-author edition set).
    banned: std::collections::BTreeSet<String>,
    /// Pin List heads folded under the FULL join-time authority (curators included,
    /// same §5 gate as any later follow): `(channel_hex, content, version, author_npub, created_at)`.
    pins: Vec<(String, String, u64, String, u64)>,
    /// Writers ledger heads from the same fold: `(channel_hex, content, version)`.
    writers: Vec<(String, String, u64, bool)>,
    /// The authorized banlist head's content + version, for local persistence.
    banlist_persist: Option<(Vec<String>, u64)>,
    /// The FULL authorized roster (admins included) from the same walk, with the
    /// newest roster edition's `created_at`. `None` when the fold saw a gap.
    ///
    /// This is the one authority artifact the join used to throw away — and a
    /// fresh member whose roster is empty until the follow worker's re-walk
    /// renders every moderator-hidden message in the meantime: the hide gate
    /// reads the stored roster, and an empty roster authorizes nobody.
    roles: Option<(crate::community::roles::CommunityRoles, i64)>,
    /// Role/Grant/Banlist heads folded under the full authority, so an
    /// ADMIN-signed grant seeds the same refuse-downgrade floor an owner-signed
    /// one does.
    authority_heads: Vec<FoldedHead>,
}

async fn verify_owner_root_and_reconcile<T: Transport + ?Sized>(
    transport: &T,
    community: CommunityV2,
) -> Result<VerifiedJoin, String> {
    let owner = community.owner()?;
    let control = control::ControlPlane::of(&community);
    let control_pk = control.pk_hex();

    // AUTH-gating relays (ditto-relay's default gates kind-1059) serve a plane's
    // wraps ONLY to a connection authenticated AS the stream key — Concord's
    // group-addressed wraps aren't p-tagged to the joiner, so the login alone can't
    // satisfy the gate and the control plane reads back empty. Register this
    // community's stream keys + start the challenge responder so the fetch below
    // (whose REQ triggers the relay's AUTH challenge) reads the plane after auth.
    super::streamauth::prime(&community);

    // Authenticity = the owner's GENESIS metadata edition (vsk-0, `eid ==
    // community_id`) at the root-derived control plane. The genesis eid pins it to
    // THIS community, and it lives ONLY under the real root — so a forged root can't
    // produce one: an edition's seal carries no community binding, but another
    // community's genesis has a different eid, and this community's own genesis is
    // unreadable without its real root (which the forger lacks). ("Any owner edition"
    // is NOT sound: an owner sig from any co-owned community, rewrapped onto the fake
    // plane, would pass — reopening the eclipse.) The residual — a T-member replaying
    // T's genesis onto a fake root to MITM another T-joiner — is closed only by
    // binding the root into community_id (protocol, deferred).
    //
    // Seed `until` with a FAR-FUTURE constant (NOT now-based), and request
    // Evidence::Full EXPLICITLY below: this walk draws an ABSENCE verdict (no
    // owner-signed genesis ⇒ reject), which trusts only the completest union —
    // an open partial window misses a genesis on a lagging relay (routine over
    // Tor). A constant beyond any real created_at clips NOTHING — so neither
    // a clock-skewed future-dated genesis nor a >1h-slow-clock joiner is excluded (a
    // now-based bound could clip either). Break on an EMPTY page (a short page is a
    // relay cap). A forged root walks to exhaustion and rejects; a flood/deep plane
    // that buries the genesis past the walk is the deferred protocol residual.
    const PAGE: usize = 500;
    const MAX_PAGES: usize = 4;
    const FAR_FUTURE_SECS: u64 = 4_102_444_800; // ~year 2100 — above any real edition, safe as a relay `until`.
    let mut editions: Vec<ParsedEdition> = Vec::new();
    let mut all_editions: Vec<ParsedEdition> = Vec::new();
    let mut found_genesis = false;
    // Rotated planes (CORD-06): compaction re-wraps each entity's CURRENT head with
    // its ORIGINAL signature, so if an admin last edited the metadata the plane holds
    // no owner-signed vsk-0 at all — the strict genesis anchor is unsatisfiable there.
    // Fallback pair for epoch > 0: the community-bound metadata head (any signer) PLUS
    // at least one owner-signed edition opened under this root. A non-member forger
    // can produce neither; the sibling-community rewrap residual this reopens is the
    // same class the spec defers to root-in-id binding.
    let mut compacted_metadata = false;
    crate::log_debug!(
        "[JoinVerify] control_pk={} root_epoch={:?} relays={:?}",
        &control_pk[..12], community.root_epoch, community.relays
    );
    let anchored = |found_genesis: bool, compacted_metadata: bool, owner_editions: usize, epoch: Epoch| {
        found_genesis || (epoch.0 > 0 && compacted_metadata && owner_editions > 0)
    };
    for attempt in 0..2 {
        editions.clear();
        all_editions.clear();
        compacted_metadata = false;
        let mut until: Option<u64> = Some(FAR_FUTURE_SECS);
        let mut seen_wraps: std::collections::HashSet<nostr_sdk::prelude::EventId> = std::collections::HashSet::new();
        for page_no in 0..MAX_PAGES {
            let query = Query { evidence: crate::community::transport::Evidence::Full, ..plane_page(control_pk.clone(), PAGE, until) };
            let wraps = transport.fetch(&query, &community.relays).await?;
            crate::log_trace!(
                "[JoinVerify] attempt {} page {}: fetched {} wraps",
                attempt, page_no, wraps.len()
            );
            // INCLUSIVE `until` + wrap-id dedup: a `-1` step can skip same-second
            // siblings at a page boundary (and the genesis with them); re-served
            // boundary events are free, and no-new-events means exhausted.
            let mut oldest = u64::MAX;
            let mut fresh = 0usize;
            let _batch = control.check_page(&wraps.iter().filter(|w| !seen_wraps.contains(&w.id)).collect::<Vec<_>>());
            for w in &wraps {
                if !seen_wraps.insert(w.id) {
                    continue;
                }
                fresh += 1;
                oldest = oldest.min(w.created_at.as_secs());
                if let Ok(ed) = control.open_edition(w) {
                    crate::log_trace!(
                        "[JoinVerify] edition vsk={} eid={} owner={} at={}",
                        ed.vsk, crate::simd::hex::bytes_to_hex_32(&ed.entity_id)[..12].to_string(),
                        ed.author == owner, w.created_at.as_secs()
                    );
                    if ed.vsk == vsk::COMMUNITY_METADATA && ed.entity_id == community.id().0 {
                        if ed.author == owner {
                            found_genesis = true;
                        } else {
                            compacted_metadata = true;
                        }
                    }
                    if ed.author == owner {
                        editions.push(ed.clone());
                    }
                    // Any-author set for the join-time authority fold below: the banlist head
                    // may be admin-signed, and its authority chains to the owner regardless.
                    all_editions.push(ed);
                }
            }
            crate::log_debug!(
                "[JoinVerify] attempt {} page {}: fresh={} opened_owner={} opened_any={} genesis={} compacted={}",
                attempt, page_no, fresh, editions.len(), all_editions.len(), found_genesis, compacted_metadata
            );
            if anchored(found_genesis, compacted_metadata, editions.len(), community.root_epoch) || fresh == 0 {
                break; // authenticated, or the relay is exhausted.
            }
            until = Some(oldest);
        }
        if anchored(found_genesis, compacted_metadata, editions.len(), community.root_epoch) {
            break;
        }
        if attempt == 0 {
            // AUTH-gating relays: the first walk's REQ triggers the NIP-42 challenge,
            // but nostr-sdk's own retry re-auths as the USER key — which doesn't
            // satisfy a stream-authors gate — and can land before the responder's
            // stream-key auth settles, reading the plane back EMPTY. Replay the
            // remembered challenges for every registered stream key, then walk once
            // more on the settled connection.
            if let Some(client) = crate::state::nostr_client() {
                super::streamauth::prime_auth(&client, &community.relays).await;
            }
        }
    }
    if !anchored(found_genesis, compacted_metadata, editions.len(), community.root_epoch) {
        return Err(
            "could not verify this community from its relays (the invite may be forged, the relays are unreachable, or the control plane is being flooded); not joining"
                .to_string(),
        );
    }
    // Join-time reconcile: the joiner holds no floors yet (empty map → bootstrap per
    // entity). The heads this fold verified are returned for the caller to SEED as
    // the initial floor once the community row is saved — without that, the first
    // post-join follow would bootstrap floor-less and could persist a state BELOW
    // what this join already verified and showed.
    // Join-time reconcile folds only the owner's editions (genesis-authenticated
    // above), and the owner is supreme — so owner-only authority suffices. The full
    // roster (admins) folds on the first post-join follow_control.
    let empty_floors = Floors::default();
    // Join-time banlist: fold authority over the ANY-author edition set (roles/grants
    // chain to the genesis-verified owner; the banlist head is honored only if its signer
    // held BAN). Returned so the accept path can refuse a banned self BEFORE it publishes
    // a Guestbook Join — the gate every join door shares (Armada parity, CORD-04 §4).
    let authority_full = fold_authority(&community, &all_editions, &empty_floors);
    let mut authority = AuthoritySet::owner_only();
    // The owner's own list of the Channels that stood bounds the document too (CORD-04 §2).
    authority.roles.legacy_channels = authority_full.roles.legacy_channels.clone();
    let fold = apply_control_fold(&community, &editions, &empty_floors, &authority);
    // Pins under the FULL authority: a curator-authored Pin List is as valid at join
    // as on any later follow (same PIN_MESSAGES + citation gate, same owner-chained
    // roster). Only the pins are taken from this pass — the DOCUMENT adoption above
    // stays owner-only, its stricter envelope unchanged.
    let ControlFold { pins_persist: pins, writers_persist: writers, .. } = apply_control_fold(&community, &all_editions, &empty_floors, &authority_full);
    // The newest roster edition's stamp, exactly as follow_control computes it, so
    // the follow's own freshness gate composes with a join-seeded roster.
    let newest_roster_at = roster_stamp(&all_editions, &authority_full.heads);
    // An anchored walk read the plane back to genesis, so the window is complete
    // by construction; `gapped` still gates the persist for the same reason
    // follow_control's does — a withheld edition must not fold into a baseline.
    // A Roster fold that ran out its bound seeds nothing it judged; the first follow folds again.
    let settled = authority_full.converged;
    let roles = (!authority_full.gapped && settled).then(|| (authority_full.roles.clone(), newest_roster_at));
    Ok(VerifiedJoin {
        community: fold.updated.unwrap_or(community),
        heads: fold.heads,
        banned: authority_full.banned,
        pins: if settled { pins } else { Vec::new() },
        writers: if settled { writers } else { Vec::new() },
        banlist_persist: authority_full.banlist_persist.filter(|_| settled),
        roles,
        authority_heads: if settled { authority_full.heads } else { Vec::new() },
    })
}

/// Accept a Direct Invite: unwrap the 3313 giftwrap (Schnorr-verifying the seal),
/// then run the shared accept path. The recipient's consent IS this call. No
/// network await precedes the accept, so the guard captured here suffices.
pub async fn accept_direct_invite<T: Transport + ?Sized>(transport: &T, wrap: &Event) -> Result<CommunityV2, String> {
    let signer = crate::signer::active_signer()?;
    let (inviter, bundle) = invite::unwrap_direct_invite_signed(&signer, wrap).await.map_err(|e| e.to_string())?;
    accept_bundle(transport, &bundle, Some(inviter), None).await
}

/// Accept a PARKED Direct Invite from its stored bundle JSON (the wrap was already
/// unwrapped + owner-verified at park time). Re-parses through the same fail-closed
/// bundle validation, then runs the shared accept path (which re-verifies the owner
/// root over the network). `inviter_hex` is the parked seal signer, for Guestbook
/// Join attribution.
pub async fn accept_parked_invite<T: Transport + ?Sized>(
    transport: &T,
    bundle_json: &str,
    inviter_hex: Option<&str>,
) -> Result<CommunityV2, String> {
    let bundle = CommunityInvite::from_bundle_json(bundle_json).map_err(|e| e.to_string())?;
    let invited_by = inviter_hex.and_then(|h| PublicKey::parse(h).ok());
    accept_bundle(transport, &bundle, invited_by, None).await
}

/// Fetch + decrypt the newest Live bundle at a public link's coordinate
/// (`(33301, link_signer, "")`). **Revocation is authoritative-if-present**: if
/// ANY signer-valid tombstone is among the fetched events, refuse — never trust
/// fetch ordering (a cross-relay union has no global newest-first sort, so a
/// stale Live could otherwise win a partial-propagation race). Otherwise pick
/// the newest valid Live by `created_at`. Read-only.
pub async fn fetch_public_bundle<T: Transport + ?Sized>(transport: &T, url: &str) -> Result<CommunityInvite, String> {
    let parsed = invite::parse_invite_link(url).map_err(|e| e.to_string())?;
    let relays = if parsed.bootstrap_relays.is_empty() {
        invite::stock_relays()
    } else {
        parsed.bootstrap_relays.clone()
    };
    fetch_bundle_on(transport, &parsed, &relays).await
}

/// [`fetch_public_bundle`] on a chosen relay set.
async fn fetch_bundle_on<T: Transport + ?Sized>(transport: &T, parsed: &invite::ParsedInviteLink, relays: &[String]) -> Result<CommunityInvite, String> {
    // NO `#d` filter, even though the coordinate's `d` is empty (CORD-05 §2). Relays disagree on
    // indexing an empty tag value: some answer the REQ and then never EOSE, so the fetch burns its
    // whole union grace on every invite. The per-link signer pins the coordinate on its own (it
    // signs nothing else), and `parse_bundle_event` re-checks the empty `d` locally.
    let query = Query {
        kinds: vec![super::kind::INVITE_BUNDLE],
        authors: vec![parsed.link_signer.to_hex()],
        ..Default::default()
    };
    // One bounded retry: a join fired while the pool is still warming (bootstrap
    // relays mid-handshake, routine during boot contention) reads back a transport
    // error, not an absent bundle. The pool add already happened on the first try,
    // so wait for a socket rather than guessing with a fixed sleep.
    let events = match transport.fetch(&query, relays).await {
        Ok(evs) => evs,
        Err(_) => {
            wait_for_bootstrap_relay(relays).await;
            transport.fetch(&query, relays).await?
        }
    };
    let bundle_key = super::derive::invite_bundle_key(&parsed.token);

    // Scan EVERY event: a tombstone beats a Live unconditionally (order-independent).
    let mut newest_live: Option<(u64, CommunityInvite)> = None;
    for event in &events {
        match invite::parse_bundle_event(event, &parsed.link_signer, &bundle_key) {
            Ok(invite::BundleState::Revoked) => return Err("this invite link has been revoked".to_string()),
            Ok(invite::BundleState::Live(bundle)) => {
                let at = event.created_at.as_secs();
                if newest_live.as_ref().is_none_or(|(t, _)| at > *t) {
                    newest_live = Some((at, *bundle));
                }
            }
            Err(_) => {} // a foreign/garbage event at the coordinate — ignore.
        }
    }
    newest_live.map(|(_, b)| b).ok_or_else(|| "invite bundle not found on relays".to_string())
}

/// Wait — bounded — for ANY of the targets to report Connected before a retry:
/// the fetch's own warm path bounds its connect wait tighter than a cold TLS
/// handshake takes under boot contention.
async fn wait_for_bootstrap_relay(relays: &[String]) {
    let Some(client) = crate::state::nostr_client() else { return };
    let deadline = crate::rt::time::Instant::now() + crate::relay_connect_timeout(std::time::Duration::from_secs(8));
    loop {
        for url in relays {
            if let Ok(Some(relay)) = client.relay(url).await {
                if relay.status() == nostr_sdk::prelude::RelayStatus::Connected {
                    return;
                }
            }
        }
        if crate::rt::time::Instant::now() >= deadline {
            return;
        }
        crate::rt::time::sleep(std::time::Duration::from_millis(400)).await;
    }
}

/// The most recent owner-root verification a PREVIEW completed, handed to a join
/// so accepting seconds later doesn't re-walk the control plane. Single-slot,
/// short-lived, session-guarded, and keyed on `(community_id, community_root)` —
/// a different delivered root never matches. The join's own bundle re-fetch is
/// untouched, so the revocation gate always runs live.
struct VerifiedPreview {
    /// Weak: the slot is process-wide and must not keep a swapped-out account alive.
    session: std::sync::Weak<crate::db::Session>,
    at: web_time::Instant,
    /// Which preview this is, so its expiry never takes a newer one.
    seq: u64,
    community_id: [u8; 32],
    community_root: [u8; 32],
    folded: CommunityV2,
    heads: Vec<FoldedHead>,
    /// The join-time authorized banlist from the SAME verified walk — carried so the
    /// handoff path keeps the ban gate (a preview-then-join must not skip it).
    banned: std::collections::BTreeSet<String>,
    /// Folded pins + banlist content from the same walk, so a preview-handoff join
    /// persists them exactly like a direct join.
    pins: Vec<(String, String, u64, String, u64)>,
    writers: Vec<(String, String, u64, bool)>,
    banlist_persist: Option<(Vec<String>, u64)>,
    roles: Option<(crate::community::roles::CommunityRoles, i64)>,
    authority_heads: Vec<FoldedHead>,
}
static VERIFIED_PREVIEW: std::sync::Mutex<Option<VerifiedPreview>> = std::sync::Mutex::new(None);
const VERIFIED_PREVIEW_TTL: std::time::Duration = std::time::Duration::from_secs(120);

/// Park a verified preview for the join, dropping it once its TTL lapses unjoined:
/// a full fold of a large community has no business staying resident.
fn stash_verified_preview(mut preview: VerifiedPreview) {
    static SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
    let seq = SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    preview.seq = seq;
    *VERIFIED_PREVIEW.lock().unwrap_or_else(|e| e.into_inner()) = Some(preview);
    if !crate::rt::can_spawn() {
        return;
    }
    // spawn-detached: clears a process-wide slot that holds its session weakly; binding would pin it.
    crate::rt::spawn(async move {
        crate::rt::time::sleep(VERIFIED_PREVIEW_TTL).await;
        expire_verified_preview(seq);
    });
}

fn expire_verified_preview(seq: u64) {
    let mut slot = VERIFIED_PREVIEW.lock().unwrap_or_else(|e| e.into_inner());
    if slot.as_ref().is_some_and(|v| v.seq == seq) {
        *slot = None;
    }
}

/// Read-only rich preview of a public link: the decrypted bundle plus the LATEST
/// display metadata folded live from the Control Plane (a v2 bundle deliberately
/// carries no icon — the fold is the authority). Owner-root verification rides
/// the fold, so a forged-root link can't render a convincing preview; on a
/// fold/transport failure the bundle snapshot is the fallback. Nothing persists
/// — the caller hasn't joined.
pub async fn preview_public_link<T: Transport + ?Sized>(transport: &T, url: &str) -> Result<CommunityV2, String> {
    let bundle = fetch_public_bundle(transport, url).await?;
    preview_bundle(transport, &bundle).await
}

/// The fold half of [`preview_public_link`], over an already-fetched bundle. Split out so a caller
/// that only needs the community's IDENTITY can read it off the bundle (it is self-certifying) and
/// skip the Control-Plane walk entirely — the walk is the join gate, and `accept_public_link` runs
/// it again regardless.
pub async fn preview_bundle<T: Transport + ?Sized>(transport: &T, bundle: &CommunityInvite) -> Result<CommunityV2, String> {
    preview_bundle_checked(transport, bundle).await.map(|(c, _)| c)
}

/// [`preview_bundle`], saying whether the owner's root verified: when it didn't, the name,
/// description and icon are the link creator's word.
pub async fn preview_bundle_checked<T: Transport + ?Sized>(transport: &T, bundle: &CommunityInvite) -> Result<(CommunityV2, bool), String> {
    let community = CommunityV2::from_bundle(bundle, 0)?;
    match verify_owner_root_and_reconcile(transport, community.clone()).await {
        Ok(vj) => {
            let folded = vj.community;
            stash_verified_preview(VerifiedPreview {
                session: std::sync::Arc::downgrade(&crate::db::current_session()),
                at: web_time::Instant::now(),
                seq: 0,
                community_id: folded.id().0,
                community_root: folded.community_root,
                folded: folded.clone(),
                heads: vj.heads,
                banned: vj.banned,
                pins: vj.pins,
                writers: vj.writers,
                banlist_persist: vj.banlist_persist,
                roles: vj.roles,
                authority_heads: vj.authority_heads,
            });
            Ok((folded, true))
        }
        Err(_) => Ok((community, false)),
    }
}

/// Accept a public invite link: fetch its bundle (revocation-aware) and join.
pub async fn accept_public_link<T: Transport + ?Sized>(transport: &T, url: &str) -> Result<CommunityV2, String> {
    crate::db::scoped(async move {
        // Held across the network fetch so the join stays with one account.
        let bundle = fetch_public_bundle(transport, url).await?;
        accept_bundle(transport, &bundle, None, None).await
    })
    .await
}

/// Leave a community: publish a Guestbook Leave and tear down the local hold.
pub async fn leave_community<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> Result<(), String> {
    crate::db::scoped(async move {
        let at_ms = now_ms();
        publish_leave(transport, community, at_ms).await?;
        // Tombstone the membership across devices (CORD-02 §8) BEFORE the local delete.
        // Best-effort, but never silent: an unpublished tombstone is what lets a stale
        // copy of the list rejoin this community on a later boot.
        record_leave(transport, community.id(), &community.relays, at_ms).await;
        crate::db::community::delete_community(&crate::simd::hex::bytes_to_hex_32(&community.id().0))?;
        Ok(())
    })
    .await
}

/// The local half of a leave, for a caller that repaints at once: the List tombstone
/// kept pending (it outlives a restart), then the community dropped here, its epoch
/// keys kept for scrubbing our own past messages. Returns the leave's time for
/// [`announce_leave`].
pub fn leave_locally(community: &CommunityV2) -> Result<u64, String> {
    let at_ms = now_ms();
    add_pending_tombstone(community.id(), at_ms);
    crate::db::community::delete_community_retain_keys(&crate::simd::hex::bytes_to_hex_32(&community.id().0))?;
    Ok(at_ms)
}

/// [`leave_locally`] for a community this device lists but no longer holds, its chats having
/// outlived its row: they go, and the List tombstone is kept pending. `None` when nothing here
/// names the community.
pub async fn leave_unheld_locally(community_id: &crate::community::CommunityId) -> Option<u64> {
    let id_hex = crate::simd::hex::bytes_to_hex_32(&community_id.0);
    let named = crate::state::STATE.lock().await.chats.iter().any(|c| c.metadata.community_id() == Some(id_hex.as_str()));
    if !named {
        return None;
    }
    let at_ms = now_ms();
    add_pending_tombstone(community_id, at_ms);
    forget_community_chats(&id_hex, &[]).await;
    Some(at_ms)
}

/// The network half of [`leave_unheld_locally`]: the List tombstone alone, as no key is left
/// to seal a Guestbook Leave. The stock set stands in for the community's unknown relays.
pub async fn announce_unheld_leave<T: Transport + ?Sized>(transport: &T, community_id: &crate::community::CommunityId, at_ms: u64) {
    crate::db::scoped(async move { record_leave(transport, community_id, &invite::stock_relays(), at_ms).await }).await
}

/// Drop a left community's channel chats, messages included, from STATE and the database,
/// with any chat that still names the community.
pub async fn forget_community_chats(community_id: &str, channel_ids: &[String]) {
    let mut gone: Vec<String> = channel_ids.to_vec();
    {
        let mut st = crate::state::STATE.lock().await;
        for chat in &st.chats {
            if chat.metadata.community_id() == Some(community_id) && !gone.contains(&chat.id) {
                gone.push(chat.id.clone());
            }
        }
        st.chats.retain(|c| !gone.contains(&c.id));
    }
    for id in &gone {
        let _ = crate::db::chats::delete_chat(id);
    }
}

/// The network half of [`leave_locally`]: the Guestbook Leave, then the List
/// tombstone, which retries from its pending record until it lands.
pub async fn announce_leave<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, at_ms: u64) {
    crate::db::scoped(async move {
        if let Err(e) = publish_leave(transport, community, at_ms).await {
            crate::log_net_fail!("[Leave] no Guestbook Leave for {} ({})", &crate::simd::hex::bytes_to_hex_32(&community.id().0)[..8], e);
        }
        record_leave(transport, community.id(), &community.relays, at_ms).await;
    })
    .await
}

/// The Guestbook Leave, best-effort once sealed: the List tombstone is what makes a leave stick.
async fn publish_leave<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, at_ms: u64) -> Result<(), String> {
    let signer = crate::signer::active_signer()?;
    let my_pk = me_pk()?;
    let gb_group = super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
    let leave_rumor = guestbook::build_leave_rumor(my_pk, at_ms);
    if let Ok((wrap, _)) = guestbook::seal_guestbook_rumor_signed(&signer, my_pk, &leave_rumor, &gb_group, Timestamp::from_secs(at_ms / 1000)).await {
        let _ = transport.publish(&wrap, &community.relays).await;
    }
    Ok(())
}

/// Cooperative Kick (CORD-04 §6, Guestbook plane): name the target; every reader
/// honors it iff the signer holds KICK and strictly outranks them (the coalesce's
/// `can_kick`), so publishing without authority is inert. A kicked member may
/// rejoin with a fresh invite — cryptographic severance is the ban/refound path.
pub async fn kick_member<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, target: &PublicKey) -> Result<(), String> {
    crate::db::scoped(async move {
        assert_current_root(community)?;
        let signer = crate::signer::active_signer()?;
        let my_pk = me_pk()?;
        // Fast local pre-check; readers re-verify independently.
        let authority = fetch_authority(transport, community).await;
        let owner_hex = community.owner()?.to_hex();
        if !authority.roles.can_act_on_member(
            &my_pk.to_hex(),
            Some(&owner_hex),
            &target.to_hex(),
            crate::community::roles::Permissions::KICK,
        ) {
            return Err("not authorized to kick this member".to_string());
        }
        // CORD-04 §6 composition: a Kick is Role Removal THEN the directive — strip
        // first, so the target's rank is gone before the departure lands. Without it a
        // kicked admin leaves the memberlist still holding every management bit, and
        // every client keeps honoring their control editions.
        //
        // SKIPPED (not refused) when the strip isn't ours to make: a revoke needs
        // MANAGE_ROLES + strict outrank, and a KICK-only moderator still kicks — the
        // target just keeps their rank until an authorized strip lands. Each layer
        // validates on its own rule, so a missing one is a weaker removal, never a
        // broken one. A strip we DO attempt and lose is a hard error: proceeding would
        // publish a directive we know leaves rank behind.
        let target_hex = target.to_hex();
        let holds_roles = authority.roles.grants.iter().any(|g| g.member == target_hex && !g.role_ids.is_empty());
        let may_strip = authority.roles.can_act_on_member(
            &my_pk.to_hex(),
            Some(&owner_hex),
            &target_hex,
            crate::community::roles::Permissions::MANAGE_ROLES,
        );
        if holds_roles && may_strip {
            grant_roles_sealing(transport, community, target, Vec::new(), Seal::BestEffort)
                .await
                .map_err(|e| format!("could not strip this member's roles before kicking: {e}"))?;
        }
        let at_ms = now_ms();
        let gb_group = super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
        // A Kick is an authority action, so it cites its Grant like any other
        // (CORD-02 §5 / CORD-04 §5).
        let citation = required_authority_citation(community, &my_pk)?;
        let rumor = guestbook::build_kick_rumor(my_pk, *target, citation.as_ref(), at_ms);
        let (wrap, _) = guestbook::seal_guestbook_rumor_signed(&signer, my_pk, &rumor, &gb_group, Timestamp::from_secs(at_ms / 1000)).await
            .map_err(|e| e.to_string())?;
        transport.publish(&wrap, &community.relays).await?;
        Ok(())
    })
    .await
}

/// Write each ban's departure to the Guestbook (CORD-04 §6): a Kick dated at the ban, which the
/// banlist alone never records, so lifting it doesn't count a pre-ban Join again. Only for a
/// member whose standing Join predates their ban; a Join after it is a return and outranks the
/// Kick anyway. Dated by the ban, one signer's departure for a member is the same rumor from any
/// of their devices. Best-effort: returns how many landed.
async fn publish_ban_departures<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, targets: &[PublicKey]) -> usize {
    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
    let marks = crate::db::community::get_community_ban_marks(&cid_hex).unwrap_or_default();
    let (Ok((events, _)), Ok(owner), Ok(my_pk), Ok(signer)) =
        (crate::db::community::get_guestbook_shared(&cid_hex), community.owner(), me_pk(), crate::signer::active_signer())
    else {
        return 0;
    };
    let Ok(citation) = required_authority_citation(community, &my_pk) else { return 0 };
    let owner_hex = owner.to_hex();
    let roles = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
    let coalesced = guestbook::coalesce(&events, now_ms(), snapshot_authority_for(&cid_hex, community, &owner, &events, &roles).as_ref(), &kick_judge(&cid_hex, &owner_hex, &roles));
    drop(events);
    let gb_group = super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
    let mut landed = 0;
    for target in targets {
        let Some(&banned_secs) = marks.get(&target.to_hex()) else { continue };
        let at_ms = banned_secs.saturating_mul(1000);
        if !coalesced.get(target).is_some_and(|st| st.verdict == guestbook::Verdict::Joined && st.at_ms <= at_ms) {
            continue;
        }
        let rumor = guestbook::build_kick_rumor(my_pk, *target, citation.as_ref(), at_ms);
        let Some(rumor_id) = rumor.id.map(|id| id.to_bytes()) else { continue };
        let Ok((wrap, _)) = guestbook::seal_guestbook_rumor_signed(&signer, my_pk, &rumor, &gb_group, Timestamp::from_secs(banned_secs)).await else { continue };
        if let Err(e) = transport.publish(&wrap, &community.relays).await {
            crate::log_warn!("[Ban] departure for an un-banned member not published: {e}");
            continue;
        }
        landed += 1;
        let kick = guestbook::GuestbookEvent {
            rumor_id,
            entry: guestbook::GuestbookEntry::Kick { actor: my_pk, target: *target, citation: citation.clone(), at_ms },
            epoch: Some(community.root_epoch.0),
            observed_at: Some(now_ms() / 1000),
        };
        let _ = ingest_guestbook_event(community, kick, 0);
    }
    landed
}

/// Once a session, the owner writes the departure of every ban lifted before un-bans wrote
/// their own: a member whose ban this device remembers, still standing on a pre-ban Join and
/// silent since. Owner-only, so one signer writes it and each member gets one rumor.
pub async fn heal_ban_departures<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> Result<usize, String> {
    if !guestbook_walked_this_session(community) || community.owner()? != me_pk()? {
        return Ok(0);
    }
    if !session_plane_once::<BanDeparturesHealed>(community) {
        return Ok(0);
    }
    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
    let banned = crate::db::community::get_community_banlist(&cid_hex)?;
    let active: std::collections::HashMap<PublicKey, u64> = crate::db::community::community_member_activity_capped(&cid_hex, false)?
        .into_iter()
        .filter_map(|(npub, secs)| PublicKey::parse(&npub).ok().map(|pk| (pk, secs)))
        .collect();
    let lifted: Vec<PublicKey> = crate::db::community::get_community_ban_marks(&cid_hex)?
        .into_iter()
        .filter(|(hex, _)| !banned.contains(hex))
        .filter_map(|(hex, at)| PublicKey::from_hex(&hex).ok().map(|pk| (pk, at)))
        .filter(|(pk, at)| active.get(pk).is_none_or(|seen| seen <= at))
        .map(|(pk, _)| pk)
        .collect();
    if lifted.is_empty() {
        return Ok(0);
    }
    Ok(publish_ban_departures(transport, community, &lifted).await)
}

struct BanDeparturesHealed;
struct JoinAnnounced;

/// True the first time this session asks for `community`'s current Guestbook plane under `K`.
fn session_plane_once<K: 'static>(community: &CommunityV2) -> bool {
    let set = crate::db::current_session().scoped::<K, std::sync::Mutex<std::collections::HashSet<[u8; 32]>>>();
    let mut held = set.lock().unwrap_or_else(|e| e.into_inner());
    held.insert(guestbook_plane(community))
}

/// Publish my Join, keeping the same signed wrap going until a relay holds it, so a retry can
/// only ever land the one event. Marks the plane as announced this session.
async fn publish_my_join<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, wrap: Event) {
    session_plane_once::<JoinAnnounced>(community);
    if transport.publish(&wrap, &community.relays).await.is_ok() || crate::state::nostr_client().is_none() {
        return;
    }
    let relays = community.relays.clone();
    crate::db::spawn_bound(async move {
        let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
        if let Err(e) = transport.publish_durable(&wrap, &relays).await {
            crate::log_warn!("[Guestbook] Join still unpublished; the next session's walk will restore it: {e}");
        }
    });
}

/// CORD-02 §5: a member finding no state of their own on the Guestbook publishes a fresh Join.
/// Only after a whole walk of the plane, once a session, and dated by the plane itself (the
/// Refounding's cut, else its oldest entry), so my devices healing at once write one rumor.
pub async fn heal_my_join<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> Result<bool, String> {
    if !guestbook_walked_this_session(community) {
        return Ok(false);
    }
    let my_pk = me_pk()?;
    let owner = community.owner()?;
    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
    if my_pk == owner || crate::db::community::is_author_banned(&cid_hex, &my_pk) {
        return Ok(false);
    }
    let at_ms = {
        let (events, _) = crate::db::community::get_guestbook_shared(&cid_hex)?;
        let roles = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
        let authority = snapshot_authority_for(&cid_hex, community, &owner, &events, &roles);
        let state = guestbook::coalesce(&events, now_ms(), authority.as_ref(), &kick_judge(&cid_hex, &owner.to_hex(), &roles)).remove(&my_pk);
        if state.is_some_and(|st| st.verdict != guestbook::Verdict::Refounded) {
            return Ok(false);
        }
        let live = Some(community.root_epoch.0);
        let Some(at_ms) = guestbook::live_refound(&events, authority.as_ref(), now_ms().saturating_add(guestbook::MAX_FUTURE_MS))
            .map(|r| r.cut)
            .or_else(|| events.iter().filter(|e| e.epoch == live).map(|e| e.entry.at_ms()).min())
        else {
            return Ok(false);
        };
        at_ms
    };
    if !session_plane_once::<JoinAnnounced>(community) {
        return Ok(false);
    }
    let signer = crate::signer::active_signer()?;
    let rumor = guestbook::build_join_rumor(my_pk, None, at_ms);
    let gb_group = super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
    let (wrap, _) = guestbook::seal_guestbook_rumor_signed(&signer, my_pk, &rumor, &gb_group, Timestamp::from_secs(at_ms / 1000))
        .await
        .map_err(|e| e.to_string())?;
    crate::log_info!("[Guestbook] no Join of ours stands on this plane; restoring it");
    publish_my_join(transport, community, wrap).await;
    Ok(true)
}

/// The Timeouts running now (CORD-04 §8), by target: judged against the Roster as it
/// stands, like every authority action. Returns target → (from, until), unix seconds.
pub fn community_timeouts(community: &CommunityV2) -> Result<std::collections::BTreeMap<PublicKey, (u64, u64)>, String> {
    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
    let events = crate::db::community::get_guestbook_standing(&cid_hex)?;
    Ok(guestbook::active_timeouts(&events, now_ms() / 1000, &timeout_judge(community)?))
}

/// Who a Timeout may silence: MODERATE_MEMBERS, unbanned, a strict outrank and the Grant it cites.
pub(crate) fn timeout_judge(community: &CommunityV2) -> Result<impl Fn(&PublicKey, &PublicKey, Option<&crate::community::edition::AuthorityCitation>) -> bool, String> {
    use crate::community::roles::Permissions;
    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
    let roster = crate::db::community::get_community_roles(&cid_hex)?;
    let banned = crate::db::community::get_community_banlist(&cid_hex).unwrap_or_default();
    let owner = community.owner()?.to_hex();
    Ok(move |actor: &PublicKey, target: &PublicKey, vac: Option<&crate::community::edition::AuthorityCitation>| {
        let (a, t) = (actor.to_hex(), target.to_hex());
        // The roster check first: it is in memory, the citation's is a database read.
        t != owner
            && !banned.contains(&a)
            && roster.can_act_on_member(&a, Some(&owner), &t, Permissions::MODERATE_MEMBERS)
            && citation_is_synced(&cid_hex, &owner, &a, vac)
    })
}

/// Silence `target` for `seconds` (at most 28 days; 0 lifts a running Timeout). Every
/// reader honours it iff the signer holds MODERATE_MEMBERS and strictly outranks them.
pub async fn timeout_member<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, target: &PublicKey, seconds: u64) -> Result<(), String> {
    crate::db::scoped(async move {
        assert_current_root(community)?;
        let signer = crate::signer::active_signer()?;
        let my_pk = me_pk()?;
        let authority = fetch_authority(transport, community).await;
        let owner_hex = community.owner()?.to_hex();
        if !authority.roles.can_act_on_member(&my_pk.to_hex(), Some(&owner_hex), &target.to_hex(), crate::community::roles::Permissions::MODERATE_MEMBERS) {
            return Err("you can only time out members beneath you, with Timeout Members".to_string());
        }
        // Strictly after every Timeout that counts for them, so a lift outranks the one it lifts
        // even when a co-moderator's clock runs ahead.
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let judge = timeout_judge(community)?;
        let newest_held = crate::db::community::get_guestbook_standing(&cid_hex)?
            .iter()
            .filter_map(|e| match &e.entry {
                guestbook::GuestbookEntry::Timeout { actor, target: t, citation, at_ms, .. } if t == target && judge(actor, t, citation.as_ref()) => Some(*at_ms),
                _ => None,
            })
            .max()
            .unwrap_or(0);
        let at_ms = next_send_ms().max(newest_held.saturating_add(1).min(now_ms() + guestbook::MAX_FUTURE_MS));
        // A lift's `until` is past for every reader, however its date runs ahead.
        let until = if seconds == 0 { 0 } else { (now_ms() / 1000).saturating_add(seconds.min(guestbook::MAX_TIMEOUT_SECS)) };
        let gb_group = super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
        let citation = required_authority_citation(community, &my_pk)?;
        let rumor = guestbook::build_timeout_rumor(my_pk, *target, until, citation.as_ref(), at_ms);
        let rumor_id = rumor.id.map(|id| id.to_bytes()).unwrap_or_default();
        let (wrap, _) = guestbook::seal_guestbook_rumor_signed(&signer, my_pk, &rumor, &gb_group, Timestamp::from_secs(at_ms / 1000)).await.map_err(|e| e.to_string())?;
        transport.publish(&wrap, &community.relays).await?;
        // Held at once, so this device honours its own Timeout before the follow reads it back.
        let gate = guestbook_write_gate();
        let _gate = gate.lock().unwrap_or_else(|e| e.into_inner());
        let (events, cursor) = crate::db::community::get_guestbook_shared(&cid_hex)?;
        if events.get(&rumor_id).is_none() {
            let timeout = guestbook::GuestbookEvent {
                rumor_id,
                entry: guestbook::GuestbookEntry::Timeout { actor: my_pk, target: *target, until_secs: until, citation, at_ms },
                epoch: Some(community.root_epoch.0),
                observed_at: Some(at_ms / 1000),
            };
            store_guestbook_and_departures(community, &cid_hex, &[timeout], cursor)?;
        }
        Ok(())
    })
    .await
}

/// Whom a Nickname may name (CORD-04 §10), judged against the Roster as it stands: their own
/// takes `CHANGE_NICKNAME` and no citation; anyone else's takes `MANAGE_NICKNAMES`, a strict
/// outrank and the Grant it cites.
pub(crate) fn nickname_judge(community: &CommunityV2) -> Result<impl Fn(&PublicKey, &PublicKey, Option<&crate::community::edition::AuthorityCitation>) -> bool, String> {
    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
    let roster = crate::db::community::get_community_roles(&cid_hex)?;
    let banned = crate::db::community::get_community_banlist(&cid_hex).unwrap_or_default();
    let owner = community.owner()?.to_hex();
    Ok(move |actor: &PublicKey, target: &PublicKey, vac: Option<&crate::community::edition::AuthorityCitation>| {
        let (a, t) = (actor.to_hex(), target.to_hex());
        !banned.contains(&a) && roster.may_name(&a, Some(&owner), &t) && (a == t || citation_is_synced(&cid_hex, &owner, &a, vac))
    })
}

/// Every Nickname standing in a community, with the entry each stands on. A Refounding starts a
/// fresh Guestbook, so only the live epoch's count: what is carried across stands, for every reader.
pub fn standing_nicknames(community: &CommunityV2) -> Result<std::collections::BTreeMap<PublicKey, guestbook::Nickname>, String> {
    nicknames_on(community, Some(community.root_epoch.0))
}

/// The Nicknames standing over `epoch`'s Guestbook, or over every one this device holds.
fn nicknames_on(community: &CommunityV2, epoch: Option<u64>) -> Result<std::collections::BTreeMap<PublicKey, guestbook::Nickname>, String> {
    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
    let held = crate::db::community::get_guestbook_standing(&cid_hex)?;
    let events: Vec<guestbook::GuestbookEvent> = held.iter().filter(|e| epoch.is_none() || e.epoch == epoch).cloned().collect();
    let judge = nickname_judge(community)?;
    let silenced = community_timeouts(community)?;
    Ok(guestbook::standing_nicknames(&events, now_ms(), &judge, &silenced))
}

/// What each member is called in a community, for those who have a Nickname there.
/// The Nicknames as their writers set them, before a Timeout silences any: a Timeout is its
/// own change, not a Nickname one.
pub(crate) fn nicknames_as_set(community: &CommunityV2) -> Result<std::collections::BTreeMap<PublicKey, guestbook::Nickname>, String> {
    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
    let held = crate::db::community::get_guestbook_standing(&cid_hex)?;
    let events: Vec<guestbook::GuestbookEvent> = held.iter().filter(|e| e.epoch == Some(community.root_epoch.0)).cloned().collect();
    let judge = nickname_judge(community)?;
    Ok(guestbook::standing_nicknames(&events, now_ms(), &judge, &Default::default()))
}

pub fn community_nicknames(community: &CommunityV2) -> Result<std::collections::BTreeMap<PublicKey, String>, String> {
    Ok(standing_nicknames(community)?.into_iter().map(|(pk, n)| (pk, n.nick)).collect())
}

/// A Nickname as a writer sends it: trimmed, at most [`guestbook::MAX_NICKNAME_CHARS`], no
/// control characters. `""` clears.
pub fn clean_nickname(nick: &str) -> Result<String, String> {
    let nick = nick.trim();
    if nick.chars().any(char::is_control) {
        return Err("a nickname can't hold line breaks or control characters".to_string());
    }
    if nick.chars().count() > guestbook::MAX_NICKNAME_CHARS {
        return Err(format!("a nickname is at most {} characters", guestbook::MAX_NICKNAME_CHARS));
    }
    Ok(nick.to_string())
}

/// Seal and publish one Nickname, then hold it, so this device shows it before the follow
/// reads it back.
async fn publish_nickname<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, rumor: nostr_sdk::prelude::UnsignedEvent, entry: guestbook::GuestbookEntry) -> Result<(), String> {
    let signer = crate::signer::active_signer()?;
    let my_pk = me_pk()?;
    let at_ms = entry.at_ms();
    let rumor_id = rumor.id.map(|id| id.to_bytes()).unwrap_or_default();
    let gb_group = super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
    let (wrap, _) = guestbook::seal_guestbook_rumor_signed(&signer, my_pk, &rumor, &gb_group, Timestamp::from_secs(now_ms() / 1000)).await.map_err(|e| e.to_string())?;
    transport.publish(&wrap, &community.relays).await?;
    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
    let gate = guestbook_write_gate();
    let _gate = gate.lock().unwrap_or_else(|e| e.into_inner());
    let (events, cursor) = crate::db::community::get_guestbook_shared(&cid_hex)?;
    // A member's own carried Nickname is the very rumor they first sent, now on this epoch too.
    let stored = match events.get(&rumor_id) {
        Some(held) if held.epoch == Some(community.root_epoch.0) => return Ok(()),
        Some(held) => guestbook::GuestbookEvent { epoch: Some(community.root_epoch.0), ..held.clone() },
        None => guestbook::GuestbookEvent { rumor_id, entry, epoch: Some(community.root_epoch.0), observed_at: Some(at_ms / 1000) },
    };
    drop(events);
    store_guestbook_and_departures(community, &cid_hex, &[stored], cursor)
}

/// Name `target` in this community (`""` clears it): your own with Change Nickname, a member
/// beneath you with Manage Nicknames.
pub async fn set_nickname<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, target: &PublicKey, nick: &str) -> Result<(), String> {
    crate::db::scoped(async move {
        assert_current_root(community)?;
        let nick = clean_nickname(nick)?;
        let my_pk = me_pk()?;
        let authority = fetch_authority(transport, community).await;
        let owner_hex = community.owner()?.to_hex();
        let mine = *target == my_pk;
        if !authority.roles.may_name(&my_pk.to_hex(), Some(&owner_hex), &target.to_hex()) {
            return Err(if mine { "you can't change your nickname here".to_string() } else { "you can only change the nicknames of members beneath you, with Manage Nicknames".to_string() });
        }
        if mine {
            refuse_while_timed_out(community, &my_pk)?;
        }
        // Strictly after every Nickname that counts for them, so this one stands even when a
        // co-moderator's clock runs ahead.
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let judge = nickname_judge(community)?;
        let newest_held = crate::db::community::get_guestbook_standing(&cid_hex)?
            .iter()
            .filter_map(|e| match &e.entry {
                guestbook::GuestbookEntry::Nickname { actor, target: t, citation, at_ms, .. } if t == target && judge(actor, t, citation.as_ref()) => Some(*at_ms),
                _ => None,
            })
            .max()
            .unwrap_or(0);
        let at_ms = next_send_ms().max(newest_held.saturating_add(1).min(now_ms() + guestbook::MAX_FUTURE_MS));
        let citation = if mine { None } else { required_authority_citation(community, &my_pk)? };
        let rumor = guestbook::build_nickname_rumor(my_pk, *target, &nick, citation.as_ref(), at_ms);
        let entry = guestbook::GuestbookEntry::Nickname { actor: my_pk, target: *target, nick, citation, at_ms };
        publish_nickname(transport, community, rumor, entry).await
    })
    .await
}

/// Carry my own Nickname onto the Guestbook a Refounding began, dated as first issued, when the
/// Refounder didn't. Best-effort; a later sync tries again.
pub async fn carry_my_nickname<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> Result<(), String> {
    crate::db::scoped(async move {
        let my_pk = me_pk()?;
        let Some(mine) = nicknames_on(community, None)?.remove(&my_pk) else { return Ok(()) };
        let carried = standing_nicknames(community)?.remove(&my_pk);
        if carried.is_some_and(|c| c.nick == mine.nick || c.at_ms > mine.at_ms) || !nickname_judge(community)?(&my_pk, &my_pk, None) {
            return Ok(());
        }
        let rumor = guestbook::build_nickname_rumor(my_pk, my_pk, &mine.nick, None, mine.at_ms);
        let entry = guestbook::GuestbookEntry::Nickname { actor: my_pk, target: my_pk, nick: mine.nick, citation: None, at_ms: mine.at_ms };
        publish_nickname(transport, community, rumor, entry).await
    })
    .await
}

/// What a [`kick_members`] sweep actually managed to do.
#[derive(Debug, Default)]
pub struct KickSweep {
    pub kicked: Vec<PublicKey>,
    /// Targets the caller has no standing over, with the reason. Collected rather than
    /// returned as an error: one unkickable member must not sink the rest of the wave.
    pub refused: Vec<(PublicKey, String)>,
    /// Publishes that failed on the wire — transient, and safe to retry.
    pub failed: Vec<PublicKey>,
}

/// Kick many members in one sweep.
///
/// A Kick is an individual directive, unlike a Banlist edition which names every npub in
/// one document, so the wire cost here is inherently linear and there is nothing to
/// batch. What this saves is everything around it: [`kick_member`] folds the whole
/// control plane per call, so kicking a raid one at a time spends a paged network fetch
/// per target. Authority, citation and the plane key are resolved once and reused.
///
/// `on_progress(done, total)` fires after every target, refusals included, so a caller
/// can drive a counter through a sweep that takes minutes.
pub async fn kick_members<T: Transport + ?Sized>(
    transport: &T,
    community: &CommunityV2,
    targets: &[PublicKey],
    on_progress: &(dyn Fn(usize, usize) + Sync),
) -> Result<KickSweep, String> {
    crate::db::scoped(async move {
        assert_current_root(community)?;
        let mut out = KickSweep::default();
        if targets.is_empty() {
            return Ok(out);
        }
        let signer = crate::signer::active_signer()?;
        let my_pk = me_pk()?;
        let my_hex = my_pk.to_hex();
        let owner_hex = community.owner()?.to_hex();
        // ONCE. This is the paged control-plane fetch that makes the per-member path
        // unusable in bulk.
        let authority = fetch_authority(transport, community).await;
        let citation = required_authority_citation(community, &my_pk)?;
        let gb_group =
            super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);

        let total = targets.len();
        for (i, target) in targets.iter().enumerate() {
            let target_hex = target.to_hex();
            let outranks = |perm: u64| {
                authority.roles.can_act_on_member(&my_hex, Some(&owner_hex), &target_hex, perm)
            };
            if !outranks(crate::community::roles::Permissions::KICK) {
                out.refused.push((*target, "you do not outrank this member".to_string()));
                on_progress(i + 1, total);
                continue;
            }
            // CORD-04 §6: a Kick is Role Removal THEN the directive. Only a role-holder
            // pays for the strip, so a wave of plain members never touches the control
            // plane at all. A strip we attempt and lose skips the target rather than
            // publishing a directive we know leaves rank behind.
            let holds_roles =
                authority.roles.grants.iter().any(|g| g.member == target_hex && !g.role_ids.is_empty());
            if holds_roles && outranks(crate::community::roles::Permissions::MANAGE_ROLES) {
                if let Err(e) = grant_roles_sealing(transport, community, target, Vec::new(), Seal::BestEffort).await {
                    out.refused.push((*target, format!("could not strip roles before kicking: {e}")));
                    on_progress(i + 1, total);
                    continue;
                }
            }
            let at_ms = now_ms();
            let rumor = guestbook::build_kick_rumor(my_pk, *target, citation.as_ref(), at_ms);
            match guestbook::seal_guestbook_rumor_signed(
                &signer,
                my_pk,
                &rumor,
                &gb_group,
                Timestamp::from_secs(at_ms / 1000),
            )
            .await
            {
                Ok((wrap, _)) => match transport.publish(&wrap, &community.relays).await {
                    Ok(_) => out.kicked.push(*target),
                    Err(_) => out.failed.push(*target),
                },
                Err(_) => out.failed.push(*target),
            }
            on_progress(i + 1, total);
        }
        Ok(out)
    })
    .await
}

/// A community's folded, delegation-authorized authority — the on-demand read
/// view (a paged control-plane fetch + fold, nothing persisted). `roles` is the
/// owner-seeded authorized roster; `banned` the
/// enforced banlist. `floored`/`head_entities` let a writer detect a WITHHELD
/// entity (floored locally but no head folded) before replacing it blind.
pub struct AuthorityView {
    pub roles: crate::community::roles::CommunityRoles,
    pub banned: std::collections::BTreeSet<String>,
    /// Any authority entity's fold hit a floor gap (withheld / evicted link).
    pub gapped: bool,
    /// Entity hexes holding a persisted floor at this epoch (all vsk kinds).
    pub floored: std::collections::BTreeSet<String>,
    /// Authority entities (role/grant/banlist) that folded a head this fetch.
    pub head_entities: std::collections::BTreeSet<String>,
    /// Ban history (npub hex → secs), outliving the ban so an un-ban raises no phantom.
    pub banned_at: std::collections::BTreeMap<String, u64>,
    /// Roles v2 is active (CORD-04 §2): Roles are vsk 13, ordered by rank key.
    pub activated: bool,
    /// Who signed each member's Grant head, by member hex.
    pub grant_authors: std::collections::BTreeMap<String, String>,
    /// `@everyone`'s head was served this read, not carried from what this device held.
    pub everyone_served: bool,
}

/// Fetch + fold the community's current authority (CORD-04), paging older like
/// `follow_control` while the fold is gapped so a busy control plane can't push
/// the roster off the newest window. A fetch failure degrades fail-safe:
/// owner-only authority plus the PERSISTED banlist — nobody gains standing from
/// an outage, and a ban never lifts on withheld data.
/// Why a Control Plane read is no verdict: it stopped short of what this device tracks.
pub(super) const CONTROL_SHORT: &str = "the Control Plane couldn't be read whole";

/// The head a reader folds for the Writers ledger at `eid` from what the relays serve now, read
/// as deep as a follow and without persisting anything: `(self_hash, version)`. A read short of
/// what this device tracks is no verdict either way.
pub(super) async fn writers_head_on_relays<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, eid: &[u8; 32]) -> Result<Option<([u8; 32], u64)>, String> {
    let read = read_control(transport, community).await?;
    let eid_hex = crate::simd::hex::bytes_to_hex_32(eid);
    let head = read.fold.heads.iter().find(|h| h.entity_hex == eid_hex).map(|h| (h.self_hash, h.version));
    // A gap above the head is an edition nobody can link: it moves no reader past it.
    if read.truncated || read.authority.gapped || (head.is_none() && read.floors.contains_key(&eid_hex)) {
        return Err(CONTROL_SHORT.to_string());
    }
    Ok(head)
}

pub async fn fetch_authority<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> AuthorityView {
    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
    // As deep as a follow reads; a failed read keeps the persisted banlist (an empty fold retains it).
    let (floors, a, short) = match read_control(transport, community).await {
        Ok(read) => (read.floors, read.authority, read.truncated),
        Err(_) => {
            let floors: Floors = crate::db::community::get_all_edition_heads_full(&cid_hex)
                .unwrap_or_default()
                .into_iter()
                .filter(|(_, f)| f.0 == community.root_epoch.0)
                .map(|(entity, f)| (entity, (f.1, f.2, f.3, f.4, f.5)))
                .collect();
            let a = fold_authority(community, &[], &floors);
            (floors, a, true)
        }
    };
    let floors = floors_of_family(&floors, crate::db::community::FLOOR_AUTHORITY);
    let head_entities = a.settled().into_iter().map(String::from).collect();
    // The first head held for each entity, as a scan of the list would find it.
    let mut first_head: std::collections::HashMap<&str, &FoldedHead> = std::collections::HashMap::with_capacity(a.heads.len());
    for h in &a.heads {
        first_head.entry(h.entity_hex.as_str()).or_insert(h);
    }
    let grant_authors = a
        .roles
        .grants
        .iter()
        .filter_map(|g| {
            let member = crate::simd::hex::hex_to_bytes_32_checked(&g.member)?;
            let eid = crate::simd::hex::bytes_to_hex_32(&super::derive::grant_locator(community.id(), &member));
            let head = first_head.get(eid.as_str())?;
            Some((g.member.clone(), crate::simd::hex::bytes_to_hex_32(&head.author)))
        })
        .collect();
    let everyone_hex = crate::simd::hex::bytes_to_hex_32(&super::derive::everyone_locator(community.id()));
    let everyone_served = a.heads.iter().any(|h| h.entity_hex == everyone_hex);
    AuthorityView {
        roles: a.roles,
        banned: a.banned,
        gapped: a.gapped || short,
        floored: floors.keys().cloned().collect(),
        head_entities,
        banned_at: a.banned_at,
        activated: a.activated,
        grant_authors,
        everyone_served,
    }
}

/// When each member provably arrived, seconds: the earliest of their Joins across
/// the live plane and every epoch this client holds, lowered by any snapshot an
/// npub that may rotate the base already listed them in. A member re-joining
/// through a new link has been here since their first trace.
///
/// A Join's time is written by its author. With `watched` (this client was
/// following before the window opened), a member it saw arrive is dated by those
/// arrivals alone, each no earlier than when it was seen: an unwatched Join can
/// only be a backdate. Only members with a Join on the live plane appear; what this
/// client holds can date them earlier, never make anyone read as new.
fn earliest_arrivals(
    fetched: &[guestbook::GuestbookEvent],
    held: &[guestbook::GuestbookEvent],
    watched: bool,
    may_rotate: impl Fn(&PublicKey) -> bool,
) -> std::collections::BTreeMap<PublicKey, u64> {
    let seen_at: std::collections::HashMap<[u8; 32], u64> =
        fetched.iter().chain(held).filter_map(|ev| ev.observed_at.map(|o| (ev.rumor_id, o))).collect();
    let on_plane: std::collections::BTreeSet<PublicKey> = fetched
        .iter()
        .filter_map(|ev| match &ev.entry {
            guestbook::GuestbookEntry::Join { member, .. } => Some(*member),
            _ => None,
        })
        .collect();
    let mut claimed: std::collections::BTreeMap<PublicKey, u64> = std::collections::BTreeMap::new();
    let mut observed: std::collections::BTreeMap<PublicKey, u64> = std::collections::BTreeMap::new();
    for ev in fetched.iter().chain(held) {
        let guestbook::GuestbookEntry::Join { member, at_ms, .. } = &ev.entry else { continue };
        if !on_plane.contains(member) {
            continue;
        }
        let claim = at_ms / 1000;
        claimed.entry(*member).and_modify(|e| *e = (*e).min(claim)).or_insert(claim);
        if let Some(seen) = seen_at.get(&ev.rumor_id).filter(|_| watched) {
            let at = claim.max(*seen);
            observed.entry(*member).and_modify(|e| *e = (*e).min(at)).or_insert(at);
        }
    }
    let mut first = claimed;
    first.extend(observed);
    for ev in fetched.iter().chain(held) {
        if let guestbook::GuestbookEntry::Snapshot { refounder, members, at_ms, .. } = &ev.entry {
            if !may_rotate(refounder) {
                continue;
            }
            for m in members {
                if let Some(e) = first.get_mut(m) {
                    *e = (*e).min(at_ms / 1000);
                }
            }
        }
    }
    first
}

/// Page the Guestbook plane newest-to-oldest, stopping once a page's oldest wrap
/// falls below `since_secs` (everything older is already held) or the plane is
/// exhausted. Returns the parsed events at/after the window plus the newest wrap
/// time seen (the caller's next cursor; `since_secs` when nothing newer arrived).
///
/// PAGE bound rationale: a single 500-window silently drops a member whose Join
/// aged out (organic growth, or an insider flooding throwaway Joins), and
/// `refound_community` consumes the fold as its rekey recipient set — a dropped
/// member is SEVERED. Beyond this depth a community needs sharding (documented);
/// the granted-member union in [`fold_members`] is the consensus-complete
/// backstop regardless of Guestbook depth.
async fn fetch_guestbook_events<T: Transport + ?Sized>(
    transport: &T,
    community: &CommunityV2,
    since_secs: u64,
) -> Result<(Vec<guestbook::GuestbookEvent>, u64, bool), String> {
    fetch_guestbook_from(transport, community, &community.relays, since_secs, None, &Default::default()).await.map(|(events, newest, end, _)| (events, newest, end))
}

/// [`fetch_guestbook_events`] over `relays` from `start_until` down, with where it stopped when
/// the page cap came first, so a long walk goes on from there. A wrap in `opened` was opened by
/// another relay's read and is skipped here; each one opened is added.
async fn fetch_guestbook_from<T: Transport + ?Sized>(
    transport: &T,
    community: &CommunityV2,
    relays: &[String],
    since_secs: u64,
    start_until: Option<u64>,
    opened: &std::sync::Mutex<std::collections::HashSet<nostr_sdk::prelude::EventId>>,
) -> Result<(Vec<guestbook::GuestbookEvent>, u64, bool, Option<u64>), String> {
    let gb_group = super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
    const GB_PAGE: usize = 500;
    const GB_MAX_PAGES: usize = 12;
    let mut events = Vec::new();
    let mut newest: u64 = since_secs;
    let mut seen: std::collections::HashSet<nostr_sdk::prelude::EventId> = std::collections::HashSet::new();
    let mut until: Option<u64> = start_until;
    let mut oldest: Option<u64> = None;
    // Did the walk run out of PLANE, or out of PAGES? Only the former means the
    // caller holds everything down to `since_secs` — advancing a cursor on the
    // latter skips whatever the walk never reached, permanently.
    let mut reached_end = false;
    for _ in 0..GB_MAX_PAGES {
        // Full: this set becomes the refound's recipient list — a member's
        // Join visible only on a minority relay must not be severed.
        let query = Query {
            since: (since_secs > 0).then_some(since_secs),
            evidence: crate::community::transport::Evidence::Full,
            ..plane_page(gb_group.pk_hex(), GB_PAGE, until)
        };
        let wraps = transport.fetch(&query, relays).await?;
        let mut fresh = 0usize;
        let to_open: Vec<&Event> = {
            let opened = opened.lock().unwrap_or_else(|e| e.into_inner());
            wraps.iter().filter(|w| !seen.contains(&w.id) && w.created_at.as_secs() >= since_secs && !opened.contains(&w.id)).collect()
        };
        let _batch = stream::check_page(&to_open, &gb_group);
        for wrap in &wraps {
            if !seen.insert(wrap.id) {
                continue;
            }
            fresh += 1;
            let at = wrap.created_at.as_secs();
            if oldest.is_none_or(|o| at < o) {
                oldest = Some(at);
            }
            if at > newest {
                newest = at;
            }
            // Older than the cursor window — already held; skip the decrypt.
            if at < since_secs {
                continue;
            }
            if !opened.lock().unwrap_or_else(|e| e.into_inner()).insert(wrap.id) {
                continue;
            }
            if let Ok(opened) = stream::open_wrap(wrap, &gb_group) {
                if let Ok(ev) = guestbook::parse_guestbook_event(&opened) {
                    events.push(ev);
                }
            }
        }
        // A full page all seen before is a same-second wall, not the end: step past it.
        if fresh == 0 && wraps.len() >= GB_PAGE {
            match until {
                Some(u) if u > since_secs => {
                    until = Some(u - 1);
                    continue;
                }
                _ => {
                    reached_end = true;
                    break;
                }
            }
        }
        if fresh == 0 || wraps.len() < GB_PAGE || oldest.is_some_and(|o| o < since_secs) {
            reached_end = true;
            break;
        }
        match oldest {
            Some(o) if o > 0 => until = Some(o),
            // Nothing older to ask for.
            _ => {
                reached_end = true;
                break;
            }
        }
    }
    Ok((events, newest, reached_end, until))
}

/// The shared membership fold: coalesce Guestbook events under the community's
/// authority (owner-supreme kicks, refounder snapshots), union observed authors
/// plus every roster grantee, subtract the banlist, and pin the proven owner.
/// One implementation, so the live and stored reads can't drift.
/// Whose Guestbook snapshot seeds this community's CURRENT epoch (CORD-02 §5):
/// "honored only from the npub whose Refounding minted that epoch". That is the
/// owner only when the owner did the refounding.
///
/// The minter comes from the rotation this device VERIFIED and adopted, never from
/// the snapshot, so writing a snapshot grants nobody authority over it. Genesis
/// (epoch 0) has no refounder and therefore no snapshot power at all.
///
/// A device that arrived after the rotation (a joiner, a re-joiner) holds only this
/// epoch and never saw it. It takes the earliest of this epoch's snapshots written by
/// someone the roster lets rotate the base (the owner or a BAN holder, CORD-06): the
/// Refounder writes its snapshot as it mints the epoch, and a rival branch's snapshot
/// lands under that branch's own root, never this one. Failing that, the owner.
fn snapshot_authority_for(
    cid_hex: &str,
    community: &CommunityV2,
    owner: &PublicKey,
    events: &[guestbook::GuestbookEvent],
    roles: &crate::community::roles::CommunityRoles,
) -> Option<PublicKey> {
    let epoch = community.root_epoch.0;
    if epoch == 0 {
        return None;
    }
    if let Some(minted_by) = epoch_minters(cid_hex).get(&epoch).and_then(|h| PublicKey::from_hex(h).ok()) {
        return Some(minted_by);
    }
    let owner_hex = owner.to_hex();
    let may_rotate = |pk: &PublicKey| {
        pk == owner || roles.is_authorized(&pk.to_hex(), Some(&owner_hex), crate::community::roles::Permissions::BAN)
    };
    let earliest = events
        .iter()
        .filter(|ev| ev.epoch == Some(epoch))
        .filter_map(|ev| match &ev.entry {
            guestbook::GuestbookEntry::Snapshot { refounder, at_ms, .. } if may_rotate(refounder) => Some((*at_ms, *refounder)),
            _ => None,
        })
        .min_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.to_bytes().cmp(&b.1.to_bytes())));
    Some(earliest.map_or(*owner, |(_, pk)| pk))
}

fn fold_members(
    community: &CommunityV2,
    events: &[guestbook::GuestbookEvent],
    observed: std::collections::BTreeMap<PublicKey, u64>,
    roles: &crate::community::roles::CommunityRoles,
    banlist: &std::collections::BTreeSet<PublicKey>,
    banned_at: &std::collections::BTreeMap<PublicKey, u64>,
) -> Result<Vec<PublicKey>, String> {
    let parts = fold_member_parts(community, events, observed, roles, banlist, banned_at)?;
    let mut all = parts.counted;
    all.extend(parts.unlisted.into_keys());
    Ok(all.into_iter().collect())
}

/// [`fold_members`], split into who counts and who is only seen posting.
fn fold_member_parts(
    community: &CommunityV2,
    events: &[guestbook::GuestbookEvent],
    mut observed: std::collections::BTreeMap<PublicKey, u64>,
    roles: &crate::community::roles::CommunityRoles,
    banlist: &std::collections::BTreeSet<PublicKey>,
    banned_at: &std::collections::BTreeMap<PublicKey, u64>,
) -> Result<guestbook::MemberParts, String> {
    let owner = community.owner()?;
    let owner_hex = owner.to_hex();
    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);

    // CONSENSUS-COMPLETE backstop: every member the folded roster GRANTS a role to
    // is provably a member (a Grant binds member_xonly, CORD-02 A.6) — count them
    // even if their Join aged out of the Guestbook entirely and they never posted.
    // This is what keeps a Refounding from severing a lurking admin. `observed`
    // carries them at ts 0 (presence, not recency); the banlist subtraction below
    // still removes a banned grantee whose grant wasn't yet stripped.
    for g in &roles.grants {
        if let Some(pk) = PublicKey::from_hex(&g.member).ok().filter(|_| !g.role_ids.is_empty()) {
            observed.entry(pk).or_insert(0);
        }
    }

    // Snapshot authority (CORD-02 §5): whoever's Refounding minted the current epoch, an
    // admin's or a bot's as much as the owner's, so its survivors stay members without re-posting.
    let snapshot_authority_pk = snapshot_authority_for(&cid_hex, community, &owner, events, roles);
    let snapshot_authority = snapshot_authority_pk.as_ref();
    let can_kick = kick_judge(&cid_hex, &owner_hex, roles);
    let now = now_ms();
    let coalesced = guestbook::coalesce(events, now, snapshot_authority, &can_kick);
    // The live refound's guest list also gates the observed-forward path in
    // complete_memberlist, so a raid spammer whose Kick was buried by the rotation
    // isn't silently re-admitted by their old spam.
    let refound = guestbook::live_refound(events, snapshot_authority, now);
    let mut parts = guestbook::memberlist_parts(&coalesced, &observed, banlist, banned_at, refound.as_ref());
    // A role-holder the fold lists counts, however their activity is stamped: a Grant is
    // consensus, the same on every client.
    for g in roles.grants.iter().filter(|g| !g.role_ids.is_empty()) {
        if let Some(pk) = PublicKey::from_hex(&g.member).ok().filter(|pk| parts.unlisted.remove(pk).is_some()) {
            parts.counted.insert(pk);
        }
    }
    // The owner is a member by definition, independent of any fetched Join.
    if !banlist.contains(&owner) {
        parts.unlisted.remove(&owner);
        parts.counted.insert(owner);
    }
    Ok(parts)
}


/// What a [`rescue_stranded_members`] pass published.
#[derive(Debug, Default, serde::Serialize)]
pub struct RescueReport {
    /// Epoch hops that received catch-up blobs (1..=current, minus any with a missing root).
    pub hops: usize,
    /// Hops skipped because an archived root was missing — those members stay wedged there.
    pub hops_skipped: usize,
    pub chunks_published: usize,
    pub targets: usize,
}

/// Re-vend the epoch chain to members a past rotation forgot.
///
/// DELIBERATELY not surfaced in any client: [`refound_community`]'s recipient union
/// exists so this situation cannot arise from our own rotations. This stays as the
/// operator/SDK primitive for strandings we don't control — another client's rotation
/// folding a narrower memberlist, or a pre-union build. It re-keyed 39 live members
/// once; prevention is the product, this is the fire axe.
///
/// A client follows rekeys hop by hop: from its held root it derives ONE plane —
/// `base_rekey_group(held_root, cid, held_epoch + 1)` — and can never jump. A member
/// excluded from the recipient set at hop N therefore wedges at N−1 forever; no later
/// rotation can reach them because they cannot even derive where to look.
///
/// The rotator holds every archived root, so it can publish what should have existed:
/// for each hop, additional blobs addressed to the stranded set, built with the SAME
/// (rotator, scope, epoch, prev-commitment) as the original rotation. `collect_rotations`
/// correlates on exactly that key, so the catch-up blobs merge into the rotation every
/// client already validated — the stranded client's next follow simply finds its blob
/// and walks the whole chain forward. No action needed on their side; works on any
/// client version.
///
/// Intermediate blobs carry the CURRENT control pair (the historical pairs are not
/// archived). A mid-walk client briefly holds a future control address, and the final
/// hop — which every walk ends on — sets the same, correct pair.
///
/// A Guestbook snapshot addendum at the current epoch re-seeds the rescued members for
/// outside readers (the invite page) and for clients whose fold lost them.
pub async fn rescue_stranded_members<T: Transport + ?Sized>(
    transport: &T,
    community: &CommunityV2,
    targets: &[PublicKey],
) -> Result<RescueReport, String> {
    crate::db::scoped(async move {
        let mut report = RescueReport { targets: targets.len(), ..Default::default() };
        if targets.is_empty() {
            return Ok(report);
        }
        let signer = crate::signer::active_signer()?;
        let my_pk = me_pk()?;
        let cid = community.id();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&cid.0);
        let owner = community.owner()?;
        let owner_hex = owner.to_hex();
        // Key-granting is rotation-shaped authority: the receive side only honors blobs
        // inside rotations whose rotator it admits, so an unauthorized caller could only
        // publish noise — but fail loudly here rather than publish it.
        let roster = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
        if my_pk != owner && !roster.is_authorized(&my_pk.to_hex(), Some(&owner_hex), crate::community::roles::Permissions::BAN) {
            return Err("rescuing stranded members requires rotation authority (owner or BAN)".to_string());
        }
        let control_pk = community.control_pk.ok_or("rescue requires a split community (no control pk held)")?;
        let citation = my_authority_citation(community, &my_pk);

        // Every archived root, plus the live head (belt-and-suspenders: the head is
        // archived at rotation time, but the union costs nothing).
        let mut roots: std::collections::BTreeMap<u64, [u8; 32]> =
            crate::db::community::held_epoch_keys(&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX)?
                .into_iter()
                .map(|(e, k)| (e.0, k))
                .collect();
        roots.insert(community.root_epoch.0, community.community_root);

        let at_secs = now_ms() / 1000;
        for e in 1..=community.root_epoch.0 {
            let (Some(prev_root), Some(new_root)) = (roots.get(&(e - 1)).copied(), roots.get(&e).copied()) else {
                crate::log_warn!("[Rescue] no archived root for hop {} -> {} — members wedged there stay wedged", e - 1, e);
                report.hops_skipped += 1;
                continue;
            };
            let group = super::derive::base_rekey_group_key(&prev_root, cid, Epoch(e));
            let prev_commit = super::derive::epoch_key_commitment(Epoch(e - 1), &prev_root);
            // The catch-up EXTENDS the original rotation's chunk set: same correlation
            // key, indices past its highest slot. Re-claiming a slot is not an option —
            // collect_rotations keeps the first chunk per index, and if ours won, the
            // original recipients in the losing chunk would fold as removed.
            let existing = fetch_rekey_chunks(transport, &community, &group).await?;
            let start_after = existing
                .iter()
                .filter(|c| {
                    c.rotator == my_pk
                        && c.scope == super::rekey::RekeyScope::Root
                        && c.new_epoch == Epoch(e)
                        && c.prev_commit == prev_commit
                })
                .map(|c| c.chunk.0.max(c.chunk.1))
                .max()
                .unwrap_or(0);
            // The owner rides every catch-up chunk: an extension inherits the original
            // chunks' owner blob, but a plane a relay withheld folds ours standalone,
            // and a rotation without an owner blob is inadmissible by design.
            let mut recipients: Vec<PublicKey> = targets.to_vec();
            if !recipients.contains(&my_pk) {
                recipients.push(my_pk);
            }
            let mut blobs = Vec::with_capacity(recipients.len());
            for r in &recipients {
                // Staff get the control secret exactly as a live rotation would give it.
                let staff = *r == my_pk || roster.is_staff(&r.to_hex(), Some(&owner_hex));
                let ctl_root = if staff { community.control_root.as_ref() } else { None };
                blobs.push(
                    super::rekey::build_base_blob(&signer, &my_pk.to_bytes(), r, Epoch(e), &new_root, &control_pk.to_bytes(), ctl_root)
                        .await
                        .map_err(|e| e.to_string())?,
                );
            }
            // A rescue extension can fold STANDALONE on a withheld plane, so it
            // must re-state the hop's sever itself: from the fetched siblings, or
            // from the persisted mark when the plane withheld even those.
            let severed_hop = existing
                .iter()
                .any(|c| c.scope == super::rekey::RekeyScope::Root && c.new_epoch == Epoch(e) && c.severed)
                || sever_marks(&cid_hex).contains_key(&e);
            let chunks = super::rekey::build_rekey_chunk_extension(
                &signer,
                my_pk,
                &group,
                super::rekey::RekeyScope::Root,
                Epoch(e),
                Epoch(e - 1),
                &prev_commit,
                &blobs,
                at_secs,
                citation.as_ref(),
                severed_hop,
                start_after,
            )
            .await
            .map_err(|e| e.to_string())?;
            for c in &chunks {
                transport.publish_durable(c, &community.relays).await?;
                report.chunks_published += 1;
            }
            report.hops += 1;
        }

        // Re-seed them in the current epoch's Guestbook: snapshot chunks are
        // independently useful (CORD-02 §5), so an addendum under a fresh snap id folds
        // as Joined on every client and every outside reader. Best-effort, like a
        // rotation's own snapshot.
        let gb_group = super::derive::guestbook_group_key(&community.community_root, cid, community.root_epoch);
        let snap_id = crate::community::random_32();
        for rumor in guestbook::build_snapshot_rumors(my_pk, targets, snap_id, at_secs * 1000) {
            if let Ok((wrap, _)) = guestbook::seal_guestbook_rumor_signed(&signer, my_pk, &rumor, &gb_group, Timestamp::from_secs(at_secs)).await {
                let _ = transport.publish(&wrap, &community.relays).await;
            }
        }

        crate::log_info!(
            "[Rescue] {} member(s): {} hop(s) re-vended ({} skipped), {} chunk(s) published, snapshot addendum at epoch {}",
            targets.len(),
            report.hops,
            report.hops_skipped,
            report.chunks_published,
            community.root_epoch.0
        );
        Ok(report)
    })
    .await
}

/// Diagnostic: the memberlist as the WIRE alone tells it — the current epoch's
/// guestbook plane fetched fresh and folded with no local observation and no roster
/// backstop. This is what an outside reader (the invite page) computes, so the diff
/// against [`stored_memberlist`] is exactly the set a rotation left behind: counted
/// locally, absent from the snapshot, holding no current key.
pub async fn wire_guestbook_members<T: Transport + ?Sized>(
    transport: &T,
    community: &CommunityV2,
) -> Result<Vec<PublicKey>, String> {
    let (events, _newest, _reached_end) = fetch_guestbook_events(transport, community, 0).await?;
    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
    let owner = community.owner()?;
    let owner_hex = owner.to_hex();
    let roles = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
    let snapshot_authority_pk = snapshot_authority_for(&cid_hex, community, &owner, &events, &roles);
    let snapshot_authority = snapshot_authority_pk.as_ref();
    let can_kick = kick_judge(&cid_hex, &owner_hex, &roles);
    let coalesced = guestbook::coalesce(&events, now_ms(), snapshot_authority, &can_kick);
    let banlist: std::collections::BTreeSet<PublicKey> = crate::db::community::get_community_banlist(&cid_hex)
        .unwrap_or_default()
        .iter()
        .filter_map(|h| PublicKey::from_hex(h).ok())
        .collect();
    Ok(coalesced
        .iter()
        .filter(|(pk, st)| st.verdict == guestbook::Verdict::Joined && !banlist.contains(pk))
        .map(|(pk, _)| *pk)
        .collect())
}

/// Who the stored Guestbook folds as gone, by a Leave, an authorized Kick or a Refounding.
pub(crate) fn stored_departures(community: &CommunityV2) -> Vec<PublicKey> {
    stored_departure_times(community).into_keys().collect()
}

/// [`stored_departures`] with when each took effect: the Leave or Kick, or the Refounding's cut.
pub(crate) fn stored_departure_times(community: &CommunityV2) -> std::collections::HashMap<PublicKey, u64> {
    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
    let Ok((events, _cursor)) = crate::db::community::get_guestbook_shared(&cid_hex) else { return Default::default() };
    let Ok(owner) = community.owner() else { return Default::default() };
    let owner_hex = owner.to_hex();
    let roles = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
    let snapshot_authority_pk = snapshot_authority_for(&cid_hex, community, &owner, &events, &roles);
    let can_kick = kick_judge(&cid_hex, &owner_hex, &roles);
    guestbook::coalesce(&events, now_ms(), snapshot_authority_pk.as_ref(), &can_kick).into_iter().filter(|(_, st)| st.verdict != guestbook::Verdict::Joined).map(|(pk, st)| (pk, st.at_ms)).collect()
}

pub(crate) type DepartureSpans = crate::db::community::DepartureSpans;

struct DepartureCache;

/// Each member's spans away from `community`, per its stored Guestbook (CORD-03 §1). Folded once
/// per change to what the fold reads, not once per post judged.
pub(crate) fn stored_departure_windows(community: &CommunityV2) -> std::sync::Arc<DepartureSpans> {
    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
    let generation = crate::db::community::membership_generation();
    let cache = departure_cache();
    if let Some(held) = cache.lock().ok().and_then(|c| c.get(&cid_hex).cloned()) {
        if held.generation == generation {
            return held.spans;
        }
    }
    let (spans, due) = fold_departure_windows(community, &cid_hex);
    let spans = std::sync::Arc::new(spans);
    if let Ok(mut c) = cache.lock() {
        if c.get(&cid_hex).is_none_or(|held| held.generation <= generation) {
            c.insert(cid_hex, HeldDepartures { generation, spans: spans.clone(), due });
        }
    }
    spans
}

#[derive(Clone)]
struct HeldDepartures {
    generation: u64,
    spans: std::sync::Arc<DepartureSpans>,
    /// The earliest entry the fold left out as too far ahead: once it is due, fold again.
    due: Option<u64>,
}

fn departure_cache() -> std::sync::Arc<std::sync::Mutex<std::collections::HashMap<String, HeldDepartures>>> {
    crate::db::current_session().scoped::<DepartureCache, std::sync::Mutex<std::collections::HashMap<String, HeldDepartures>>>()
}

/// What storing some entries does to the windows held at the current membership generation.
enum DeparturesAfter {
    /// Only these members' windows can move: none for a Join or snapshot seed of members never away.
    Members(u64, Vec<PublicKey>),
    Refold,
}

/// Past this many members moved, one fold of everyone costs less than one fold each.
const MEMBER_REFOLDS_MAX: usize = 8;

fn departures_after<'a>(cid_hex: &str, entries: impl IntoIterator<Item = &'a guestbook::GuestbookEntry>) -> DeparturesAfter {
    use guestbook::GuestbookEntry;
    let cache = departure_cache();
    let Ok(c) = cache.lock() else { return DeparturesAfter::Refold };
    let Some(held) = c.get(cid_hex).filter(|h| h.generation == crate::db::community::membership_generation() && !h.is_due()) else {
        return DeparturesAfter::Refold;
    };
    let mut moved: Vec<PublicKey> = Vec::new();
    for entry in entries {
        let member = match entry {
            GuestbookEntry::Join { member, .. } if !held.spans.contains_key(member) => continue,
            GuestbookEntry::Join { member, .. } | GuestbookEntry::Leave { member, .. } | GuestbookEntry::Kick { target: member, .. } => member,
            GuestbookEntry::Snapshot { members, .. } if members.iter().all(|m| !held.spans.contains_key(m)) => continue,
            GuestbookEntry::Snapshot { .. } => return DeparturesAfter::Refold,
            _ => continue,
        };
        if !moved.contains(member) {
            moved.push(*member);
        }
        if moved.len() > MEMBER_REFOLDS_MAX {
            return DeparturesAfter::Refold;
        }
    }
    DeparturesAfter::Members(held.generation, moved)
}

impl HeldDepartures {
    fn is_due(&self) -> bool {
        self.due.is_some_and(|due| now_ms().saturating_add(guestbook::MAX_FUTURE_MS) >= due)
    }

    /// `due` once entries dated `at_ms` are stored: one too far ahead to fold yet comes due later.
    fn due_with(&self, at_ms: impl IntoIterator<Item = u64>) -> Option<u64> {
        let horizon = now_ms().saturating_add(guestbook::MAX_FUTURE_MS);
        self.due.into_iter().chain(at_ms.into_iter().filter(|&at| at > horizon)).min()
    }
}

/// Store `events` with the Guestbook write gate held, and bring the departure windows over the
/// write without folding everyone again.
fn store_guestbook_and_departures(community: &CommunityV2, cid_hex: &str, events: &[guestbook::GuestbookEvent], cursor_secs: u64) -> Result<(), String> {
    let after = departures_after(cid_hex, events.iter().map(|e| &e.entry));
    crate::db::community::store_guestbook_events(cid_hex, events, cursor_secs)?;
    departures_stored(community, cid_hex, after, events.iter().map(|e| e.entry.at_ms()));
    Ok(())
}

/// Bring windows held at `generation` over the one write that moved it on, which stored entries
/// dated `at_ms`. Any other write since moved it further, so what is brought over is never served.
fn departures_stored(community: &CommunityV2, cid_hex: &str, after: DeparturesAfter, at_ms: impl IntoIterator<Item = u64>) {
    let DeparturesAfter::Members(generation, moved) = after else { return };
    let cache = departure_cache();
    let held = cache.lock().ok().and_then(|c| c.get(cid_hex).filter(|h| h.generation == generation).cloned());
    let Some(held) = held else { return };
    if held.is_due() {
        return;
    }
    let spans = if moved.is_empty() {
        held.spans.clone()
    } else {
        let Some(folded) = with_departure_fold(community, cid_hex, |events, now, authority, can_kick| {
            moved.iter().map(|member| (*member, guestbook::member_departure_windows(events, member, now, authority, can_kick))).collect::<Vec<_>>()
        }) else {
            return;
        };
        let changed: Vec<_> = folded.into_iter().filter(|(member, windows)| !held.spans.get(member).map_or(windows.is_empty(), |was| was[..] == windows[..])).collect();
        if changed.is_empty() {
            held.spans.clone()
        } else {
            let mut spans = (*held.spans).clone();
            for (member, windows) in changed {
                if windows.is_empty() {
                    spans.remove(&member);
                } else {
                    spans.insert(member, windows.into());
                }
            }
            std::sync::Arc::new(spans)
        }
    };
    let due = held.due_with(at_ms);
    let mut c = cache.lock().unwrap_or_else(|e| e.into_inner());
    if let Some(entry) = c.get_mut(cid_hex).filter(|h| h.generation == generation) {
        *entry = HeldDepartures { generation: generation + 1, spans, due };
    }
}

/// Run `f` over the stored Guestbook with the Kick and snapshot judgements every departure
/// fold makes.
fn with_departure_fold<R>(
    community: &CommunityV2,
    cid_hex: &str,
    f: impl FnOnce(&[guestbook::GuestbookEvent], u64, Option<&PublicKey>, &dyn Fn(&PublicKey, &PublicKey, Option<&crate::community::edition::AuthorityCitation>) -> bool) -> R,
) -> Option<R> {
    let (events, _cursor) = crate::db::community::get_guestbook_shared(cid_hex).ok()?;
    let owner = community.owner().ok()?;
    let owner_hex = owner.to_hex();
    let roles = crate::db::community::get_community_roles(cid_hex).unwrap_or_default();
    let snapshot_authority_pk = snapshot_authority_for(cid_hex, community, &owner, &events, &roles);
    let can_kick = kick_judge(cid_hex, &owner_hex, &roles);
    Some(f(&events, now_ms(), snapshot_authority_pk.as_ref(), &can_kick))
}

fn fold_departure_windows(community: &CommunityV2, cid_hex: &str) -> (DepartureSpans, Option<u64>) {
    with_departure_fold(community, cid_hex, |events, now, authority, can_kick| {
        let horizon = now.saturating_add(guestbook::MAX_FUTURE_MS);
        let due = events.iter().map(|e| e.entry.at_ms()).filter(|&at| at > horizon).min();
        (guestbook::departure_windows(events, now, authority, can_kick).into_iter().map(|(member, spans)| (member, spans.into())).collect(), due)
    })
    .unwrap_or_default()
}

/// A departure this device hasn't owed for yet undoes what its member posted at a writer address
/// while it held, in every Channel that keeps a ledger: a Leave until the Join that ends it, a
/// Kick until the writer window it fell in ends, since one back after a Kick posts on a fresh
/// epoch. Judged against a durable record, so a departure that appears by a Roster or citation
/// landing later, or a pass cut short, is owed all the same. Only that member's writer posts are
/// owed, never from before the Channel's first writer window.
pub(crate) fn owe_new_departures(community: &CommunityV2) {
    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
    let Ok(seen) = crate::db::community::departures_seen(&cid_hex) else { return };
    let now = stored_departure_windows(community);
    if std::sync::Arc::ptr_eq(&now, &seen.spans) {
        return;
    }
    let mut ledgers: Option<Vec<(String, &super::writers::Ledger)>> = None;
    let (mut moved, mut owed) = (false, false);
    // Both are in key order: one walk pairs each member with what was seen of them.
    let mut was = seen.spans.iter().peekable();
    for (pk, spans) in now.iter() {
        while was.next_if(|(k, _)| *k < pk).is_some() {
            moved = true;
        }
        let before = was.next_if(|(k, _)| *k == pk).map(|(_, s)| s);
        if before == Some(spans) {
            continue;
        }
        moved = true;
        let mut fresh = spans.iter().filter(|w| !before.is_some_and(|s| s.contains(w))).peekable();
        if fresh.peek().is_none() {
            continue;
        }
        let ledgers = ledgers.get_or_insert_with(|| community.channels.iter().filter_map(|c| Some((crate::simd::hex::bytes_to_hex_32(&c.id.0), c.writers.as_ref()?))).collect());
        let author = pk.to_hex();
        let Ok(npub) = nostr_sdk::prelude::ToBech32::to_bech32(pk);
        for &(from, until, kicked) in fresh {
            for (chan, ledger) in ledgers.iter() {
                let Some(first) = ledger.writers().filter_map(|(e, ..)| ledger.writer_start(e)).min() else { continue };
                let since = from.max(first);
                let end = if kicked { ledger.writers().find(|(e, _, end)| ledger.writer_start(*e).is_some_and(|s| s <= since) && end.is_none_or(|end| end > since)).and_then(|(_, _, end)| end) } else { until };
                // A read that fails leaves the record unwritten, so the next pass owes it again.
                let Ok(posts) = crate::db::events::posts_since_by(chan, since, Some(&npub)) else { return };
                if posts.iter().any(|p| p.writer && end.is_none_or(|end| p.at_ms < end)) {
                    if crate::db::community::owe_author_retraction(&cid_hex, chan, &author, since, end).is_err() {
                        return;
                    }
                    owed = true;
                }
            }
        }
    }
    if !moved && was.next().is_none() {
        return;
    }
    if crate::db::community::set_departures_seen(&cid_hex, now.clone()).is_ok() && owed {
        super::realtime::enqueue_follow(community.id());
    }
}

/// Did the AUTHORIZED Guestbook coalesce rule `member` KICKED, per the stored plane?
///
/// This is the only sound basis for acting on a kick against ourselves. The
/// memberlist is the wrong question: it also folds the banlist, the ban marks and
/// observed authors, so a member whose Guestbook hasn't caught up yet — a REJOIN,
/// where the store starts empty while the control fold has already re-derived their
/// old ban mark — is absent from it while being perfectly joined. Coalescing asks
/// only "what is the latest authorized entry for this npub", so a fresh Join
/// supersedes an old Kick and an empty store yields no verdict at all.
pub fn stored_kick_verdict(community: &CommunityV2, member: &PublicKey) -> bool {
    stored_kick_at(community, member).is_some()
}

/// When the authorized Guestbook fold last ruled `member` kicked, if it does now.
/// The rumor of the Kick the authorized fold rules `member` kicked by, if it does.
pub fn stored_kick_rumor(community: &CommunityV2, member: &PublicKey) -> Option<[u8; 32]> {
    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
    let (events, _cursor) = crate::db::community::get_guestbook_shared(&cid_hex).ok()?;
    let owner = community.owner().ok()?;
    let owner_hex = owner.to_hex();
    let roles = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
    let snapshot_authority = snapshot_authority_for(&cid_hex, community, &owner, &events, &roles);
    let can_kick = kick_judge(&cid_hex, &owner_hex, &roles);
    guestbook::coalesce(&events, now_ms(), snapshot_authority.as_ref(), &can_kick)
        .get(member)
        .filter(|st| st.verdict == guestbook::Verdict::Kicked)
        .map(|st| st.rumor_id)
}

pub fn stored_kick_at(community: &CommunityV2, member: &PublicKey) -> Option<u64> {
    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
    let (events, _cursor) = crate::db::community::get_guestbook_shared(&cid_hex).ok()?;
    let owner = community.owner().ok()?;
    let owner_hex = owner.to_hex();
    let roles = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
    let snapshot_authority_pk = snapshot_authority_for(&cid_hex, community, &owner, &events, &roles);
    let snapshot_authority = snapshot_authority_pk.as_ref();
    let can_kick = kick_judge(&cid_hex, &owner_hex, &roles);
    guestbook::coalesce(&events, now_ms(), snapshot_authority, &can_kick)
        .get(member)
        .filter(|st| st.verdict == guestbook::Verdict::Kicked)
        .map(|st| st.at_ms)
}

/// The latest a local hold can date from. Rows keep whole seconds, so a join is never ruled older
/// than a removal it may have followed within the same second.
fn hold_bound_ms(c: &CommunityV2) -> u64 {
    c.created_at_ms.saturating_add(999)
}

/// Record an eviction this device obeyed in the synced List, at the evicting act's time: siblings and
/// the next boot then don't re-adopt it, and an invite sent after the act still lands.
pub fn record_eviction(community: &CommunityV2, removed_at: u64) {
    tombstone_community_list_durable(*community.id(), community.relays.clone(), removed_at);
}

/// Catch the persisted Guestbook up with what each relay holds of its plane: a relay that
/// reconciles is asked only for the wraps this device has not read, and one that cannot is read
/// by pages from its own cursor (see `control_sync`). Returns the entries that were NEW to the
/// store: the caller surfaces them (presence lines) and refreshes on non-empty.
pub async fn sync_guestbook<T: Transport + ?Sized>(
    transport: &T,
    community: &CommunityV2,
) -> Result<Vec<guestbook::GuestbookEvent>, String> {
    sync_guestbook_pass(transport, community).await.map(|(added, _)| added)
}

/// [`sync_guestbook`], and how the pass against the relays ended.
async fn sync_guestbook_pass<T: Transport + ?Sized>(
    transport: &T,
    community: &CommunityV2,
) -> Result<(Vec<guestbook::GuestbookEvent>, control_sync::PlaneSync), String> {
    // The store holds the Guestbook's entries, not its wraps, so it cannot tell an entry on the
    // plane from one only this device holds: what must be exactly the plane (a Refounding's
    // recipients, the late-joiner cut) still walks it.
    crate::db::scoped(async move {
        let view = guestbook_store::GuestbookView::of(community);
        let began = crate::rt::time::Instant::now();
        // Every relay is waited for: its Joins may be nobody else's.
        let sync = match control_sync::sync_plane(transport, community, &view, control_sync::Wait::All).await {
            Ok(sync) => sync,
            Err(control_sync::Unsynced::NoRelay(e) | control_sync::Unsynced::Store(e)) => return Err(e),
        };
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        if !sync.unread {
            // Read to the end on every relay that answered: the cursor says as of when.
            let gate = guestbook_write_gate();
            let _gate = gate.lock().unwrap_or_else(|e| e.into_inner());
            let now = crate::clock::now_secs();
            if crate::db::community::get_guestbook_shared(&cid_hex)?.1 < now {
                store_guestbook_and_departures(community, &cid_hex, &[], now)?;
                mark_guestbook_observed_since(&cid_hex);
            }
            drop(_gate);
            mark_guestbook_walked(community);
        }
        crate::log_debug!(
            "[v2:guestbook {}] {} wrap(s) read in, {} of {} relay(s) answered, short={} in {:?}",
            &cid_hex[..8],
            sync.opened,
            sync.answered(),
            sync.relays.len(),
            sync.unread,
            began.elapsed()
        );
        Ok((view.added(), sync))
    })
    .await
}

/// Store `fresh` entries read off the Guestbook plane this community holds the key to, merged
/// into the store as it stands. `newest` is their wraps' latest timestamp. Returns the ones the
/// store did not hold.
fn merge_guestbook(community: &CommunityV2, fresh: Vec<guestbook::GuestbookEvent>, newest: u64) -> Result<Vec<guestbook::GuestbookEvent>, String> {
    if fresh.is_empty() {
        return Ok(Vec::new());
    }
    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
    // The stamp is what lets the fold tell a Join carried over from a buried epoch apart from a
    // live one; a row stored before stamping existed earns its stamp on re-read.
    let live = Some(community.root_epoch.0);
    // Merged into the store as it stands now: another walk may have written while this one read.
    let gate = guestbook_write_gate();
    let _gate = gate.lock().unwrap_or_else(|e| e.into_inner());
    let (held, cursor) = crate::db::community::get_guestbook_shared(&cid_hex)?;
    // Where in `events` a rumor this walk stored sits; the rest are found in `held`.
    let mut written: std::collections::HashMap<[u8; 32], usize> = std::collections::HashMap::new();
    let mut events: Vec<guestbook::GuestbookEvent> = Vec::new();
    let mut added = Vec::new();
    let mut restamped = false;
    // A member's carried Nickname is the very rumor they first sent, now on this plane.
    let stamp = |had: &guestbook::GuestbookEvent| (had.epoch.is_none() || matches!(had.entry, guestbook::GuestbookEntry::Nickname { .. }) && had.epoch < live).then(|| guestbook::GuestbookEvent { epoch: live, ..had.clone() });
    for mut ev in fresh {
        ev.epoch = live;
        if let Some(&j) = written.get(&ev.rumor_id) {
            if let Some(stamped) = stamp(&events[j]) {
                events[j] = stamped;
                restamped = true;
            }
        } else if let Some(had) = held.get(&ev.rumor_id) {
            if let Some(stamped) = stamp(had) {
                written.insert(stamped.rumor_id, events.len());
                events.push(stamped);
                restamped = true;
            }
        } else {
            // First sight on THIS client. The author writes `at_ms`; they do not write this.
            if ev.observed_at.is_none() {
                ev.observed_at = Some(crate::clock::now_secs());
            }
            written.insert(ev.rumor_id, events.len());
            events.push(ev.clone());
            added.push(ev);
        }
    }
    drop(held);
    let advanced = cursor.max(newest);
    if !added.is_empty() || advanced > cursor || restamped {
        store_guestbook_and_departures(community, &cid_hex, &events, advanced)?;
        mark_guestbook_observed_since(&cid_hex);
        if !added.is_empty() {
            owe_new_departures(community);
        }
    }
    Ok(added)
}

/// Record a Guestbook wrap that came in live as read, once its entry is stored: a sync then
/// never asks a relay for it.
pub(crate) fn hold_guestbook_wrap(community: &CommunityV2, wrap: &Event) {
    guestbook_store::GuestbookView::of(community).hold(wrap);
}

/// Guestbook planes read to the end this session on every relay that answered: a Refounding
/// moves the plane, and the read starts again. Lives on the Session, so an account swap drops it
/// and the next account reads its own rather than inheriting this one's coverage.
struct GuestbookWalked;

fn guestbook_walked_set() -> std::sync::Arc<std::sync::Mutex<std::collections::HashSet<[u8; 32]>>> {
    crate::db::current_session().scoped::<GuestbookWalked, _>()
}

fn guestbook_walked_this_session(community: &CommunityV2) -> bool {
    guestbook_walked_set().lock().is_ok_and(|s| s.contains(&guestbook_plane(community)))
}

/// The Guestbook plane a community reads now: a Refounding moves it, and a walk with it.
fn guestbook_plane(community: &CommunityV2) -> [u8; 32] {
    super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch).pk().to_bytes()
}

/// Whether a relay's read of `community`'s Guestbook stopped short and has more to read.
pub(crate) fn guestbook_walk_pending(community: &CommunityV2) -> bool {
    control_sync::pending(community, &guestbook_store::GuestbookView::of(community))
}

fn mark_guestbook_walked(community: &CommunityV2) {
    if let Ok(mut s) = guestbook_walked_set().lock() {
        s.insert(guestbook_plane(community));
    }
}

/// A new session: no Guestbook read yet.
#[cfg(test)]
pub(crate) fn forget_session_walks_for_test() {
    guestbook_walked_set().lock().unwrap().clear();
}

struct GuestbookWrite;

/// Held across a Guestbook store's read, merge and write, never across an await, so one writer
/// never drops what another just stored.
fn guestbook_write_gate() -> std::sync::Arc<std::sync::Mutex<()>> {
    crate::db::current_session().scoped::<GuestbookWrite, _>()
}

/// Fold ONE live guestbook event into the store (the realtime path — no fetch).
/// Returns whether it was new.
pub fn ingest_guestbook_event(community: &CommunityV2, mut ev: guestbook::GuestbookEvent, wrap_secs: u64) -> Result<bool, String> {
    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
    let gate = guestbook_write_gate();
    let _gate = gate.lock().unwrap_or_else(|e| e.into_inner());
    let (events, cursor) = crate::db::community::get_guestbook_shared(&cid_hex)?;
    let live = Some(community.root_epoch.0);
    let stored = match events.get(&ev.rumor_id) {
        // A member's carried Nickname is the very rumor they first sent, now on this plane.
        Some(held) if !matches!(held.entry, guestbook::GuestbookEntry::Nickname { .. }) || held.epoch >= live => return Ok(false),
        Some(held) => guestbook::GuestbookEvent { epoch: live, ..held.clone() },
        None => {
            ev.epoch = live;
            ev
        }
    };
    drop(events);
    store_guestbook_and_departures(community, &cid_hex, std::slice::from_ref(&stored), cursor.max(wrap_secs))?;
    drop(_gate);
    owe_new_departures(community);
    Ok(true)
}

/// The memberlist from LOCAL state only: the persisted Guestbook, plus locally
/// observed authors (the synced events DB), plus roster grantees, minus the
/// banlist. Instant and offline-correct; [`sync_guestbook`] (post-join, boot,
/// reconnect, live ingest) keeps the store current. The live [`memberlist`]
/// remains the authoritative walk — a refounding's rekey recipient set must
/// never trust a possibly-stale store.
/// Unix seconds from which this client has been following `cid_hex`'s guestbook.
///
/// Set once, on the first sync that stores anything, and never moved forward. It is
/// what makes `observed_at` usable as evidence: a client that only started watching
/// AFTER a raid began sees every member as new, so its observations prove nothing and
/// must not be allowed to evict anyone.
fn guestbook_observed_since(cid_hex: &str) -> Option<u64> {
    crate::db::settings::get_sql_setting(format!("gb_observed_since:{cid_hex}"))
        .ok()
        .flatten()
        .and_then(|v| v.parse::<u64>().ok())
}

fn mark_guestbook_observed_since(cid_hex: &str) {
    let key = format!("gb_observed_since:{cid_hex}");
    if crate::db::settings::get_sql_setting(key.clone()).ok().flatten().is_some() {
        return; // never moves forward — a later stamp would erase our own coverage
    }
    let now = crate::clock::now_secs();
    let _ = crate::db::settings::set_sql_setting(key, now.to_string());
}

pub fn stored_memberlist(community: &CommunityV2) -> Result<Vec<PublicKey>, String> {
    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
    let (events, _cursor) = crate::db::community::get_guestbook_shared(&cid_hex)?;
    stored_memberlist_from(community, &events)
}

/// [`stored_memberlist`] over a guestbook the caller already holds, so a read that needs
/// the cursor too decrypts and parses the plane once.
pub fn stored_memberlist_from(community: &CommunityV2, events: &[guestbook::GuestbookEvent]) -> Result<Vec<PublicKey>, String> {
    memberlist_folded(community, events, false)
}

/// [`stored_memberlist`] where leaving counts whatever Role lingers: who may post and who
/// manages a restricted Channel's writers.
pub fn stored_memberlist_strict(community: &CommunityV2) -> Result<Vec<PublicKey>, String> {
    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
    let (events, _cursor) = crate::db::community::get_guestbook_shared(&cid_hex)?;
    memberlist_folded(community, &events, true)
}

/// The stored memberlist split into who counts and who is only seen posting: what a member
/// list and its counters show.
pub fn stored_member_parts(community: &CommunityV2, events: &[guestbook::GuestbookEvent]) -> Result<guestbook::MemberParts, String> {
    let (observed, roles, banlist, banned_at) = memberlist_inputs(community, false)?;
    fold_member_parts(community, events, observed, &roles, &banlist, &banned_at)
}

fn memberlist_folded(community: &CommunityV2, events: &[guestbook::GuestbookEvent], strict: bool) -> Result<Vec<PublicKey>, String> {
    let (observed, roles, banlist, banned_at) = memberlist_inputs(community, strict)?;
    fold_members(community, events, observed, &roles, &banlist, &banned_at)
}

type MemberlistInputs = (
    std::collections::BTreeMap<PublicKey, u64>,
    crate::community::roles::CommunityRoles,
    std::collections::BTreeSet<PublicKey>,
    std::collections::BTreeMap<PublicKey, u64>,
);

/// What the stored fold reads besides the Guestbook: activity, the roster, the banlist and ban history.
fn memberlist_inputs(community: &CommunityV2, strict: bool) -> Result<MemberlistInputs, String> {
    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
    let mut observed: std::collections::BTreeMap<PublicKey, u64> = std::collections::BTreeMap::new();
    let activity = if strict { crate::db::community::community_member_activity_strict(&cid_hex) } else { crate::db::community::community_member_activity(&cid_hex) };
    for (npub, last_active_secs) in activity.unwrap_or_default() {
        if let Ok(pk) = PublicKey::parse(&npub) {
            observed.insert(pk, last_active_secs.saturating_mul(1000));
        }
    }
    // For posting, only a newer Join brings back one who left, was kicked or refounded out.
    if strict {
        let gone: std::collections::HashSet<PublicKey> = stored_departures(community).into_iter().collect();
        observed.retain(|pk, ms| *ms == 0 || !gone.contains(pk));
    }
    let roles = crate::db::community::get_community_roles(&cid_hex)?;
    let banlist: std::collections::BTreeSet<PublicKey> = crate::db::community::get_community_banlist(&cid_hex)
        .unwrap_or_default()
        .iter()
        .filter_map(|h| PublicKey::from_hex(h).ok())
        .collect();
    // Ban history gates observation (CORD-02 §5). Read from the store, since this path never
    // folds editions.
    let banned_at: std::collections::BTreeMap<PublicKey, u64> = crate::db::community::get_community_ban_marks(&cid_hex)
        .unwrap_or_default()
        .into_iter()
        .filter_map(|(h, at)| PublicKey::from_hex(&h).ok().map(|pk| (pk, at)))
        .collect();
    Ok((observed, roles, banlist, banned_at))
}

/// Fold the Complete Memberlist from the Guestbook plane. The proven owner is
/// ALWAYS a member (derived from the self-certifying community_id — no network,
/// so a lost/evicted genesis Join can't drop them). Observed authors — anyone
/// seen publishing on a channel — are folded in FORWARD-only per CORD-02 §5, so a
/// member whose Join was lost still counts.
pub async fn memberlist<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> Result<Vec<PublicKey>, String> {
    let (events, _newest, _reached_end) = fetch_guestbook_events(transport, community, 0).await?;
    // Observed authors: fold each held channel's recent authorship (real author +
    // newest ms), so a member who posted but whose Join was lost is still counted.
    let mut observed: std::collections::BTreeMap<PublicKey, u64> = std::collections::BTreeMap::new();
    for ch in &community.channels {
        if let Ok(page) = fetch_channel(transport, community, &ch.id, 200).await {
            for f in &page {
                let e = observed.entry(f.event.opened().author).or_insert(0);
                *e = (*e).max(f.event.opened().at_ms);
            }
        }
    }

    // Fold the Control Plane roster + banlist (CORD-04) for Kick authority and the
    // ban subtraction. A control fetch failure degrades to owner-only authority + no
    // bans (fail-open on availability is safe here: a Kick still needs a real signer,
    // and a missed ban only fails to HIDE, never to wrongly admit authority).
    let authority = fetch_authority(transport, community).await;
    // The authorized banlist, as pubkeys (a malformed hex entry is simply dropped).
    let banlist: std::collections::BTreeSet<PublicKey> =
        authority.banned.iter().filter_map(|h| PublicKey::from_hex(h).ok()).collect();
    // Union the live fold's ban history with the stored marks: the fetch only reaches the
    // editions still in its window, and a ban that aged out is exactly the one whose
    // pre-ban Join would phantom.
    let mut banned_at: std::collections::BTreeMap<PublicKey, u64> = crate::db::community::get_community_ban_marks(
        &crate::simd::hex::bytes_to_hex_32(&community.id().0),
    )
    .unwrap_or_default()
    .into_iter()
    .filter_map(|(h, at)| PublicKey::from_hex(&h).ok().map(|pk| (pk, at)))
    .collect();
    for (h, at) in &authority.banned_at {
        if let Ok(pk) = PublicKey::from_hex(h) {
            let slot = banned_at.entry(pk).or_insert(0);
            *slot = (*slot).max(*at);
        }
    }
    fold_members(community, &events, observed, &authority.roles, &banlist, &banned_at)
}

// ── Dissolution (CORD-02 §9) ─────────────────────────────────────────────────

/// Owner dissolution / "Delete Community" (CORD-02 §9): publish the terminal
/// tombstone at the dissolved plane (`community_id`-derived, epoch-free, so every
/// past or present member resolves the same grave and a Refounding can never strand
/// it). The tombstone's presence IS the state; only the owner's seal counts.
/// Irreversible — on success the local hold is sealed read-only AND the owner's
/// own membership is tombstoned out of the §8 List: dissolving is also leaving,
/// so the owner's other devices tear the community down on their next list sync
/// instead of keeping a sealed husk they believe is still held.
pub async fn dissolve_community<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> Result<(), String> {
    crate::db::scoped(async move {
        let signer = crate::signer::active_signer()?;
        let my_pk = me_pk()?;
        if community.owner()? != my_pk {
            return Err("only the owner can dissolve a community".to_string());
        }
        let at_ms = now_ms();
        let at = at_ms / 1000;
        let rumor = super::dissolution::dissolved_tombstone_rumor(my_pk, community.id(), at);
        let wrap = super::dissolution::seal_dissolved_signed(&signer, my_pk, &rumor, community.id(), Timestamp::from_secs(at)).await.map_err(|e| e.to_string())?;
        // Durable broadcast: death must propagate (a rekey racing a dissolution loses).
        transport.publish_durable(&wrap, &community.relays).await?;
        crate::db::community::set_community_dissolved(&crate::simd::hex::bytes_to_hex_32(&community.id().0))?;
        // Dissolving IS leaving (same discipline as `leave_community`): retire the
        // membership from the cross-device List (kind 33302) in the same breath as the
        // grave, or sibling devices and §8 clients keep the entry LIVE and show a
        // dissolved husk. Best-effort with a durable
        // retry, never failing the dissolve: the grave is already published, and an
        // unrecorded leave only costs the husk lingering until the retry lands.
        record_leave(transport, community.id(), &community.relays, at_ms).await;
        Ok(())
    })
    .await
}

/// Whether a valid owner-signed dissolution tombstone exists for this community on
/// its relays (CORD-02 §9). A join refuses a dead community, and a live follow seals
/// on sight. Fail-OPEN on a fetch error (absence of proof is not death), but any
/// owner-verified tombstone found is authoritative.
pub async fn is_dissolved<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> bool {
    let group = super::derive::dissolved_group_key(community.id());
    let query = Query {
        kinds: vec![stream::KIND_WRAP],
        authors: vec![group.pk_hex()],
        limit: Some(20),
        ..Default::default()
    };
    let Ok(wraps) = transport.fetch(&query, &community.relays).await else {
        return false;
    };
    wraps.iter().any(|w| super::dissolution::verify_dissolved(w, &community.identity))
}

// ── Refounding (CORD-06 §3) ──────────────────────────────────────────────────

/// Owner/admin Refounding (CORD-06 §3): roll the `community_root` to
/// cryptographically remove `removed` from a Private community (a Ban's read-cut).
/// Compacts the Control Plane under the new root (re-wraps each head VERBATIM — the
/// inner owner/actor signatures survive, so no re-authoring), rekeys the base plus
/// every Private channel (each sealed under the PRIOR root, D2, so a base-fork loser
/// can still open them), and seeds the new epoch's Guestbook snapshot. Requires BAN.
///
/// **Acquire-before-commit:** the compaction is fetched + re-sealed BEFORE any
/// publish, and a head we can't fetch ABORTS with ZERO published state — so a
/// transient miss never strands a published rekey with a half-anchored plane.
pub async fn refound_community<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, removed: &[PublicKey]) -> Result<CommunityV2, String> {
    refound_community_with(transport, community, removed, false, 0, None).await
}

/// A SEVERING Refounding (CORD-06 Severing): the rotation carries the `sever`
/// marker, and every adopter — this client included — revokes its own public
/// invite links instead of refreshing them into the new epoch. The read-cut is
/// real even while the community was Public: the door closes with the rotation,
/// and only a deliberate fresh mint re-opens it.
pub async fn refound_community_severing<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, removed: &[PublicKey], joined_after_cut: u64) -> Result<CommunityV2, String> {
    refound_community_with(transport, community, removed, true, joined_after_cut, None).await
}

/// `joined_after_cut`: seconds. A member whose EARLIEST Join is at or after this is
/// vended no key. 0 disables it. The test is positive evidence only — a member with no
/// Join on the reachable guestbook (buried epoch, aged-out window) is NOT excluded, and
/// an unreadable guestbook excludes nobody. Absence must never evict: five rotations
/// once shed 39 real members that way.
/// Re-found vending keys to `retain` ONLY (plus the owner and this device).
///
/// An operator picked a list; anyone not on it gets nothing, whenever they arrived.
/// The removal-list form cannot express that: it is computed from the memberlist at
/// one instant while the refound fetches its own later, so an account that appears in
/// between is on neither list and is vended a key by default — implicitly RETAINED by
/// the very purge meant to be exhaustive. An allow-list has no such gap, and unlike a
/// join-time cut it is immune to a backdated (author-claimed) Join.
pub async fn refound_community_retaining<T: Transport + ?Sized>(
    transport: &T,
    community: &CommunityV2,
    removed: &[PublicKey],
    retain: &[PublicKey],
) -> Result<CommunityV2, String> {
    refound_community_with(transport, community, removed, false, 0, Some(retain)).await
}

async fn refound_community_with<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, removed: &[PublicKey], sever: bool, joined_after_cut: u64, allow_only: Option<&[PublicKey]>) -> Result<CommunityV2, String> {
    crate::db::scoped(async move {
        let cid = community.id();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&cid.0);
        // Death wins every race: a dissolved community never re-founds (CORD-02 §9).
        if crate::db::community::get_community_dissolved(&cid_hex).unwrap_or(false) {
            return Err("this community has been dissolved; it cannot be re-founded".to_string());
        }
        let signer = crate::signer::active_signer()?;
        let my_pk = me_pk()?;
        // Serialize with the follow worker for the whole rotation: the commit tail
        // whole-row-saves, and an unserialized concurrent follow could otherwise be
        // rolled back (or adopt a half-published sibling of this very rotation).
        let lock = super::realtime::follow_lock(cid);
        let _guard = lock.lock().await;
        // Read whole before the rotation replaces the Guestbook that records them.
        let _ = writing::read_whole(transport, community).await;
        let away = (*stored_departure_windows(community)).clone();
        // Reload the FRESHEST base state: a stale caller struct would address the rotation
        // under a superseded root (a base fork with no heal). The community_id is
        // self-certifying + stable, so re-loading by it is safe.
        let fresh = crate::db::community::load_community_v2(cid)?.ok_or("community gone before re-founding")?;
        let community = &fresh;
        let owner = community.owner()?;

        // CORD-06 §Authority: a Refounding requires the BAN permission and the rotator
        // must strictly OUTRANK every removed target — the owner is supreme (BAN ⊂
        // owner). Mirrors the receive counterpart (`advance_scope::base_rotator_ok`)
        // and the banlist authority fold: any admin holding BAN may re-found, checked
        // against the folded Roster. Fail-closed — an empty/unauthorized roster leaves
        // only the owner able to re-found.
        {
            let owner_hex = owner.to_hex();
            let me_hex = my_pk.to_hex();
            // Persisted (last-folded) roster — the receive side is authoritative, so
            // this is a belt-and-suspenders gate. Fail-closed: a stale/empty roster
            // collapses to owner-only, which can only OVER-restrict a fresh admin whose
            // grant hasn't folded into their own DB (the caller's ban flow folds control
            // first). It can never grant authority no one has.
            let roster = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
            let banned = crate::db::community::get_community_banlist(&cid_hex).unwrap_or_default();
            let authorized = my_pk == owner
                || (!banned.contains(&me_hex)
                    && roster.is_authorized(&me_hex, Some(&owner_hex), crate::community::roles::Permissions::BAN)
                    && removed.iter().all(|t| {
                        roster.can_act_on_member(&me_hex, Some(&owner_hex), &t.to_hex(), crate::community::roles::Permissions::BAN)
                    }));
            if !authorized {
                return Err("re-founding requires the BAN permission and outranking every removed member".to_string());
            }
        }

        // Fold the current roster: the opened editions are reused for the compaction (their
        // seals re-wrap under the new epoch), and the roster gates which admin-authored
        // heads carry forward.
        let floors: Floors = crate::db::community::get_all_edition_heads_full(&cid_hex)?
            .into_iter()
            .filter(|(_, f)| f.0 == community.root_epoch.0)
            .map(|(entity, f)| (entity, (f.1, f.2, f.3, f.4, f.5)))
            .collect();
        let current_control = control::ControlPlane::of(community);
        // Page the ENTIRE control plane, not just the newest window: the compaction MUST
        // carry EVERY committed (floored) entity to the new epoch, so a head buried under a
        // flood of newer editions (100 roles + 400 grants already exceeds one page) or a
        // head a relay withholds can't silently drop. CORD-06 §3 mandates aborting if the
        // Refounder cannot fold all Control Events — a dropped Banlist would unban a member
        // at the new epoch a fresh joiner bootstraps.
        const UNREAD: &str = "The community's control plane is too deep to read in full right now; re-founding stopped so no member is left behind.";
        // Through the wraps held once the store is on, each relay's own read behind them; by
        // pages when the store cannot serve it.
        let held_wraps = match control_store::mode() {
            control_store::Mode::On => whole_wraps_held(transport, community).await.ok(),
            _ => None,
        };
        let opened: Vec<(ParsedEdition, super::stream::OpenedStream)> = match held_wraps {
            Some(None) => return Err(UNREAD.to_string()),
            Some(Some(wraps)) => {
                let mut opened = Vec::with_capacity(wraps.len());
                for page in wraps.chunks(FOLLOW_PAGE) {
                    let _batch = current_control.check_page(&page.iter().collect::<Vec<_>>());
                    opened.extend(page.iter().filter_map(|w| current_control.open(w).ok()));
                }
                opened
            }
            None => {
            let mut opened: Vec<(ParsedEdition, super::stream::OpenedStream)> = Vec::new();
            let mut seen_wraps: std::collections::HashSet<nostr_sdk::prelude::EventId> = std::collections::HashSet::new();
            let mut oldest: Option<u64> = None;
            let mut until: Option<u64> = None;
            // Read to EXHAUSTION, not to coverage: an entity with no floor yet (a
            // first-ever Banlist published while we were away) is invisible to a
            // coverage test, so stopping there could compact it away.
            let mut truncated = false;
            for page in 0..COMPACT_MAX_PAGES {
                // Full: compaction re-wraps the head set it can SEE — a control
                // edition (a ban head) reachable only on a minority relay must not be
                // compacted away by a partial union.
                let query = Query { evidence: crate::community::transport::Evidence::Full, ..plane_page(current_control.pk_hex(), FOLLOW_PAGE, until) };
                let wraps = transport.fetch(&query, &community.relays).await?;
                let mut fresh = 0usize;
                let _batch = current_control.check_page(&wraps.iter().filter(|w| !seen_wraps.contains(&w.id)).collect::<Vec<_>>());
                for w in &wraps {
                    if !seen_wraps.insert(w.id) {
                        continue;
                    }
                    fresh += 1;
                    let at = w.created_at.as_secs();
                    if oldest.is_none_or(|o| at < o) {
                        oldest = Some(at);
                    }
                    if let Ok(parsed) = current_control.open(w) {
                        opened.push(parsed);
                    }
                }
                if fresh == 0 {
                    // `until` is inclusive: a FULL page with nothing new is a same-second
                    // wall no cursor steps past, so older editions stay unreachable. A
                    // short page is simply the end of the plane.
                    truncated = wraps.len() >= FOLLOW_PAGE;
                    break;
                }
                until = oldest;
                if page + 1 == COMPACT_MAX_PAGES {
                    truncated = true;
                }
            }
                if truncated {
                    return Err(UNREAD.to_string());
                }
                opened
            }
        };

        let prev_epoch = community.root_epoch;
        let new_epoch = Epoch(prev_epoch.0.checked_add(1).ok_or("root epoch overflow")?);
        let prev_commit = super::derive::epoch_key_commitment(prev_epoch, &community.community_root);
        // Mint-or-REUSE the new root, keyed by (scope, new_epoch) and archived BEFORE any
        // publish: a retried Refounding re-delivers the SAME root at this epoch/address, so
        // it can't double-mint two roots a receiver's correlation dedup would collapse into
        // a permanent fork (CORD-06 §3 idempotency). The compaction fetch above straddled
        let new_root = mint_or_reuse_rotation_key(&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX, new_epoch.0)?;
        // Every compliant base rotation mints the split beside the root (CORD-06
        // §3) — a legacy community upgrades as a side effect of this Refounding.
        // Reserved under the same retry-idempotency: both attempts must deliver ONE
        // pair, or staff adopt whichever secret rode the chunk with their locator.
        let new_control_root = mint_or_reuse_rotation_key(&cid_hex, crate::community::CONTROL_ROOT_SCOPE, new_epoch.0)?;
        let new_control_pk = super::derive::control_signer_group_key(&new_control_root, cid, new_epoch).pk();
        // The new epoch's Control plane is SPLIT: wraps sign with the fresh
        // control_root-derived signer and encrypt under the new community_root-
        // derived read key. Editions are never ALSO mirrored to the legacy-derived
        // address — that would re-open exactly the member-writable surface the
        // split closes (CORD-06 §3).
        let new_control = control::split_write_group(&new_control_root, &new_root, cid, new_epoch);
        let at = now_ms();
        let at_secs = at / 1000;

        // ACQUIRE + COVERAGE GATE (CORD-06 §3 MUST): re-wrap the head of EVERY committed
        // (floored) entity under the new epoch — FLOOR-driven, so nothing silently drops,
        // including entities the metadata/roster folds don't touch (the invite Registry
        // vsk-8, whose coordinate survives the rekey per CORD-05 §5). A floor whose head
        // can't be folded (buried past the pager / withheld) ABORTS before any publish.
        use std::collections::BTreeMap;
        let mut by_eid: BTreeMap<String, Vec<usize>> = BTreeMap::new();
        for (i, (e, _)) in opened.iter().enumerate() {
            by_eid.entry(crate::simd::hex::bytes_to_hex_32(&e.entity_id)).or_default().push(i);
        }
        // A held head the Roster now refuses, kept on this device for want of a fallback, is
        // not re-founded as if it stood: carry what a reader holding no floor folds instead.
        // Carry what this fold decides, never the floor as such: a head the fold steps down
        // from, or a banned signer's, would be read on its own at the new epoch.
        let eds: Vec<ParsedEdition> = opened.iter().map(|(e, _)| e.clone()).collect();
        let decided_authority = fold_authority(community, &eds, &floors);
        if !decided_authority.converged {
            return Err("re-founding aborted: the roster fold did not settle; no state published".to_string());
        }
        let decided_control = apply_control_fold(community, &eds, &floors, &decided_authority);
        // Authority heads first: a control head never takes an authority entity's place.
        let mut decided: std::collections::HashMap<String, [u8; 32]> = decided_control.heads.iter().map(|h| (h.entity_hex.clone(), h.inner_id)).collect();
        decided.extend(decided_authority.heads.iter().map(|h| (h.entity_hex.clone(), h.inner_id)));
        let (kept, kept_control, settled_absent) = (&decided_authority.carried, &decided_control.kept, &decided_authority.refused);
        // For a kept head, a floorless reader's pick (CORD-06 §3), and only one this device's own
        // evidence admits too.
        let cold: std::collections::HashMap<String, [u8; 32]> = if kept.is_empty() && kept_control.is_empty() {
            Default::default()
        } else {
            let cold_authority = fold_authority(community, &eds, &Floors::default());
            if !cold_authority.converged {
                return Err("re-founding aborted: the roster fold of a reader holding no floor did not settle; no state published".to_string());
            }
            let cold_control = apply_control_fold(community, &eds, &Floors::default(), &cold_authority);
            let mut cold: std::collections::HashMap<String, [u8; 32]> = cold_control
                .heads
                .into_iter()
                .filter(|h| decided_control.admitted.contains(&h.inner_id))
                .map(|h| (h.entity_hex, h.inner_id))
                .collect();
            cold.extend(cold_authority.heads.into_iter().filter(|h| decided_authority.admitted.contains(&h.inner_id)).map(|h| (h.entity_hex, h.inner_id)));
            cold
        };
        let mut carried: Vec<(FoldedHead, Event, &'static str)> = Vec::new();
        for (floor_key, floor) in &floors {
            // Re-wrap the AUTHORIZED head — the exact edition the persisted floor commits to,
            // signer included: the hash alone would take a copy re-signed under another key.
            // The floor advances ONLY to authorized heads (author-aware fold). `fold_head`'s
            // version-chain TIP is author-BLIND: a member can seal a forged higher-version
            // edition chaining onto the floor, which the tip would carry and honest folders
            // then DROP as unauthorized — silently suppressing that role/grant/banlist across
            // the refounding. Abort if the committed head isn't served (fail-closed).
            if settled_absent.contains(floor_key) {
                continue;
            }
            let pick = if kept.contains(floor_key) || kept_control.contains(floor_key) {
                // Refused whole for a floorless reader: nothing stands to carry.
                let Some(id) = cold.get(floor_key) else { continue };
                Some(*id)
            } else {
                decided.get(floor_key).copied()
            };
            let head_idx = match pick {
                Some(id) => by_eid.get(floor_key).and_then(|v| v.iter().copied().find(|&i| opened[i].0.inner_id == id)),
                None => by_eid.get(floor_key).and_then(|v| v.iter().copied().find(|&i| held_is(floor, &opened[i].0))),
            };
            let Some(head_idx) = head_idx else {
                return Err(format!("re-founding aborted: the committed head of control entity {floor_key} (v{}) was not served; no state published", floor.0));
            };
            let (head_ed, head_os) = &opened[head_idx];
            let h = FoldedHead { entity_hex: floor_key.clone(), version: head_ed.version, self_hash: head_ed.self_hash, inner_id: head_ed.inner_id, author: head_ed.author.to_bytes(), rebased: false };
            let (rewrapped, _) = super::stream::rewrap_seal(&head_os.seal, &new_control, Timestamp::from_secs(at_secs)).map_err(|e| e.to_string())?;
            carried.push((h, rewrapped, floor_family(&head_ed.vsk)));
        }
        // And every head the fold decided for an entity this device never floored: a first
        // Banlist published while it was away is as current as the rest.
        for (entity, id) in &decided {
            if floors.contains_key(entity) {
                continue;
            }
            let Some(i) = by_eid.get(entity).and_then(|v| v.iter().copied().find(|&i| opened[i].0.inner_id == *id)) else { continue };
            let (head_ed, head_os) = &opened[i];
            let h = FoldedHead { entity_hex: entity.clone(), version: head_ed.version, self_hash: head_ed.self_hash, inner_id: head_ed.inner_id, author: head_ed.author.to_bytes(), rebased: false };
            let (rewrapped, _) = super::stream::rewrap_seal(&head_os.seal, &new_control, Timestamp::from_secs(at_secs)).map_err(|e| e.to_string())?;
            carried.push((h, rewrapped, floor_family(&head_ed.vsk)));
        }
        // A sync is judged against the Category its predecessor names, so that predecessor
        // crosses beside it. The floor stays on the head.
        let mut beside: Vec<Event> = Vec::new();
        for (h, _, _) in &carried {
            let Some(group) = by_eid.get(&h.entity_hex) else { continue };
            let Some(head) = group.iter().map(|&i| &opened[i].0).find(|e| e.inner_id == h.inner_id) else { continue };
            let (true, Some(prev)) = (head.vsk == vsk::CHANNEL_SYNC, head.prev_hash) else { continue };
            // Compacted away before predecessors crossed: readers will refuse this sync either way.
            let Some(&pi) = group.iter().find(|&&i| opened[i].0.self_hash == prev) else {
                crate::log_warn!("[v2:refound] channel sync {} crosses without its predecessor", h.entity_hex);
                continue;
            };
            let (rewrapped, _) = super::stream::rewrap_seal(&opened[pi].1.seal, &new_control, Timestamp::from_secs(at_secs)).map_err(|e| e.to_string())?;
            beside.push(rewrapped);
        }

        // The Timeouts to carry, read after the Guestbook catches up so a lift this device
        // hasn't seen yet isn't undone.
        let _ = sync_guestbook(transport, community).await;
        let running_timeouts = community_timeouts(community).unwrap_or_default();
        let nicknames = standing_nicknames(community).unwrap_or_default();

        // Recipients: the current members minus `removed`, plus me (multi-device).
        //
        // UNION of the network fold and the LOCAL memberlist. The network fold only
        // observes the recent window, so a quiet member whose Join lives on a buried
        // epoch falls out of it — and out of the key set and snapshot — on every
        // rotation. Five rotations in one evening shed 39 real members that way, each
        // left wedged at the hop that first forgot them. Locally-known members are
        // vended keys too; being forgotten is not a removal, only `removed` is.
        let members = memberlist(transport, community).await?;
        let removed_set: std::collections::HashSet<[u8; 32]> = removed.iter().map(|p| p.to_bytes()).collect();
        let net_len = members.len();
        let mut union: std::collections::BTreeSet<PublicKey> = members.into_iter().collect();
        let local = stored_memberlist(community)?;
        let local_len = local.len();
        union.extend(local);
        let mut recipients: Vec<PublicKey> = union.into_iter().filter(|m| !removed_set.contains(&m.to_bytes())).collect();
        if !recipients.contains(&my_pk) {
            recipients.push(my_pk);
        }

        // The freshest roster reachable, for two per-recipient decisions below:
        // channel entitlement AND staff-ness (who receives the 136-byte blob).
        // Entitlement must come from a CURRENT roster, not the last-folded cache:
        // the base recipients above are a fresh network fold, and mixing the two
        // strands anyone granted since this client last folded — they keep a dead
        // key and the new epoch's rekey plane carries no blob for them. Fetched,
        // then merged over the cache so a role we published ourselves survives too.
        let mut roster_for_channels = fetch_authority(transport, community).await.roles;
        {
            let cached = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
            for r in cached.roles {
                if !roster_for_channels.roles.iter().any(|x| x.role_id == r.role_id) {
                    roster_for_channels.roles.push(r);
                }
            }
            for g in cached.grants {
                if !roster_for_channels.grants.iter().any(|x| x.member == g.member) {
                    roster_for_channels.grants.push(g);
                }
            }
        }
        let owner_hex_for_channels = community.owner().ok().map(|o| o.to_hex());

        // Operator purge: vend ONLY to the chosen list.
        //
        // Not a time test — a hard allow-list, so an account that arrived between the
        // operator's selection and this fetch is excluded by NOT BEING ON IT, with no
        // window to slip through and nothing to backdate. Owner and this device are
        // always kept: a purge must not orphan the community or lock out the operator
        // running it.
        if let Some(allow) = allow_only {
            let allowed: std::collections::HashSet<[u8; 32]> = allow.iter().map(|p| p.to_bytes()).collect();
            let before = recipients.len();
            recipients.retain(|r| {
                *r == my_pk
                    || Some(r.to_hex()) == owner_hex_for_channels
                    || allowed.contains(&r.to_bytes())
            });
            let dropped = before.saturating_sub(recipients.len());
            if dropped > 0 {
                crate::log_info!(
                    "[Refound {}] purge: {} member(s) not on the retain list vended no key",
                    &cid_hex[..8.min(cid_hex.len())], dropped
                );
            }
        }

        // Containment: vend no key to anyone who walked in DURING the raid.
        //
        // `removed` is a list computed at one instant; the recipient set above is a
        // LIVE fetch taken later, and re-taken on every retry. A bot joining in that
        // gap lands in the memberlist, misses the list, and is handed a working key
        // for the epoch meant to evict it. Testing the join TIME instead of matching a
        // frozen list is immune to when the fetch happens: a later read only surfaces
        // more late joiners, and each one fails the same test.
        //
        // Positive evidence only. No Join on the reachable guestbook means OLD (or
        // buried), never "new" — and an unreadable guestbook filters nobody, because
        // failing closed here would evict the whole community on one bad read.
        if joined_after_cut > 0 {
            match fetch_guestbook_events(transport, community, 0).await {
                Ok((events, _, _)) => {
                    // A Join's `at_ms` is written by its author, so a raider can
                    // backdate under any window computed from it. What this client
                    // WATCHED arrive, they cannot forge — but only if we were already
                    // following before the window opened. A client that started
                    // watching later sees everyone as new, and trusting it would evict
                    // the whole community.
                    let watched = guestbook_observed_since(&cid_hex).is_some_and(|since| since < joined_after_cut);
                    let (held, _) = crate::db::community::get_guestbook(&cid_hex).unwrap_or_default();
                    let first_seen = earliest_arrivals(&events, &held, watched, |pk| {
                        Some(pk.to_hex()) == owner_hex_for_channels
                            || roster_for_channels.is_authorized(
                                &pk.to_hex(),
                                owner_hex_for_channels.as_deref(),
                                crate::community::roles::Permissions::BAN,
                            )
                    });
                    let before = recipients.len();
                    recipients.retain(|r| {
                        if *r == my_pk || Some(r.to_hex()) == owner_hex_for_channels {
                            return true;
                        }
                        // A moderator who joined moments before a raid is still a moderator.
                        if roster_for_channels.is_staff(&r.to_hex(), owner_hex_for_channels.as_deref()) {
                            return true;
                        }
                        first_seen.get(r).is_none_or(|joined| *joined < joined_after_cut)
                    });
                    let dropped = before.saturating_sub(recipients.len());
                    if dropped > 0 {
                        crate::log_info!(
                            "[Refound {}] containment: {} raid-window joiner(s) vended no key",
                            &cid_hex[..8.min(cid_hex.len())], dropped
                        );
                    }
                }
                Err(e) => crate::log_warn!(
                    "[Refound {}] guestbook unreadable — raid-window joiners NOT filtered, only the named cut is severed ({e})",
                    &cid_hex[..8.min(cid_hex.len())]
                ),
            }
        }

        // STAFF COVERAGE GATE: a granted member who is not a recipient would be
        // stranded at this hop for good — they can only ever derive `held + 1`, so
        // no later rotation reaches them, while every other client still reads them
        // as staff. That is silent and permanent, and it happened: an admin holding
        // a valid grant was vended no key and only surfaced because a human noticed
        // the member list had shrunk.
        //
        // A grant is consensus-complete proof of membership — the same claim
        // `fold_members` makes when it counts granted members "even if their Join
        // aged out of the Guestbook entirely". So the recipients must cover them.
        // Refusing here matches the entity carry-forward directly above, which
        // ABORTS rather than publish a rotation that drops a floored head: better a
        // rotation that did not happen than one that quietly severs the staff.
        //
        // Only the CUT are exempt — removing someone is the one thing a rotation is
        // allowed to do to them.
        {
            // A banned member is not owed a key; every other grant-holder is.
            let banned = crate::db::community::get_community_banlist(&cid_hex).unwrap_or_default();
            let missing: Vec<String> = roster_for_channels
                .grants
                .iter()
                .filter(|g| !g.role_ids.is_empty())
                .filter_map(|g| PublicKey::from_hex(&g.member).ok())
                .filter(|pk| !removed_set.contains(&pk.to_bytes()))
                .filter(|pk| !banned.contains(&pk.to_hex()))
                .filter(|pk| !recipients.contains(pk))
                .map(|pk| pk.to_hex())
                .collect();
            if !missing.is_empty() {
                // The counts ride the message: which of the two folds lost them is
                // the whole diagnosis, and a refusal that does not say leaves the
                // next person guessing exactly as long as this one did.
                return Err(format!(
                    "re-founding aborted: {} granted member(s) would be vended no key and stranded at epoch {} — {}; \
                     recipients={} (network fold {}, local fold {}); no state published",
                    missing.len(),
                    prev_epoch.0,
                    missing.iter().map(|h| h[..8.min(h.len())].to_string()).collect::<Vec<_>>().join(", "),
                    recipients.len(),
                    net_len,
                    local_len
                ));
            }
        }

        // Base rekey blobs, sealed under the PRIOR root: every member's carries the
        // new root + control_pk (104 bytes); a STAFF recipient's (CORD-04 §3)
        // appends the control_root itself (136) — the rotator is staff by
        // construction (a Refounding takes BAN). A stale-roster overshoot hands a
        // just-demoted member only flooding power until the next rotation, the
        // spec's accepted erosion; an undershoot self-heals via the Grant's
        // control_wrap re-delivery.
        let mut base_blobs = Vec::new();
        for r in &recipients {
            let staff = *r == my_pk || roster_for_channels.is_staff(&r.to_hex(), owner_hex_for_channels.as_deref());
            base_blobs.push(
                super::rekey::build_base_blob(&signer, &my_pk.to_bytes(), r, new_epoch, &new_root, &new_control_pk.to_bytes(), staff.then_some(&new_control_root))
                    .await
                    .map_err(|e| e.to_string())?,
            );
        }
        let base_group = super::derive::base_rekey_group_key(&community.community_root, cid, new_epoch);
        let base_chunks =
            super::rekey::build_rekey_chunks(&signer, my_pk, &base_group, super::rekey::RekeyScope::Root, new_epoch, prev_epoch, &prev_commit, &base_blobs, at_secs, my_authority_citation(community, &my_pk).as_ref(), sever)
                .await
                .map_err(|e| e.to_string())?;

        // Private-channel rekeys: each mints a fresh key at its next channel-epoch, sealed
        // under the PRIOR root (D2). Public channels ride the base — no per-channel rekey.
        //
        // Each private channel goes only to ITS entitled set, never the base recipient
        // list: a Refounding that re-broadcast every private key to every member would
        // undo the access lists on every rotation (CORD-03).
        let mut channel_updates: Vec<(ChannelId, [u8; 32], Epoch)> = Vec::new();
        let mut channel_chunk_sets: Vec<Vec<Event>> = Vec::new();
        for ch in &community.channels {
            let (Some(old_key), true) = (ch.key, ch.private) else { continue };
            let ch_hex = crate::simd::hex::bytes_to_hex_32(&ch.id.0);
            let entitled: Vec<PublicKey> = recipients
                .iter()
                .copied()
                .filter(|r| {
                    *r == my_pk
                        || roster_for_channels.is_entitled(owner_hex_for_channels.as_deref(), &r.to_hex(), &ch_hex, &[], &[])
                })
                .collect();
            let ch_new_epoch = Epoch(ch.epoch.0.checked_add(1).ok_or("channel epoch overflow")?);
            // Mint-or-reuse per channel too, keyed by (channel_id, next epoch) — same
            // retry-idempotency as the base root. The base-rekey signing above is a bunker
            // round-trip; re-check before this per-channel DB write straddles it.
            let ch_new_key = mint_or_reuse_rotation_key(&cid_hex, &crate::simd::hex::bytes_to_hex_32(&ch.id.0), ch_new_epoch.0)?;
            let ch_prev_commit = super::derive::epoch_key_commitment(ch.epoch, &old_key);
            let mut ch_blobs = Vec::new();
            for r in &entitled {
                ch_blobs.push(
                    super::rekey::build_blob(&signer, &my_pk.to_bytes(), r, super::rekey::RekeyScope::Channel(ch.id), ch_new_epoch, &ch_new_key)
                        .await
                        .map_err(|e| e.to_string())?,
                );
            }
            let ch_group = super::derive::channel_rekey_group_key(&community.community_root, &ch.id, ch_new_epoch);
            let ch_chunks = super::rekey::build_rekey_chunks(&signer, my_pk, &ch_group, super::rekey::RekeyScope::Channel(ch.id), ch_new_epoch, ch.epoch, &ch_prev_commit, &ch_blobs, at_secs, my_authority_citation(community, &my_pk).as_ref(), false)
                .await
                .map_err(|e| e.to_string())?;
            channel_updates.push((ch.id, ch_new_key, ch_new_epoch));
            channel_chunk_sets.push(ch_chunks);
        }

        // COMMIT (durable publishes only — all fetching is done). Base rekey first
        // (delivers the new root), then channel rekeys, then the compacted control.
        for c in &base_chunks {
            transport.publish_durable(c, &community.relays).await?;
        }
        for set in &channel_chunk_sets {
            for c in set {
                transport.publish_durable(c, &community.relays).await?;
            }
        }
        for wrap in carried.iter().map(|(_, w, _)| w).chain(&beside) {
            transport.publish_durable(wrap, &community.relays).await?;
        }
        // Guestbook snapshot at the new epoch — best-effort (a Refounding succeeds without
        // it; an omitted member heals by publishing their own Join).
        let gb_group = super::derive::guestbook_group_key(&new_root, cid, new_epoch);
        let snap_id = crate::community::random_32();
        for rumor in guestbook::build_snapshot_rumors(my_pk, &recipients, snap_id, at) {
            if let Ok((wrap, _)) = guestbook::seal_guestbook_rumor_signed(&signer, my_pk, &rumor, &gb_group, Timestamp::from_secs(at_secs)).await {
                let _ = transport.publish(&wrap, &community.relays).await;
            }
        }
        // A running Timeout lives on the old Guestbook: the refounder re-issues, in its own
        // name, those it may issue itself, dated as issued so a later lift still wins and the
        // window doesn't move. Best-effort, like the snapshot.
        let owner_hex = community.owner()?.to_hex();
        let citation = required_authority_citation(community, &my_pk).ok().flatten();
        for (target, (from, until)) in running_timeouts {
            if removed_set.contains(&target.to_bytes())
                || !decided_authority.roles.can_act_on_member(&my_pk.to_hex(), Some(&owner_hex), &target.to_hex(), crate::community::roles::Permissions::MODERATE_MEMBERS)
            {
                continue;
            }
            let rumor = guestbook::build_timeout_rumor(my_pk, target, until, citation.as_ref(), from * 1000);
            if let Ok((wrap, _)) = guestbook::seal_guestbook_rumor_signed(&signer, my_pk, &rumor, &gb_group, Timestamp::from_secs(at_secs)).await {
                let _ = transport.publish_durable(&wrap, &community.relays).await;
            }
        }
        // Nicknames someone set for another member, each it could set itself, to the
        // millisecond. A member's own stands on their own word, so their client carries it.
        for (target, n) in nicknames {
            if n.actor == target || target == my_pk || !recipients.contains(&target) || !decided_authority.roles.may_name(&my_pk.to_hex(), Some(&owner_hex), &target.to_hex()) {
                continue;
            }
            let rumor = guestbook::build_nickname_rumor(my_pk, target, &n.nick, citation.as_ref(), n.at_ms);
            if let Ok((wrap, _)) = guestbook::seal_guestbook_rumor_signed(&signer, my_pk, &rumor, &gb_group, Timestamp::from_secs(at_secs)).await {
                let _ = transport.publish_durable(&wrap, &community.relays).await;
            }
        }

        // COMMIT locally, only now that the new root + compacted plane are on relays.
        if !crate::db::community::community_held(cid)? {
            return Ok(community.clone()); // left/deleted mid-rotation — don't resurrect.
        }
        // Save the new root/epoch + rekeyed channel keys in ONE tx FIRST, so a crash can
        // never leave the base root advanced while the channel keys lag (which would
        // re-derive the channel rekey address under the wrong root and orphan them).
        let mut updated = community.clone();
        updated.community_root = new_root;
        updated.root_epoch = new_epoch;
        updated.control_pk = Some(new_control_pk);
        updated.control_root = Some(new_control_root);
        for (id, key, ep) in &channel_updates {
            if let Some(c) = updated.channels.iter_mut().find(|c| c.id.0 == id.0) {
                c.key = Some(*key);
                c.epoch = *ep;
            }
        }
        crate::db::community::save_community_v2(&updated)?;
        for wrap in carried.iter().map(|(_, w, _)| w).chain(&beside) {
            hold_wrap(&updated, wrap);
        }
        archive_control_address(&cid_hex, community.root_epoch.0, community.control_pk.as_ref());
        archive_control_address(&cid_hex, new_epoch.0, updated.control_pk.as_ref());
        // Archive the new epoch key + confirm the monotonic base head (the root was already
        // archived by mint_or_reuse, so this is idempotent). Record the carried heads at
        // the NEW epoch; if a crash skips this, the epoch-filtered floors bootstrap the
        // compacted control on the next follow, so they self-heal.
        crate::db::community::advance_server_root_epoch(&cid_hex, new_epoch.0, &new_root)?;
        for (h, _, family) in &carried {
            crate::db::community::set_family_head_at_epoch(&cid_hex, &h.entity_hex, h.version, &h.self_hash, &h.inner_id, &h.author, new_epoch.0, family)?;
        }
        // Re-subscribe NOW: the rotation changed every plane author, and the live sub
        // still carries the OLD epoch's set. Members adopt via the follow worker
        // (which refreshes); the REFOUNDER has no such path — without this, the very
        // client that performed the ban goes deaf to the new epoch (a rejoin lands on
        // the relays and never arrives live).
        if let Some(client) = crate::state::nostr_client() {
            super::realtime::refresh_subscription(&client).await;
        }
        // We minted this epoch, so our own snapshot is what seeds it (CORD-02 §5).
        // Recorded here so the local fold agrees with every follower's without
        // waiting to adopt our own rotation back off the wire.
        record_epoch_minter(&cid_hex, new_epoch.0, &my_pk.to_hex());
        if sever {
            // Severing: the mark persists FIRST (a crash between it and the revoke
            // must retry, not forget — B4), then my own links are tombstoned. Other
            // creators' links die when their clients adopt the marked rotation.
            add_sever_mark(&cid_hex, new_epoch.0, at_secs);
            for attempt in 0..3u8 {
                match sever_own_links(transport, &updated).await {
                    Ok(_) => break,
                    Err(e) if attempt == 2 => {
                        crate::log_warn!("v2: post-severing link revocation failed after retries ({e}); the sever mark retries it on the next follow");
                    }
                    Err(_) => continue,
                }
            }
        } else {
            // Refresh any live public links so their bundles carry the NEW root behind the
            // same URL (a link shared once survives the rotation, CORD-05 §2). Idempotent,
            // so retry a transient failure — a stranded link lands a new joiner on the dead
            // pre-refound epoch, and there's no other trigger to heal it before the next
            // refounding. A persistent failure is logged (refound already succeeded).
            for attempt in 0..3u8 {
                match refresh_public_links(transport, &updated).await {
                    Ok(()) => break,
                    Err(e) if attempt == 2 => {
                        crate::log_warn!("v2: post-refounding public-link refresh failed after retries ({e}); live links may serve the prior root until the next refresh");
                    }
                    Err(_) => continue,
                }
            }
        }
        for (id, ..) in &channel_updates {
            reseal_rotated(transport, &updated, id).await;
        }
        // A restricted Channel's writer key may be held by those this Refounding removed.
        writing::retire_after_refounding(transport, &updated, &away).await;
        Ok(updated)
    })
    .await
}

/// Mint a fresh 32-byte rotation key for `(scope, new_epoch)`, or REUSE the one
/// already archived from a prior (aborted) attempt — so a retried Refounding re-
/// delivers the SAME key at the same epoch/address instead of double-minting two roots
/// a receiver's correlation dedup would collapse into a permanent fork (CORD-06 §3
/// idempotency). Archived BEFORE the first publish; `scope` is the all-zero server-root
/// sentinel for a base rotation, else the channel_id hex.
fn mint_or_reuse_rotation_key(community_id_hex: &str, scope_hex: &str, new_epoch: u64) -> Result<[u8; 32], String> {
    if let Some(existing) = crate::db::community::held_epoch_key(community_id_hex, scope_hex, new_epoch)? {
        return Ok(existing);
    }
    let fresh = crate::community::random_32();
    crate::db::community::store_epoch_key(community_id_hex, scope_hex, new_epoch, &fresh)?;
    Ok(fresh)
}

// ── The Community List (kind 33302, CORD-02 §8) ──────────────────────────────

/// This community's MEMBERSHIP subset for the Community List (CORD-02 §8): never the
/// icon (a rehydrating device folds it from the Control Plane), never the link
/// fields. Only PRIVATE channel keys ride — public channels derive from the root.
fn join_material(community: &CommunityV2) -> super::list::JoinMaterial {
    let hex = crate::simd::hex::bytes_to_hex_32;
    let channels = community
        .channels
        .iter()
        .filter(|c| c.private)
        // Keyed channels ONLY. A keyless entry is readable by this build but is
        // rejected outright by shipped ones (their `key` is a required String),
        // so emitting one would strand every older client on a stale list.
        .filter_map(|c| {
            c.key.map(|k| super::list::ChannelKeyRef { id: hex(&c.id.0), key: Some(hex(&k)), epoch: c.epoch.0, name: c.name.clone(), extra: Default::default() })
        })
        .collect();
    super::list::JoinMaterial {
        community_id: hex(&community.identity.community_id.0),
        owner: hex(&community.identity.owner_xonly),
        owner_salt: hex(&community.identity.owner_salt),
        community_root: hex(&community.community_root),
        root_epoch: community.root_epoch.0,
        control_pk: community.control_pk.map(|p| p.to_hex()),
        // The list carries every private key its holder has (CORD-02 §8) — a
        // staffer's own devices must be able to write. Same trust class as the
        // community_root beside it: NIP-44-encrypted to self.
        control_root: community.control_root.map(|r| hex(&r)),
        channels,
        relays: community.relays.clone(),
        name: community.name.clone(),
        rev: 0,
        extra: Default::default(),
    }
}

/// Our snapshot as this write publishes it: what this device holds, merged with the
/// same epoch's copy it read, one revision past that copy when the merge changes
/// anything (CORD-02 §8).
///
/// The merge is what makes revisions safe: a newer revision wins outright, so a
/// device behind its sibling — a channel key it has not received, a staff key, a
/// peer client's own fields (Armada's `priors` are retired keys) — would otherwise
/// publish its smaller view one revision up and erase them everywhere. Only names
/// and relays are ours to overwrite: both come from this device's Control fold.
/// Across a Refounding the read copy is a different snapshot and nothing is merged.
fn rebuild_snapshot(mut ours: super::list::JoinMaterial, theirs: Option<&super::list::JoinMaterial>) -> super::list::JoinMaterial {
    let Some(theirs) = theirs else {
        ours.channels.sort_by(|a, b| a.id.cmp(&b.id));
        return ours;
    };
    if theirs.root_epoch == ours.root_epoch {
        if ours.control_root.is_none() && ours.control_pk == theirs.control_pk {
            ours.control_root = theirs.control_root.clone();
        }
        for t in &theirs.channels {
            let Some(c) = ours.channels.iter_mut().find(|c| c.id == t.id) else {
                ours.channels.push(t.clone());
                continue;
            };
            if t.epoch > c.epoch {
                c.epoch = t.epoch;
                c.key = t.key.clone();
            } else if t.epoch == c.epoch && c.key.is_none() {
                c.key = t.key.clone();
            }
            if t.epoch == c.epoch {
                for (k, v) in &t.extra {
                    c.extra.entry(k.clone()).or_insert_with(|| v.clone());
                }
            }
        }
        for (k, v) in &theirs.extra {
            ours.extra.entry(k.clone()).or_insert_with(|| v.clone());
        }
    }
    // One canonical order, or two devices read each other's copies as changes.
    ours.channels.sort_by(|a, b| a.id.cmp(&b.id));
    let unrevised = |jm: &super::list::JoinMaterial| {
        let mut jm = jm.clone();
        jm.rev = 0;
        jm.channels.sort_by(|a, b| a.id.cmp(&b.id));
        jm
    };
    ours.rev = if unrevised(&ours) == unrevised(theirs) {
        theirs.effective_rev()
    } else {
        theirs.effective_rev() + 1
    };
    ours
}

/// Rebuild an invite bundle from list join material, for a cross-device rehydrate
/// (the material IS the membership subset of a bundle). The owner root is still
/// verified over the network before the community is trusted (accept_bundle).
fn material_to_invite(jm: &super::list::JoinMaterial) -> CommunityInvite {
    // A keyless listing records that the channel EXISTS, not a grant — there is
    // nothing to seat, and it keys up when access is granted.
    let channels = jm
        .channels
        .iter()
        .filter_map(|c| {
            c.key.as_ref().map(|k| invite::ChannelGrant { id: c.id.clone(), key: k.clone(), epoch: c.epoch, name: c.name.clone() })
        })
        .collect();
    CommunityInvite {
        community_id: jm.community_id.clone(),
        owner: jm.owner.clone(),
        owner_salt: jm.owner_salt.clone(),
        community_root: jm.community_root.clone(),
        root_epoch: jm.root_epoch,
        control_pk: jm.control_pk.clone(),
        channels,
        relays: jm.relays.clone(),
        name: jm.name.clone(),
        icon: None,
        expires_at: None,
        creator_npub: None,
        label: None,
        extra: Default::default(),
    }
}

/// The account's OWN relays — where an account-level list belongs. Published to a
/// community's relays instead, the list stops being readable the moment that
/// community is left, which is exactly when its tombstone has to be found.
/// Empty without a client (tests), where the caller falls back to the held set.
async fn own_list_relays() -> Vec<String> {
    let Some(client) = crate::state::nostr_client() else { return Vec::new() };
    client
        .relays()
        .await
        .iter()
        .filter(|(_, r)| r.capabilities().load().can_write())
        .map(|(url, _)| url.to_string())
        .collect()
}

/// Read the list from everywhere a copy could be: our own relays, the stock CORD
/// set (where it lands when ours refuse the kind), and the held communities'
/// (where every list published before the move still lives). Missing one of these
/// reads a stale copy and republishes it over a newer tombstone.
async fn list_read_relays(extra: &[String]) -> Vec<String> {
    let mut set = own_list_relays().await;
    set.extend(invite::stock_relays());
    set.extend(held_v2_relays());
    set.extend(extra.iter().cloned());
    set.sort();
    set.dedup();
    set
}

/// What a fragment fetch found: the unioned list, and each index's `created_at`
/// so the next write to that fragment can exceed it.
pub struct FragSet {
    pub list: super::list::CommunityList,
    pub created_at: std::collections::BTreeMap<usize, u64>,
    /// `frags` as declared by the newest fragment seen.
    pub declared: usize,
    /// The winning parsed fragment per index — what the relays currently hold,
    /// so a rewrite can skip publishing byte-identical fragments.
    pub read_frags: std::collections::BTreeMap<usize, super::list_frag::FragList>,
    /// The winning signed event per index and the relays that returned it, so an unchanged
    /// fragment still reaches a relay that lacks it.
    pub on_relays: std::collections::BTreeMap<usize, (Event, Vec<String>)>,
}

impl FragSet {
    /// Coverage, not agreement: we hold every index below `declared`, whatever
    /// their individual ages. A short read is read-only, never a write.
    pub fn is_complete(&self) -> bool {
        (0..self.declared).all(|i| self.created_at.contains_key(&i))
    }
}

/// One read of the list: what it found, and which relays actually answered it.
struct FragRead {
    set: Option<FragSet>,
    /// Relays that answered (EOSE). A write goes only here: a relay we didn't hear from may
    /// hold a newer copy, and a newer `created_at` would replace it unseen.
    answered: Vec<String>,
    /// A fragment that wouldn't open: it may be the newest copy, so no write may build on
    /// this read.
    unreadable: bool,
}

/// Fetch the account's 33302 fragments and union them. Newest wins PER INDEX —
/// each fragment is its own addressable coordinate, so they age independently.
async fn fetch_fragments<T: Transport + ?Sized>(transport: &T, relays: &[String]) -> Result<Option<FragSet>, String> {
    read_fragments(transport, relays).await.map(|r| r.set)
}

/// Read the list from every relay, each asked on its own and waited for: a read that stops at
/// the first answer can be a relay holding nothing, or a stale copy, and a write built on it
/// replaces the real list everywhere. Every readable version is merged (the List is a CRDT:
/// a stale copy can't revive what a newer one removed), so one relay's copy never hides
/// another's tombstone.
async fn read_fragments<T: Transport + ?Sized>(transport: &T, relays: &[String]) -> Result<FragRead, String> {
    let signer = crate::signer::active_signer()?;
    let my_pk = me_pk()?;
    let query = Query {
        kinds: vec![super::kind::COMMUNITY_LIST_FRAG],
        authors: vec![my_pk.to_hex()],
        limit: Some(64),
        ..Default::default()
    };
    let per_relay = futures_util::future::join_all(
        relays.iter().map(|r| async { (r.clone(), transport.fetch(&query, std::slice::from_ref(r)).await) }),
    )
    .await;
    let mut answered = Vec::new();
    let mut holders: std::collections::HashMap<nostr_sdk::prelude::EventId, Vec<String>> = Default::default();
    let mut events = Vec::new();
    for (relay, res) in per_relay {
        if let Ok(evs) = res {
            for e in evs {
                let held_by = holders.entry(e.id).or_default();
                if held_by.is_empty() {
                    events.push(e);
                }
                held_by.push(relay.clone());
            }
            answered.push(relay);
        }
    }
    // Folded oldest first, so where versions disagree on an unmerged field the newest
    // has the last word whatever order the relays answered in.
    events.sort_by(|a, b| (a.created_at, a.id).cmp(&(b.created_at, b.id)));
    if answered.is_empty() {
        return Err(format!("no relay answered the list read (0/{})", relays.len()));
    }
    if events.is_empty() {
        return Ok(FragRead { set: None, answered, unreadable: false });
    }
    let mut newest: std::collections::BTreeMap<usize, (u64, [u8; 32], super::list_frag::FragList)> = Default::default();
    let mut newest_event: std::collections::BTreeMap<usize, Event> = Default::default();
    let mut list = super::list::CommunityList::default();
    // Unreadable versions by index: they matter only if one could be the newest.
    let mut unopened: Vec<(usize, u64)> = Vec::new();
    for e in events {
        let at = e.created_at.as_secs();
        let id = *e.id.as_bytes();
        // Not one of our fragment coordinates: nothing we read or write, so nothing to block.
        let Some(index) = e.tags.identifier().and_then(|d| d.parse::<usize>().ok()) else { continue };
        match super::list_frag::parse_fragment_event(&signer, my_pk, &e).await {
            Ok((index, frag)) => {
                list = list.merge(&super::list_frag::defragment(std::slice::from_ref(&frag)));
                // Mirror relay resolution (CORD-02 §8): newest created_at holds the
                // coordinate, an age tie falls to the LOWEST event id.
                let wins = match newest.get(&index) {
                    None => true,
                    Some((prev_at, prev_id, _)) => at > *prev_at || (at == *prev_at && id < *prev_id),
                };
                if wins {
                    newest.insert(index, (at, id, frag));
                    newest_event.insert(index, e);
                }
            }
            Err(_) => unopened.push((index, at)),
        }
    }
    // An older copy that won't open is history; one at or past the newest we read may be the
    // current list, and writing over it unseen is the loss this read exists to prevent.
    let blocking = unopened.iter().filter(|(i, at)| newest.get(i).is_none_or(|(n, _, _)| at >= n)).count();
    if blocking > 0 {
        crate::log_warn!("[CommunityList] {} current fragment(s) would not open — reading what did, refusing to write", blocking);
    }
    if newest.is_empty() {
        return Ok(FragRead { set: None, answered, unreadable: blocking > 0 });
    }
    // Fragment-level unknowns belong to the List, not the version fold: each index
    // speaks through its newest copy, and the lowest index wins a key (CORD-02 §8).
    list.extra = Default::default();
    for (_, _, frag) in newest.values() {
        for (k, v) in &frag.extra {
            list.extra.entry(k.clone()).or_insert_with(|| v.clone());
        }
    }
    // The newest fragment governs `frags`; an age tie resolves to the LARGER count
    // (CORD-02 §8) — too large reads an index that turns out empty, too small sends
    // live fragments out of range and dormant.
    let declared = newest
        .values()
        .max_by_key(|(at, _, f)| (*at, f.frags))
        .map(|(_, _, f)| f.frags)
        .unwrap_or(1)
        .max(1);
    let read_frags: std::collections::BTreeMap<usize, super::list_frag::FragList> =
        newest.iter().map(|(i, (_, _, f))| (*i, f.clone())).collect();
    let on_relays = newest_event
        .into_iter()
        .map(|(i, e)| {
            let held_by = holders.remove(&e.id).unwrap_or_default();
            (i, (e, held_by))
        })
        .collect();
    let set = FragSet {
        list,
        created_at: newest.iter().map(|(i, (at, _, _))| (*i, *at)).collect(),
        declared,
        read_frags,
        on_relays,
    };
    if !set.is_complete() {
        crate::log_warn!(
            "[CommunityList] INCOMPLETE: hold {} of {} fragment(s) — reading, refusing to write",
            set.created_at.len(),
            declared
        );
    }
    Ok(FragRead { set: Some(set), answered, unreadable: blocking > 0 })
}

/// Publish a list as fragments. Each fragment's `created_at` must exceed that
/// fragment's own previous value — relays resolve an addressable event on
/// `created_at` alone and break a tie on the lowest event id, so a same-second
/// rewrite can silently discard the newer content.
async fn publish_fragments<T: Transport + ?Sized>(
    transport: &T,
    list: &super::list::CommunityList,
    prev: &std::collections::BTreeMap<usize, u64>,
    read: &std::collections::BTreeMap<usize, super::list_frag::FragList>,
    on_relays: &std::collections::BTreeMap<usize, (Event, Vec<String>)>,
    targets: &ListTargets,
) -> Result<usize, String> {
    let signer = crate::signer::active_signer()?;
    let my_pk = me_pk()?;
    let frags = super::list_frag::fragment(list);
    let now = now_ms() / 1000;
    // A fragment serializing to the bytes we just read is already on the relay:
    // republishing it only churns created_at — and hands a same-second sibling
    // write a lowest-id coin-flip it didn't need to enter.
    let unchanged = |index: usize, frag: &super::list_frag::FragList| -> bool {
        let Some(old) = read.get(&index) else { return false };
        matches!(
            (serde_json::to_string(old), serde_json::to_string(frag)),
            (Ok(a), Ok(b)) if a == b
        )
    };
    // Persisted, not level-gated: a List write that silently never lands is the failure
    // mode this whole format exists to end, and it is only ever diagnosed after the fact.
    crate::log_net_info!(
        "[CommunityList] publishing {} fragment(s): {} live entries ({} retired), {} tombstones",
        frags.len(),
        frags.iter().map(|f| f.entries.len()).sum::<usize>(),
        list.entries.len() - frags.iter().map(|f| f.entries.len()).sum::<usize>(),
        frags.iter().map(|f| f.tombstones.len()).sum::<usize>(),
    );
    let mut skipped = 0usize;
    for (index, frag) in frags.iter().enumerate() {
        if unchanged(index, frag) {
            skipped += 1;
            spread_unchanged(transport, on_relays.get(&index), targets).await;
            continue;
        }
        let created_at = now.max(prev.get(&index).copied().unwrap_or(0) + 1);
        let event = super::list_frag::build_fragment_event(&signer, my_pk, frag, index, created_at).await?;
        publish_list_event(transport, &event, targets).await?;
    }
    // A shrunk set leaves the fragments above it in place; empty them so a later
    // growth into that index cannot re-read stale memberships.
    for index in frags.len()..prev.len() {
        let empty = super::list_frag::FragList {
            frags: frags.len(),
            entries: vec![],
            tombstones: vec![],
            extra: Default::default(),
        };
        if unchanged(index, &empty) {
            skipped += 1;
            spread_unchanged(transport, on_relays.get(&index), targets).await;
            continue;
        }
        let created_at = now.max(prev.get(&index).copied().unwrap_or(0) + 1);
        let event = super::list_frag::build_fragment_event(&signer, my_pk, &empty, index, created_at).await?;
        publish_list_event(transport, &event, targets).await?;
    }
    if skipped > 0 {
        crate::log_net_info!("[CommunityList] {} fragment(s) skipped — byte-identical to the relay copy", skipped);
    }
    Ok(frags.len())
}

/// Publish an account-level list, falling back to the stock CORD relays when our
/// own reject it — 33302 is a custom kind, and a relay with a kind whitelist drops
/// it silently. The list is the vault: it has to land somewhere every client reads.
/// Held across a list write's whole read, merge and publish. Two overlapping writes read the
/// same version and publish in the same second, and a relay keeps only one of them.
static LIST_WRITE: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());

/// The list write lock, waited for (a background retry) or only if free (a user action,
/// which hands off to the background rather than queue behind someone else's write).
async fn list_write_turn(wait: bool) -> Option<tokio::sync::MutexGuard<'static, ()>> {
    if wait { Some(LIST_WRITE.lock().await) } else { LIST_WRITE.try_lock().ok() }
}

const LIST_BUSY: &str = "another list write is in flight";

/// Our own leaves still on their way, as tombstones a write carries along: one write lands
/// every leave queued behind it.
fn pending_tombstones() -> super::list::CommunityList {
    let tombstones = load_pending()
        .tombstones
        .into_iter()
        .map(|t| super::list::Tombstone { community_id: t.community_id, removed_at: t.removed_at, extra: Default::default() })
        .collect();
    super::list::CommunityList { tombstones, ..Default::default() }
}

/// Drop every pending leave and join the relays now show.
fn settle_pending(landed: &super::list::CommunityList) {
    edit_pending(|p| {
        p.tombstones.retain(|t| !landed.tombstones.iter().any(|l| l.community_id == t.community_id && l.removed_at >= t.removed_at));
        p.joins.retain(|j| !landed.entries.iter().any(|e| e.community_id == j.community_id && e.added_at >= j.joined_at));
    });
}

/// Where a list write goes: our own relays and the stock set, each only if it answered the
/// read the write was built on (a relay we didn't hear from may hold a newer copy, and a newer
/// `created_at` would replace it unseen). Both, always: the stock set is in every device's read
/// set where our own relays may not be, and a relay can accept a kind it then discards.
struct ListTargets {
    own: Vec<String>,
    fallback: Vec<String>,
}

impl ListTargets {
    fn new(own: Vec<String>, answered: &[String]) -> Self {
        let pick = |set: Vec<String>| -> Vec<String> { set.into_iter().filter(|r| answered.contains(r)).collect() };
        ListTargets { own: pick(own), fallback: pick(invite::stock_relays()) }
    }

    fn is_empty(&self) -> bool {
        self.own.is_empty() && self.fallback.is_empty()
    }
}

async fn publish_list_event<T: Transport + ?Sized>(transport: &T, event: &Event, targets: &ListTargets) -> Result<(), String> {
    let mut all = targets.own.clone();
    all.extend(targets.fallback.iter().filter(|r| !targets.own.contains(r)).cloned());
    if all.is_empty() {
        return Err("no relay that answered the read took the list".to_string());
    }
    transport.publish(event, &all).await
}

/// An unchanged fragment needs no new version, but a target relay that lacks the current one
/// (it held nothing, or a stale copy) still gets it, as signed.
async fn spread_unchanged<T: Transport + ?Sized>(transport: &T, current: Option<&(Event, Vec<String>)>, targets: &ListTargets) {
    let Some((event, held_by)) = current else { return };
    let lacking: Vec<String> = targets.own.iter().chain(&targets.fallback).filter(|r| !held_by.contains(r)).cloned().collect();
    if !lacking.is_empty() {
        if let Err(e) = transport.publish(event, &lacking).await {
            crate::log_warn!("[CommunityList] could not copy the current fragment to {} relay(s): {e}", lacking.len());
        }
    }
}

/// The union of every held v2 community's relays — a fallback write target, and
/// where every list published before the move to our own relays still lives.
fn held_v2_relays() -> Vec<String> {
    let mut set: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
    if let Ok(ids) = crate::db::community::list_community_ids() {
        for id in ids {
            if matches!(crate::db::community::community_held(&id), Ok(true)) {
                if let Ok(Some(c)) = crate::db::community::load_community_v2(&id) {
                    set.extend(c.relays);
                }
            }
        }
    }
    set.into_iter().collect()
}

/// Rebuild this account's Community List from its held v2 communities, MERGE with the remote
/// copy (preserving tombstones, other-device entries, unknown fields), and publish.
/// `just_joined` is the community THIS call is recording a create/join for — the
/// ONLY community whose entry is (re)stamped `now`, so it beats any prior tombstone
/// (a deliberate re-join resurrects). Every OTHER held community that the remote
/// has tombstoned is left tombstoned (a sibling device's leave is NOT undone just
/// because we joined something else — the W1 resurrection hole). Idempotent;
/// best-effort — a list-publish failure never fails the membership change itself.
/// Returns `Ok(true)` when the list was PUBLISHED, `Ok(false)` when the attempt was
/// skipped without failing the caller (a failed remote fetch — see below). Callers that
/// need the membership to actually land use [`republish_community_list_durable`].
pub async fn republish_community_list<T: Transport + ?Sized>(transport: &T, just_joined: Option<&crate::community::CommunityId>) -> Result<bool, String> {
    republish_community_list_at(transport, just_joined.map(|id| (id, now_ms())), false).await
}

/// [`republish_community_list`] with the join's own time: a retry stamps when the join
/// happened, not when the retry ran.
async fn republish_community_list_at<T: Transport + ?Sized>(
    transport: &T,
    joined: Option<(&crate::community::CommunityId, u64)>,
    wait: bool,
) -> Result<bool, String> {
    let just_joined = joined.map(|(id, _)| id);
    crate::db::scoped(async move {
        // A user action never queues behind another write: it reports a skip and the caller
        // hands it to the durable retry, which waits its turn.
        let Some(_write) = list_write_turn(wait).await else { return Ok(false) };
        let held = held_v2_relays();
        if held.is_empty() {
            return Ok(false); // nothing held → nothing to sync
        }
        let relays = list_read_relays(&[]).await;
        let own = own_list_relays().await;
        // Written to our own relays, read from both: the copy has to outlive any
        // one membership. Falls back to the held set when we have no relays of
        // our own to write to.
        let write_relays = if own.is_empty() { held.clone() } else { own };
        // A FAILED remote fetch must not drive this replaceable-event write: publishing
        // a list built without the remote seeds would drop older-epoch backfill anchors
        // and re-stamp add-times (the W2 seed-regression + a resurrection window).
        let read = match read_fragments(transport, &relays).await {
            Ok(read) => read,
            Err(e) => {
                // SILENT-SKIP HAZARD: bailing is correct (publishing a list built without the
                // remote seeds drops backfill anchors), but the membership this call was meant
                // to record is now simply unrecorded. A join that lands here leaves a community
                // held locally with no list entry — and if it also carries an older tombstone,
                // nothing ever out-ranks it again. Say so loudly; `Ok(())` keeps it non-fatal.
                crate::log_warn!(
                    "[CommunityList] republish SKIPPED (remote fetch failed: {}){}",
                    e,
                    just_joined
                        .map(|c| format!(" — the join of {} is NOT recorded across devices", &crate::simd::hex::bytes_to_hex_32(&c.0)[..8]))
                        .unwrap_or_default()
                );
                return Ok(false);
            }
        };
        if read.unreadable {
            crate::log_warn!("[CommunityList] republish SKIPPED — a fragment would not open, and it may be the newest copy");
            return Ok(false);
        }
        let targets = ListTargets::new(write_relays, &read.answered);
        if targets.is_empty() {
            crate::log_warn!("[CommunityList] republish SKIPPED — no relay we write to answered the read");
            return Ok(false);
        }
        let (remote, prev_created, read_frags, on_relays) = match read.set {
            Some(set) if !set.is_complete() => {
                crate::log_net_fail!(
                    "[CommunityList] republish SKIPPED — hold {} of {} fragments; rewriting a set we haven't fully read would drop the memberships in the ones we're missing",
                    set.created_at.len(),
                    set.declared
                );
                return Ok(false);
            }
            Some(set) => (set.list, set.created_at, set.read_frags, set.on_relays),
            // No fragment on any relay that answered, and we write only to those: nothing
            // there to lose, and local state is the source.
            None => Default::default(),
        };
        let just_joined_hex = just_joined.map(|c| crate::simd::hex::bytes_to_hex_32(&c.0));
        let now = now_ms();
        let pending = pending_tombstones();
        let mut local = super::list::CommunityList::default();
        for id in crate::db::community::list_community_ids()? {
            if !matches!(crate::db::community::community_held(&id), Ok(true)) {
                continue;
            }
            let Some(c) = crate::db::community::load_community_v2(&id)? else { continue };
            let cid_hex = crate::simd::hex::bytes_to_hex_32(&c.id().0);
            let is_join = just_joined_hex.as_deref() == Some(cid_hex.as_str());
            // A held community the remote has tombstoned (a sibling device left it) that
            // we are NOT currently (re)joining stays LEFT — don't re-add it, or joining a
            // different community would silently undo the leave everywhere.
            //
            // UNLESS our hold POST-DATES the removal. A rejoin whose membership never
            // reached the list (this publish is best-effort — a failed remote fetch
            // silently skips it) leaves a tombstone with no entry, and nothing can ever
            // out-rank it again: every boot the list sync reads "removed", tears the
            // community down, the rejoin re-adds it, and it loops forever. Our own hold
            // is first-hand evidence of membership, so let it settle the tie by the same
            // add-vs-remove rule the list already uses everywhere else.
            let tombstoned_at = remote
                .tombstones
                .iter()
                .find(|t| t.community_id == cid_hex)
                .map(|t| t.removed_at)
                .unwrap_or(0);
            let held_since = hold_bound_ms(&c);
            if !is_join && !remote.is_live(&cid_hex) && tombstoned_at > 0 && held_since <= tombstoned_at {
                crate::log_warn!(
                    "[CommunityList] holding {} but NOT recording it: a tombstone at {} post-dates our hold ({}) — treated as a leave from another device",
                    &cid_hex[..8], tombstoned_at, held_since
                );
                continue;
            }
            // Keep an already-live entry's add time (no churn); the joined community (or a
            // genuinely-new one) stamps `now` so a re-join beats a stale tombstone. A hold
            // that outlived a tombstone re-asserts itself at its own join time, which is
            // already newer than the removal.
            let added_at = if remote.is_live(&cid_hex) && !is_join {
                remote.entries.iter().find(|e| e.community_id == cid_hex).map(|e| e.added_at).unwrap_or(now)
            } else if is_join {
                // A join outranks every removal already known: one stamped later than the join
                // was noticed late or on a skewed clock, never made after it.
                let known = pending.tombstones.iter().filter(|t| t.community_id == cid_hex).map(|t| t.removed_at).fold(tombstoned_at, u64::max);
                joined.map_or(now, |(_, at)| at).max(known.saturating_add(1))
            } else {
                // Recorded at its own hold time: `now` would out-date a removal this read missed.
                held_since
            };
            let jm = join_material(&c);
            let theirs = remote.entries.iter().find(|e| e.community_id == cid_hex);
            let current = rebuild_snapshot(jm.clone(), theirs.map(|e| &e.current));
            let seed = rebuild_snapshot(jm, theirs.map(|e| &e.seed));
            local.entries.push(super::list::CommunityListEntry { community_id: cid_hex, seed, current, added_at, extra: Default::default() });
        }
        let merged = remote.merge(&local).merge(&pending);
        // No whole-list cap: fragmentation is what keeps each event publishable,
        // and the count limit is gone (CORD-02 §8).
        match publish_fragments(transport, &merged, &prev_created, &read_frags, &on_relays, &targets).await {
            Ok(_) => {}
            Err(e) => {
                crate::log_net_fail!("[CommunityList] publish FAILED ({}) — memberships stay local-only until the next edit", e);
                return Err(e);
            }
        }
        // A join counts as recorded only once the relays show it: a write from another device
        // in the same second can win the coordinate, and an accepted publish says nothing of that.
        let shown = fetch_fragments(transport, &relays).await.ok().flatten().map(|set| set.list).unwrap_or_default();
        settle_pending(&shown);
        if let Some(hex) = just_joined_hex.as_deref().filter(|h| local.entries.iter().any(|e| e.community_id == *h)) {
            let at = joined.map_or(now, |(_, at)| at);
            let landed = shown.entries.iter().any(|e| e.community_id == hex && e.added_at >= at);
            if !landed {
                crate::log_warn!("[CommunityList] the join of {} was published but isn't on the relays — retrying", &hex[..8]);
                return Ok(false);
            }
        }
        Ok(true)
    })
    .await
}

/// Retry budget for [`republish_community_list_durable`]. An unrecorded membership is
/// invisible to the user and self-heals only on their NEXT join, so ride out a relay
/// blip rather than a single shot. Bounded: a permanently dead relay set gives up
/// instead of spinning.
const LIST_REPUBLISH_BACKOFF_SECS: [u64; 6] = [2, 5, 15, 45, 120, 300];

/// Record a membership across devices DURABLY: retry in the background until the list
/// actually lands.
///
/// [`republish_community_list`] must never fail a join, and it deliberately publishes
/// NOTHING when the remote fetch fails (a list built without the remote seeds would drop
/// other devices' entries). One shot at that means a relay blip during a join leaves the
/// membership unrecorded until the user happens to join something else — and if a stale
/// tombstone out-ranks it, the community is stranded until a manual leave+rejoin.
///
/// Non-blocking. Skipped entirely without a live client (headless/unit tests drive the
/// generic fn directly). Bound to its account, so a swap mid-backoff leaves it
/// publishing A's list from A's client rather than from B's.
pub fn republish_community_list_durable(just_joined: Option<crate::community::CommunityId>) {
    match just_joined {
        Some(id) => record_join_durable(id, now_ms()),
        None => retry_republish(None),
    }
}

/// Record a join made at `joined_at`, kept until it lands.
fn record_join_durable(id: crate::community::CommunityId, joined_at: u64) {
    let hex = crate::simd::hex::bytes_to_hex_32(&id.0);
    edit_pending(|p| {
        if !p.joins.iter().any(|j| j.community_id == hex) {
            p.joins.push(PendingJoin { community_id: hex.clone(), joined_at });
        }
    });
    retry_republish(Some((id, joined_at)));
}

fn retry_republish(join: Option<(crate::community::CommunityId, u64)>) {
    if crate::state::nostr_client().is_none() {
        return;
    }
    crate::db::spawn_bound(async move {
        for (attempt, wait) in LIST_REPUBLISH_BACKOFF_SECS.iter().enumerate() {
            let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
            match republish_community_list_at(&transport, join.as_ref().map(|(id, at)| (id, *at)), true).await {
                Ok(true) => {
                    if let Some((id, _)) = &join {
                        let hex = crate::simd::hex::bytes_to_hex_32(&id.0);
                        edit_pending(|p| p.joins.retain(|j| j.community_id != hex));
                    }
                    if attempt > 0 {
                        crate::log_info!("[CommunityList] membership recorded on retry #{}", attempt);
                    }
                    return;
                }
                Ok(false) => {} // skipped — already logged; retry
                Err(e) => crate::log_warn!("[CommunityList] republish attempt #{} failed: {}", attempt, e),
            }
            crate::rt::time::sleep(std::time::Duration::from_secs(*wait)).await;
        }
        crate::log_warn!(
            "[CommunityList] membership not recorded after {} attempts — kept, retried on the next boot",
            LIST_REPUBLISH_BACKOFF_SECS.len()
        );
    });
}

/// Record a permanent leave tombstone for `community_id` in the List. Written to
/// our OWN relays: the departing community's are about to stop being read at all,
/// so a tombstone left only there is one no later sync can ever fetch — the
/// community then rejoins itself from a stale copy on the next boot.
async fn tombstone_community_list<T: Transport + ?Sized>(
    transport: &T,
    community_id: &crate::community::CommunityId,
    relays: &[String],
    removed_at: u64,
    wait: bool,
) -> Result<(), String> {
    let Some(_write) = list_write_turn(wait).await else { return Err(LIST_BUSY.to_string()) };
    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community_id.0);
    let read_relays = list_read_relays(relays).await;
    let own = own_list_relays().await;
    let write_relays = if own.is_empty() { relays.to_vec() } else { own };
    // A failed fetch here would drop other communities' entries (only the
    // tombstone would survive); preserve them by bailing — the leave re-records
    // on the next attempt, and the local teardown already happened.
    let read = read_fragments(transport, &read_relays).await?;
    if read.unreadable {
        return Err("a fragment would not open, and it may be the newest copy — refusing to write".to_string());
    }
    let targets = ListTargets::new(write_relays, &read.answered);
    if targets.is_empty() {
        return Err("no relay we write to answered the read".to_string());
    }
    let (mut doc, prev_created, read_frags, on_relays) = match read.set {
        Some(set) if !set.is_complete() => {
            return Err(format!("hold {} of {} fragments — refusing to rewrite a set we haven't fully read", set.created_at.len(), set.declared));
        }
        Some(set) => (set.list, set.created_at, set.read_frags, set.on_relays),
        None => Default::default(),
    };
    // A late retry must never replace a newer removal with its own older one.
    let removed_at = doc.tombstones.iter().filter(|t| t.community_id == cid_hex).map(|t| t.removed_at).fold(removed_at, u64::max);
    doc.tombstones.retain(|t| t.community_id != cid_hex);
    doc.tombstones.push(super::list::Tombstone { community_id: cid_hex.clone(), removed_at, extra: Default::default() });
    let doc = doc.merge(&pending_tombstones());
    // No size gate on the way out: a tombstone strictly shrinks the live set, and
    // a guard that blocks the only operation able to restore compliance is a
    // deadlock, not a guard (CORD-02 §8).
    publish_fragments(transport, &doc, &prev_created, &read_frags, &on_relays, &targets).await?;
    // Landed only once the relays show it: a write from another device in the same second can
    // win the coordinate, and an accepted publish says nothing of that.
    let shown = fetch_fragments(transport, &read_relays).await?.map(|set| set.list).unwrap_or_default();
    settle_pending(&shown);
    if shown.tombstones.iter().any(|t| t.community_id == cid_hex && t.removed_at >= removed_at) {
        Ok(())
    } else {
        Err("the tombstone was published but isn't on the relays".to_string())
    }
}

/// Retry a leave tombstone until it lands, on the same budget a join gets. A leave
/// that fails to record is the worse of the two: the local hold is already gone, so
/// this device shows the community left while every other one still holds it, and
/// nothing re-records it until some unrelated edit happens to carry it.
///
/// `removed_at` is the caller's, not `now` — re-stamping it here would let a retry
/// that fires after a genuine rejoin bury that rejoin.
pub fn tombstone_community_list_durable(community_id: crate::community::CommunityId, relays: Vec<String>, removed_at: u64) {
    retry_pending_tombstone(add_pending_tombstone(&community_id, removed_at), relays);
}

fn add_pending_tombstone(community_id: &crate::community::CommunityId, removed_at: u64) -> PendingTombstone {
    let pending = PendingTombstone { community_id: crate::simd::hex::bytes_to_hex_32(&community_id.0), removed_at };
    mirror_tombstones([(pending.community_id.as_str(), removed_at)]);
    edit_pending(|p| {
        p.tombstones.retain(|t| t.community_id != pending.community_id || t.removed_at > pending.removed_at);
        if !p.tombstones.iter().any(|t| t.community_id == pending.community_id) {
            p.tombstones.push(pending.clone());
        }
    });
    pending
}

/// Record a leave in the List: kept as pending first, written now when no other list write
/// is running, else left to the background queue (which carries every pending leave).
async fn record_leave<T: Transport + ?Sized>(transport: &T, community_id: &crate::community::CommunityId, relays: &[String], removed_at: u64) {
    let pending = add_pending_tombstone(community_id, removed_at);
    match tombstone_community_list(transport, community_id, relays, removed_at, false).await {
        Ok(()) => {}
        Err(e) => {
            if e != LIST_BUSY {
                crate::log_net_fail!("[CommunityList] leave tombstone failed ({}) — retrying in the background", e);
            }
            retry_pending_tombstone(pending, relays.to_vec());
        }
    }
}

fn retry_pending_tombstone(pending: PendingTombstone, relays: Vec<String>) {
    if crate::state::nostr_client().is_none() {
        return;
    }
    let Some(id) = crate::simd::hex::hex_to_bytes_32_checked(&pending.community_id).map(crate::community::CommunityId) else { return };
    crate::db::spawn_bound(async move {
        for (attempt, wait) in LIST_REPUBLISH_BACKOFF_SECS.iter().enumerate() {
            crate::rt::time::sleep(std::time::Duration::from_secs(*wait)).await;
            // Another write may have carried it already.
            if !load_pending().tombstones.iter().any(|t| t.community_id == pending.community_id) {
                return;
            }
            let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
            match tombstone_community_list(&transport, &id, &relays, pending.removed_at, true).await {
                Ok(()) => {
                    crate::log_net_info!(
                        "[CommunityList] leave tombstone for {} landed on retry #{}",
                        &pending.community_id[..8],
                        attempt + 1
                    );
                    return;
                }
                Err(e) => crate::log_warn!("[CommunityList] leave tombstone retry #{} failed: {}", attempt + 1, e),
            }
        }
        crate::log_net_fail!(
            "[CommunityList] leave tombstone for {} not landed after {} attempts — kept, retried on the next boot",
            &pending.community_id[..8],
            LIST_REPUBLISH_BACKOFF_SECS.len()
        );
    });
}

/// List writes that haven't landed yet, kept in the account's DB: a leave or a join whose
/// retries die with the app (closed, killed, offline) is otherwise lost for good, and the
/// other devices never hear of it.
#[derive(Default, serde::Serialize, serde::Deserialize)]
struct PendingListWrites {
    #[serde(default)]
    tombstones: Vec<PendingTombstone>,
    #[serde(default)]
    joins: Vec<PendingJoin>,
}

#[derive(Clone, serde::Serialize, serde::Deserialize)]
struct PendingTombstone {
    community_id: String,
    removed_at: u64,
}

#[derive(Clone, serde::Serialize, serde::Deserialize)]
struct PendingJoin {
    community_id: String,
    /// When the join happened: a retry days later must not out-date a leave made since.
    joined_at: u64,
}

const LIST_PENDING_KEY: &str = "community_list_pending_writes";

fn load_pending() -> PendingListWrites {
    let raw = crate::db::settings::get_sql_setting(LIST_PENDING_KEY.to_string()).ok().flatten();
    raw.map_or_else(PendingListWrites::default, |s| {
        serde_json::from_str(&s).unwrap_or_else(|e| {
            // Kept aside rather than overwritten by the next edit: it may hold a leave.
            crate::log_warn!("[CommunityList] pending list writes unreadable ({e}) — set aside");
            let _ = crate::db::settings::set_sql_setting(format!("{LIST_PENDING_KEY}_unread"), s);
            PendingListWrites::default()
        })
    })
}

fn edit_pending(f: impl FnOnce(&mut PendingListWrites)) {
    // Process-wide: a task from an earlier session of the same account writes the same row.
    static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
    let _held = LOCK.lock().unwrap_or_else(|e| e.into_inner());
    let mut pending = load_pending();
    f(&mut pending);
    if let Ok(json) = serde_json::to_string(&pending) {
        if let Err(e) = crate::db::settings::set_sql_setting(LIST_PENDING_KEY.to_string(), json) {
            crate::log_warn!("[CommunityList] could not persist pending list writes: {e}");
        }
    }
}

/// Every removal this device has read from the List or written to it: `community_id` →
/// newest `removed_at` (ms). Merge-only, so an invite arriving between syncs still meets
/// the decision that answered it.
const LIST_TOMBSTONES_KEY: &str = "community_list_tombstones";

fn load_tombstone_mirror() -> Result<std::collections::HashMap<String, u64>, String> {
    let raw = crate::db::settings::get_sql_setting_strict(LIST_TOMBSTONES_KEY)?;
    Ok(raw.map_or_else(Default::default, |s| {
        serde_json::from_str(&s).unwrap_or_else(|e| {
            crate::log_warn!("[CommunityList] tombstone mirror unreadable ({e}) — set aside");
            let _ = crate::db::settings::set_sql_setting(format!("{LIST_TOMBSTONES_KEY}_unread"), s);
            Default::default()
        })
    }))
}

fn mirror_tombstones<'a>(tombstones: impl IntoIterator<Item = (&'a str, u64)>) {
    static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
    let _held = LOCK.lock().unwrap_or_else(|e| e.into_inner());
    // A failed read must not become an empty map that replaces the row.
    let mut mirror = match load_tombstone_mirror() {
        Ok(m) => m,
        Err(e) => {
            crate::log_warn!("[CommunityList] tombstone mirror not read ({e}) — removals not mirrored");
            return;
        }
    };
    let mut changed = false;
    for (id, at) in tombstones {
        let id = id.to_ascii_lowercase();
        if mirror.get(&id).is_none_or(|&held| held < at) {
            mirror.insert(id, at);
            changed = true;
        }
    }
    if !changed {
        return;
    }
    if let Ok(json) = serde_json::to_string(&mirror) {
        if let Err(e) = crate::db::settings::set_sql_setting(LIST_TOMBSTONES_KEY.to_string(), json) {
            crate::log_warn!("[CommunityList] could not persist the tombstone mirror: {e}");
        }
    }
}

/// Record a removal this device made without a List write (a kick, a rekey exclusion), so a
/// re-delivered invite no newer than it stays answered.
pub fn note_local_removal(community_id: &str, removed_at: u64) {
    mirror_tombstones([(community_id, removed_at)]);
}

/// Every removal this device has made or read: `community_id` → newest `removed_at` (ms).
fn known_removals() -> std::collections::HashMap<String, u64> {
    let mut known = load_tombstone_mirror().unwrap_or_default();
    for t in load_pending().tombstones {
        let at = known.entry(t.community_id.to_ascii_lowercase()).or_insert(0);
        *at = (*at).max(t.removed_at);
    }
    known
}

/// Whether a leave or decline at least as new as an invite (its inner rumor time,
/// in seconds) has already answered it, here or on a sibling device.
pub fn tombstone_suppresses(community_id: &str, invite_created_at_secs: u64) -> bool {
    let invite_ms = invite_created_at_secs.saturating_mul(1000);
    known_removals().get(&community_id.to_ascii_lowercase()).is_some_and(|&at| at >= invite_ms)
}

/// Resume every list write a previous run left unfinished. Once per session.
fn resume_pending_list_writes() {
    struct Resumed;
    if crate::state::nostr_client().is_none() {
        return;
    }
    let flag = crate::db::current_session().scoped::<Resumed, std::sync::atomic::AtomicBool>();
    if flag.swap(true, std::sync::atomic::Ordering::SeqCst) {
        return;
    }
    let pending = load_pending();
    if !pending.tombstones.is_empty() || !pending.joins.is_empty() {
        crate::log_net_info!(
            "[CommunityList] resuming {} unlanded leave(s) and {} unrecorded join(s)",
            pending.tombstones.len(),
            pending.joins.len()
        );
    }
    for t in pending.tombstones {
        retry_pending_tombstone(t, Vec::new());
    }
    for j in pending.joins {
        if let Some(cid) = crate::simd::hex::hex_to_bytes_32_checked(&j.community_id) {
            record_join_durable(crate::community::CommunityId(cid), j.joined_at);
        }
    }
}

/// Sync memberships from the Community List across devices: fetch this account's list from
/// `bootstrap_relays` (its held communities' relays plus any caller-supplied set for
/// a fresh device), and JOIN every live entry not already held — reconstructing the
/// community from its join material and re-verifying the owner root. Returns the
/// newly-rehydrated communities (so the caller can subscribe + notify).
/// What one Community-List sync changed locally.
pub struct ListSyncOutcome {
    /// Communities newly adopted from the list (already persisted + chat-registered).
    pub joined: Vec<CommunityV2>,
    /// Communities a sibling device LEFT, as `(community_id_hex, channel_id_hexes)`.
    ///
    /// The rows are already gone here, so the ids are captured BEFORE deletion: the caller
    /// still has to finish the local teardown (chat rows, STATE, the live subscription),
    /// and it can't look them up afterwards. Deleting the community while leaving its chat
    /// row behind is what produces a ghost "0 Members" room pointing at nothing.
    pub removed: Vec<(String, Vec<String>)>,
}

/// Marks that this account has written the fragmented list at least once.
const LIST_SEEDED_KEY: &str = "community_list_frag_seeded";

/// The join refusal for a VERIFIED dissolution — an owner-signed, identity-bound
/// tombstone (§9: no un-dissolve). A sentinel because the accept boundary matches
/// on it: this is the one join failure that is a verdict rather than a maybe, so
/// the parked invite is retired instead of kept for a retry that can never succeed.
pub const ERR_DISSOLVED: &str = "this community has been dissolved";

/// Retire a parked invite whose community is provably dead: drop the local row and
/// tombstone the §8 List so every sibling device purges its copy on the next sync.
/// ONLY for the dissolved verdict — ambiguous could-not-verify failures stay parked.
pub async fn retire_dead_invite<T: Transport + ?Sized>(transport: &T, community_id_hex: &str, relays: &[String]) {
    let _ = crate::db::community::delete_pending_invite(community_id_hex);
    if let Some(cid) = crate::simd::hex::hex_to_bytes_32_checked(community_id_hex) {
        let id = crate::community::CommunityId(cid);
        let at = now_ms();
        record_leave(transport, &id, relays, at).await;
    }
    crate::emit_event("community_invites_purged", &serde_json::json!({}));
}

/// Every relay answered EOSE with zero fragments — the only reading of "empty"
/// strong enough to seed over. The aggregate fetch that precedes this cannot
/// distinguish "no fragments" from "the relay holding them never answered";
/// asked one at a time, an error is a FAILED read and a failed read never seeds.
async fn confirmed_no_fragments<T: Transport + ?Sized>(transport: &T, relays: &[String]) -> bool {
    let Ok(my_pk) = me_pk() else { return false };
    if relays.is_empty() {
        return false;
    }
    let query = Query {
        kinds: vec![super::kind::COMMUNITY_LIST_FRAG],
        authors: vec![my_pk.to_hex()],
        limit: Some(1),
        ..Default::default()
    };
    for relay in relays {
        match transport.fetch(&query, std::slice::from_ref(relay)).await {
            Ok(events) if events.is_empty() => {}
            // Found one (the aggregate read raced a sibling's write) or the relay
            // didn't answer — either way this account is not confirmed empty.
            _ => return false,
        }
    }
    true
}

/// First write of the §8 List for an account that has none: an account upgrading
/// from the retired single-event list arrives here with memberships that exist
/// only in local state, and nothing else in the stack publishes without a
/// membership change to record. Latched once it lands, so a boot-load read that
/// comes back empty can never republish local state over a sibling's tombstones.
async fn seed_community_list<T: Transport + ?Sized>(transport: &T) {
    if crate::db::settings::get_sql_setting(LIST_SEEDED_KEY.to_string()).ok().flatten().is_some() {
        return;
    }
    if held_v2_relays().is_empty() {
        return;
    }
    // Seeding over a read that merely FAILED publishes fragment 0 over a sibling
    // device's tombstones at a fresh created_at — confirm the emptiness per relay.
    let own = own_list_relays().await;
    let confirm = if own.is_empty() { held_v2_relays() } else { own };
    if !confirmed_no_fragments(transport, &confirm).await {
        crate::log_warn!("[CommunityList] seed DEFERRED — the empty read is unconfirmed; retrying on a later boot");
        return;
    }
    crate::log_net_info!("[CommunityList] no fragments held anywhere (confirmed per relay) — seeding from local state");
    match republish_community_list(transport, None).await {
        Ok(true) => {
            let _ = crate::db::settings::set_sql_setting(LIST_SEEDED_KEY.to_string(), "1".to_string());
        }
        Ok(false) => {}
        Err(e) => crate::log_net_fail!("[CommunityList] seed failed: {e}"),
    }
}

pub async fn sync_community_list<T: Transport + ?Sized>(transport: &T, bootstrap_relays: &[String]) -> Result<ListSyncOutcome, String> {
    crate::db::scoped(async move {
        resume_pending_list_writes();
        let relays = list_read_relays(bootstrap_relays).await;
        if relays.is_empty() {
            return Ok(ListSyncOutcome { joined: vec![], removed: vec![] });
        }
        // A cross-device sync that finds nothing is indistinguishable from one that
        // never ran, so every exit says why — this path is only ever debugged after
        // the fact, from a user's log.
        let list = match fetch_fragments(transport, &relays).await {
            Ok(Some(set)) => {
                crate::log_net_info!(
                    "[CommunityList] fetched: {} of {} fragment(s), {} entries, {} tombstones, across {} relays",
                    set.created_at.len(),
                    set.declared,
                    set.list.entries.len(),
                    set.list.tombstones.len(),
                    relays.len()
                );
                set.list
            }
            Ok(None) => {
                // Transient by nature: boot runs many concurrent passes and a relay that
                // times out under that load returns nothing. Only persistent absence
                // matters, and that shows up as "adopted nothing" anyway.
                crate::log_debug!("[CommunityList] no fragments across {} relays", relays.len());
                seed_community_list(transport).await;
                return Ok(ListSyncOutcome { joined: vec![], removed: vec![] });
            }
            Err(e) => {
                crate::log_net_fail!("[CommunityList] fetch failed across {} relays: {e}", relays.len());
                return Ok(ListSyncOutcome { joined: vec![], removed: vec![] });
            }
        };
        // Every removal this device has made or read counts, whatever this copy says: one still
        // on its way to the relays, or one a relay serving an older copy never got, would
        // otherwise bring back a community already left.
        let known: Vec<super::list::Tombstone> = known_removals()
            .into_iter()
            .map(|(community_id, removed_at)| super::list::Tombstone { community_id, removed_at, extra: Default::default() })
            .collect();
        let list = list.merge(&super::list::CommunityList { tombstones: known, ..Default::default() });
        mirror_tombstones(list.tombstones.iter().map(|t| (t.community_id.as_str(), t.removed_at)));
        // Receive-side teardown (the counterpart to the republish tombstone guard):
        // a community this device still holds but the synced list shows TOMBSTONED (a
        // sibling device left it) and NOT live gets torn down here, so a leave on one
        // device propagates to the others. A re-join would have re-added it live
        // (beating the tombstone), so is_live short-circuits the honest case.
        let mut removed: Vec<(String, Vec<String>)> = Vec::new();
        for t in &list.tombstones {
            if list.is_live(&t.community_id) {
                continue;
            }
            let Some(cid) = crate::simd::hex::hex_to_bytes_32_checked(&t.community_id) else { continue };
            let id = crate::community::CommunityId(cid);
            let Some(held) = crate::db::community::load_community_v2(&id).ok().flatten() else {
                continue; // not held — nothing to tear down
            };
            // `is_live` above assumes a rejoin re-added an entry, but recording that entry is
            // best-effort: a relay blip at join time leaves the tombstone unopposed forever, and
            // this would then delete the community on every sync. So let the LOCAL hold break the
            // tie too — a hold created after the removal IS the rejoin, whether or not its entry
            // ever reached the list.
            if hold_bound_ms(&held) > t.removed_at {
                crate::log_warn!(
                    "[CommunityList] {} is tombstoned at {} but our hold ({}) post-dates it — treating as a rejoin, not tearing down",
                    &t.community_id[..8], t.removed_at, held.created_at_ms
                );
                continue;
            }
            let channel_ids: Vec<String> = held.channels.iter().map(|c| crate::simd::hex::bytes_to_hex_32(&c.id.0)).collect();
            let _ = crate::db::community::delete_community(&t.community_id);
            removed.push((t.community_id.clone(), channel_ids));
        }
        // A tombstone also retires any PARKED invite it post-dates — a decline or a
        // dissolution-retire made on another device. Supersession, not a bare id
        // match: only a removal NEWER than the invite's arrival is a verdict on it;
        // an older tombstone is a past leave the re-invite already superseded
        // (received_at is seconds, removed_at is ms).
        let mut invites_purged = 0usize;
        for t in &list.tombstones {
            if list.is_live(&t.community_id) {
                continue;
            }
            let Ok(Some(received_at)) = crate::db::community::pending_invite_received_at(&t.community_id) else { continue };
            if (received_at.max(0) as u64).saturating_mul(1000) <= t.removed_at
                && crate::db::community::delete_pending_invite(&t.community_id).is_ok()
            {
                invites_purged += 1;
            }
        }
        if invites_purged > 0 {
            crate::emit_event("community_invites_purged", &serde_json::json!({}));
        }
        let mut joined = Vec::new();
        for entry in list.live_entries() {
            let Some(cid) = crate::simd::hex::hex_to_bytes_32_checked(&entry.community_id) else { continue };
            // Held under ANY protocol, not just v2: a protocol-scoped check would re-adopt
            // an id held under another protocol, fail verification (no v2 community at that
            // coordinate), and retry on EVERY sync pass, a warning flood plus a relay walk.
            if crate::db::community::community_exists(&crate::community::CommunityId(cid)).unwrap_or(false) {
                continue; // already held
            }
            // The material IS a bundle; accept_bundle re-verifies the owner root, saves,
            // and seeds floors. NO Guestbook Join: this device is receiving keys the
            // account already holds elsewhere — the membership was announced when it
            // actually joined, and a key sync is not a membership event.
            let bundle = material_to_invite(&entry.current);
            match accept_bundle(transport, &bundle, None, Some(entry.added_at)).await {
                // A leave made while the adoption ran has already answered it.
                Ok(community) if known_removals().get(&entry.community_id).is_some_and(|&at| at >= entry.added_at) => {
                    let channel_ids = community.channels.iter().map(|c| crate::simd::hex::bytes_to_hex_32(&c.id.0)).collect();
                    let _ = crate::db::community::delete_community(&entry.community_id);
                    removed.push((entry.community_id.clone(), channel_ids));
                }
                Ok(community) => {
                    // The staff write secret never rides a bundle shape — adopt it
                    // from the list entry directly, and only when it derives to the
                    // control_pk held for exactly this epoch (CORD-02 §5/§8). A
                    // stale secret fails closed to read-only; a 136-byte base blob
                    // or the Grant's control_wrap re-delivers on the walk forward.
                    if let (Some(pk), Some(root_hex)) = (community.control_pk, entry.current.control_root.as_deref()) {
                        if let Some(root) = crate::simd::hex::hex_to_bytes_32_checked(root_hex) {
                            if super::derive::control_signer_group_key(&root, community.id(), community.root_epoch).pk() == pk

                            {
                                let mut held = community.clone();
                                held.control_root = Some(root);
                                let _ = crate::db::community::save_community_v2(&held);
                            }
                        }
                    }
                    joined.push(community);
                }
                // A listed-but-unadoptable entry is the failure mode that reads as
                // "cross-device sync is broken": the community never appears and any
                // parked invite for it is never retired.
                Err(e) => crate::log_net_fail!(
                    "[CommunityList] {} is listed but adoption failed: {e}",
                    &entry.community_id[..entry.community_id.len().min(8)]
                ),
            }
        }
        Ok(ListSyncOutcome { joined, removed })
    })
    .await
}

// ── Control edition authoring (CORD-04 roles / CORD-02 §6 / CORD-03 §2) ──────

/// Publish one control edition (a role, grant, banlist, community-metadata, or
/// channel-metadata edit) at the next version for its entity, chaining `prev` from
/// our held head, and advance our local floor. Authority is enforced by every
/// reader's roster fold (CORD-04 §5: authority is rejection, not prevention), so this
/// requires only a valid local signer; a well-behaved client checks its own rank
/// first, but a reader drops an unauthorized edition regardless.
/// This actor's authority citation for a control edition (CORD-04 §5): the head
/// of their OWN Grant entity, pinned by coordinate + version + edition hash.
///
/// A SYNC FLOOR, not a verdict — a verifier refuses to act until it has synced
/// at least this Grant, then resolves rank against its CURRENT roster, so a
/// demoted admin is never grandfathered by an old-but-once-valid citation.
///
/// `None` for the owner (supreme, rank comes from the community id) and `None`
/// when no Grant head is held — an actor who cannot cite has no rank to claim,
/// and the edition is dropped by a conforming reader either way.
/// The verify half of [`my_authority_citation`] (CORD-04 §5): does the actor's
/// cited Grant prove authority we have actually SYNCED? The owner is supreme and
/// cites nothing. A non-owner MUST cite, and we must hold that Grant at ≥ the
/// cited version with the cited hash at the tip — else fail closed, because
/// honoring an action whose authority we can't confirm is exactly how a demoted
/// moderator keeps moderating.
///
/// Completeness only: the permission + outrank is the separate roster check, so a
/// since-demoted actor is refused there (refuse-superseded). An action citing a
/// version we haven't synced parks and is re-judged on the next roster sync — the
/// sync path can't escalate to a blocking fetch.
/// Whom a Kick is honored from (CORD-04 §6): a signer holding KICK, or BAN for the departure an
/// un-ban writes, who strictly outranks the target, is not banned, and cites a Grant we hold.
pub(super) fn kick_judge<'a>(
    cid_hex: &'a str,
    owner_hex: &'a str,
    roles: &'a crate::community::roles::CommunityRoles,
) -> impl Fn(&PublicKey, &PublicKey, Option<&crate::community::edition::AuthorityCitation>) -> bool + 'a {
    use crate::community::roles::Permissions;
    move |actor, target, citation| {
        let (actor_hex, target_hex) = (actor.to_hex(), target.to_hex());
        // The roster check first: it is in memory, the other two read the database.
        [Permissions::KICK, Permissions::BAN].into_iter().any(|bit| roles.can_act_on_member(&actor_hex, Some(owner_hex), &target_hex, bit))
            // A banned member's Guestbook events count for nothing (CORD-04 §4).
            && !crate::db::community::is_author_banned(cid_hex, actor)
            && citation_is_synced(cid_hex, owner_hex, &actor_hex, citation)
    }
}

pub(super) fn citation_is_synced(
    cid_hex: &str,
    owner_hex: &str,
    actor_hex: &str,
    citation: Option<&crate::community::edition::AuthorityCitation>,
) -> bool {
    if owner_hex == actor_hex {
        return true;
    }
    if citation.is_none() {
        return false;
    }
    let cid_bytes = crate::simd::hex::hex_to_bytes_32(cid_hex);
    let actor_bytes = crate::simd::hex::hex_to_bytes_32(actor_hex);
    let grant_hex = crate::simd::hex::bytes_to_hex_32(&super::derive::grant_locator(
        &crate::community::CommunityId(cid_bytes),
        &actor_bytes,
    ));
    let head: Vec<crate::community::edition::EntityHead> =
        crate::db::community::get_edition_head(cid_hex, &grant_hex)
            .ok()
            .flatten()
            .map(|(version, self_hash)| crate::community::edition::EntityHead {
                entity_hex: grant_hex.clone(),
                version,
                self_hash,
                inner_id: [0u8; 32],
                citation: None,
            })
            .into_iter()
            .collect();
    crate::community::edition::authority_citation_satisfied(&head, Some(owner_hex), actor_hex, &grant_hex, citation)
}

/// [`my_authority_citation`], but refusing to emit an action every reader will
/// drop (CORD-04 §5: which non-owner actions must cite).
///
/// The citation is built from PERSISTED heads, which only `follow_control` writes
/// — so an admin who hasn't folded yet (just promoted, or freshly restored) would
/// otherwise publish uncited and have the action silently vanish on every client,
/// with nothing shown locally. Failing here turns that into one retryable error.
fn required_authority_citation(
    community: &CommunityV2,
    actor: &PublicKey,
) -> Result<Option<crate::community::edition::AuthorityCitation>, String> {
    if community.owner().ok().as_ref() == Some(actor) {
        return Ok(None); // supreme, cites nothing
    }
    my_authority_citation(community, actor).map(Some).ok_or_else(|| {
        "your admin rights aren't synced on this device yet — reopen the community and retry".to_string()
    })
}

fn my_authority_citation(
    community: &CommunityV2,
    actor: &PublicKey,
) -> Option<crate::community::edition::AuthorityCitation> {
    if community.owner().ok().as_ref() == Some(actor) {
        return None;
    }
    let entity_id = super::derive::grant_locator(community.id(), &actor.to_bytes());
    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
    let entity_hex = crate::simd::hex::bytes_to_hex_32(&entity_id);
    crate::db::community::get_edition_head(&cid_hex, &entity_hex)
        .ok()
        .flatten()
        .map(|(version, edition_hash)| crate::community::edition::AuthorityCitation { entity_id, version, edition_hash })
}

/// The row as the Control Plane leaves it now, read again under the lock every whole-row
/// writer takes. Hold the guard while acting on it; drop it before anything that rotates.
async fn follow_fresh<T: Transport + ?Sized>(transport: &T, id: &crate::community::CommunityId) -> Result<(tokio::sync::OwnedMutexGuard<()>, CommunityV2), String> {
    let guard = super::realtime::follow_lock(id).lock_owned().await;
    let current = crate::db::community::load_community_v2(id)?.ok_or("v2 community not found")?;
    follow_control(transport, &current).await?;
    let fresh = crate::db::community::load_community_v2(id)?.ok_or("v2 community not found")?;
    Ok((guard, fresh))
}

/// Refuse a root-derived write whose in-hand struct predates a rotation.
///
/// A Ban's refound buries the old root while the caller's `CommunityV2` still
/// points at it; publishing there lands on a plane nobody folds — the action
/// "succeeds" and silently never happened (an unban that doesn't unban, an
/// invite that strands its joiner on a dead epoch). Failing loudly instead lets
/// the caller reload and retry against the living root.
fn assert_current_root(community: &CommunityV2) -> Result<(), String> {
    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
    match crate::db::community::get_server_root_epoch(&cid_hex)? {
        Some(held) if held != community.root_epoch.0 => Err(format!(
            "the community re-founded mid-action (epoch {} -> {held}); retry",
            community.root_epoch.0
        )),
        _ => Ok(()), // no row = a not-yet-persisted create; nothing newer to defer to
    }
}

async fn publish_control_edition<T: Transport + ?Sized>(
    transport: &T,
    community: &CommunityV2,
    vsk: &str,
    entity_id: &[u8; 32],
    content: &str,
) -> Result<(), String> {
    publish_control_edition_at(transport, community, vsk, entity_id, content, now_ms() / 1000).await
}

/// [`publish_control_edition`] dated `at` (seconds).
async fn publish_control_edition_at<T: Transport + ?Sized>(
    transport: &T,
    community: &CommunityV2,
    vsk: &str,
    entity_id: &[u8; 32],
    content: &str,
    at: u64,
) -> Result<(), String> {
    publish_control_edition_wrap_at(transport, community, vsk, entity_id, content, at).await.map(|_| ())
}

/// [`publish_control_edition_at`], handing back the wrap it published.
async fn publish_control_edition_wrap_at<T: Transport + ?Sized>(
    transport: &T,
    community: &CommunityV2,
    vsk: &str,
    entity_id: &[u8; 32],
    content: &str,
    at: u64,
) -> Result<Event, String> {
    crate::db::scoped(async move {
        assert_current_root(community)?;
        let signer = crate::signer::active_signer()?;
        let my_pk = me_pk()?;
        // On a split epoch the signing secret is the staff-held control_root
        // (CORD-02 §2) — a member without it fails HERE with a readable error
        // instead of minting a wrap every reader and relay drops.
        let view = control::ControlPlane::of(community);
        let control = view.write_group()?;
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let entity_hex = crate::simd::hex::bytes_to_hex_32(entity_id);
        let (version, prev) = match crate::db::community::get_edition_head(&cid_hex, &entity_hex)? {
            Some((v, h)) => (v + 1, Some(h)),
            None => (1, None),
        };
        // CORD-04 §5: a non-owner names the exact Grant edition it claims its rank
        // under. Computed here rather than passed in — the citation is a property of
        // WHO IS ACTING, identical for every entity kind, so deciding it per call
        // site is nine chances to forget (and nine were, silently: every site passed
        // None). The owner cites nothing; their rank is the community id itself.
        let citation = required_authority_citation(community, &my_pk)?;
        // On Roles v2 every edition is marked: its hash covers its signer and it names its
        // Community (CORD-04 §1). A Roles v2 kind is marked even while the switch is under way.
        let everyone_hex = crate::simd::hex::bytes_to_hex_32(&super::derive::everyone_locator(community.id()));
        let marked = [super::vsk::ROLE_V2, super::vsk::TENURE, super::vsk::CATEGORY, super::vsk::CHANNEL_ACL, super::vsk::CHANNEL_SYNC, super::vsk::WRITERS].contains(&vsk)
            || crate::db::community::get_edition_head(&cid_hex, &everyone_hex)?.is_some();
        let binding = marked.then(|| super::derive::edition_binding(community.id()));
        let rumor = control::build_edition_rumor_bound(my_pk, vsk, entity_id, version, prev.as_ref(), content, at, citation.as_ref(), binding);
        // Readers judge the edition's own time; relays refuse a wrap dated ahead.
        let (wrap, _) = control::seal_control_edition_signed(&signer, my_pk, &rumor, &control, Timestamp::from_secs(at.min(now_ms() / 1000))).await.map_err(|e| e.to_string())?;
        // A Tenure is what keeps a removed member's decisions standing, so it goes to every relay.
        if vsk == super::vsk::TENURE {
            transport.publish_durable(&wrap, &community.relays).await?;
        } else {
            transport.publish(&wrap, &community.relays).await?;
        }
        // Advance our own floor so a follow-up edit chains from this head and refuse-
        // downgrade holds; open our own wrap to recover the self_hash + inner_id.
        // Re-check the session AFTER the publish await: a swap mid-publish means the
        // pool now points at another account's DB — skipping is safe (the next own
        // edit rebuilds the same head from the relay's copy).
        hold_wrap(community, &wrap);
        if let Ok((ed, _)) = control::open_control_edition(&wrap, &control) {
            crate::db::community::set_family_head_at_epoch(&cid_hex, &entity_hex, ed.version, &ed.self_hash, &ed.inner_id, &ed.author.to_bytes(), community.root_epoch.0, floor_family(&ed.vsk))?;
            hold_own(community, ed);
        }
        Ok(wrap)
    })
    .await
}

/// Merge our OWN just-published Role/Grant into the locally stored roster.
///
/// v2 persists the roster only inside `follow_control`, so a role or grant we
/// just published is invisible to every sync local read (entitlement, capability
/// gates, the next grant) until the next fold. This writes what we are already
/// authorized to have written; the next fold recomputes from the plane and
/// converges. Mirrors the fold's own write, so the stored `roles_at` is left
/// alone — a real edition always outranks this optimistic merge.
fn merge_local_roster(cid_hex: &str, role: Option<&crate::community::roles::Role>, grant: Option<&crate::community::roles::MemberGrant>) {
    let mut roster = crate::db::community::get_community_roles(cid_hex).unwrap_or_default();
    if let Some(r) = role {
        match roster.roles.iter_mut().find(|x| x.role_id == r.role_id) {
            Some(slot) => *slot = r.clone(),
            None => roster.roles.push(r.clone()),
        }
    }
    if let Some(g) = grant {
        match roster.grants.iter_mut().find(|x| x.member == g.member) {
            Some(slot) => *slot = g.clone(),
            None => roster.grants.push(g.clone()),
        }
    }
    let at = crate::db::community::get_community_roles_at(cid_hex).unwrap_or(0);
    if let Err(e) = crate::db::community::set_community_roles(cid_hex, &roster, at) {
        crate::log_warn!("v2: local roster merge failed (heals on the next control fold): {e}");
    }
}

/// Create or edit a Role (vsk 1, CORD-04 §2). `role.role_id` is the coordinate; a
/// rename or permission change is a versioned edit of the same id. Gated on the
/// reader side by `MANAGE_ROLES` + outrank.
pub async fn set_role<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, role: &crate::community::roles::Role) -> Result<(), String> {
    super::roles::validate_role(role)?;
    let content = super::roles::role_content_json(role)?;
    let role_id = crate::simd::hex::hex_to_bytes_32_checked(&role.role_id).ok_or("role_id must be 32-byte hex")?;
    publish_control_edition(transport, community, vsk::ROLE, &role_id, &content).await
}

/// Grant or revoke a member's Roles (vsk 3, CORD-04 §2). Empty `role_ids` is a
/// revoke. Gated on the reader side by `MANAGE_ROLES` + outrank of every role + the
/// member. Staff-ness (whether the Grant must deliver the `control_root`,
/// CORD-04 §3) is judged from the persisted roster; internal callers holding a
/// fresher fetched view use `grant_roles_with_roster`.
pub async fn grant_roles<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, member: &PublicKey, role_ids: Vec<String>) -> Result<(), String> {
    grant_roles_sealing(transport, community, member, role_ids, Seal::Strict).await
}

async fn grant_roles_sealing<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, member: &PublicKey, role_ids: Vec<String>, seal: Seal) -> Result<(), String> {
    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
    let roster = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
    // A role this device hasn't folded is unjudgeable for staff-ness, and
    // guessing "not staff" publishes a staff-making Grant with NO control_wrap
    // — seating a staffer who cannot write, silently (CORD-04 §3 makes the wrap
    // mandatory on such a Grant). Resolve it from the network first; only the
    // definitions still missing after that fall back to the local view.
    // Internal callers already holding a fetched roster use
    // `grant_roles_with_roster` and skip this round trip.
    let roster = if community.control_pk.is_some() && role_ids.iter().any(|rid| roster.role(rid).is_none()) {
        let mut fetched = fetch_authority(transport, community).await.roles;
        for r in roster.roles {
            if !fetched.roles.iter().any(|x| x.role_id == r.role_id) {
                fetched.roles.push(r);
            }
        }
        fetched
    } else {
        roster
    };
    grant_roles_with_roster_sealing(transport, community, member, role_ids, &roster, seal).await
}

/// The `control_wrap` a Grant carries when its role set leaves `member` staff
/// (CORD-04 §3): the current epoch's `control_root`, NIP-44-encrypted under
/// the granter↔member pairwise key, `epoch_be[8] ‖ control_root[32]` inside.
/// `None` when nothing is owed — a legacy pre-split epoch, or a grant that
/// leaves the member non-staff. Attached on EVERY staff-leaving grant, not
/// just the first: a re-issue with a fresh wrap is the spec's own re-delivery
/// path (a lost key, a head superseded before its member fetched it), and the
/// marginal cost is one ECDH.
///
/// Errs when a wrap is owed but this granter cannot mint one: a staff-making
/// edition MUST carry a wrap fresh for the current epoch — publishing without
/// it would seat a staffer who cannot write, silently. (The publish itself
/// would fail on the same missing secret, but the promotion must never outrun
/// the delivery.)
async fn control_wrap_owed(community: &CommunityV2, makes_staff: bool, member: &PublicKey) -> Result<Option<String>, String> {
    if !makes_staff {
        return Ok(None);
    }
    let Some(pk) = community.control_pk else {
        return Ok(None); // legacy epoch — the plane has no write key to deliver
    };
    let Some(cr) = community.control_root else {
        return Err("you don't hold this community's staff write key, so you can't promote to staff yet".to_string());
    };
    // Never deliver a secret that doesn't derive to the held address — the
    // recipient's fail-closed check would drop it anyway (CORD-04 §3).
    if super::derive::control_signer_group_key(&cr, community.id(), community.root_epoch).pk() != pk {
        return Err("this community's held staff write key is corrupt; re-sync before promoting".to_string());
    }
    use nostr_sdk::prelude::AsyncNip44;
    let signer = crate::signer::active_signer()?;
    let wrap = signer
        .nip44_encrypt_async(member, &super::rekey::control_wrap_b64(community.root_epoch, &cr))
        .await
        .map_err(|e| format!("staff key delivery: {e}"))?;
    Ok(Some(wrap))
}

/// [`grant_roles`] judging staff-ness against a caller-supplied roster — the
/// freshest view the caller holds (a fetched authority merge, or one carrying
/// a role minted moments ago that no fold has read back).
async fn grant_roles_with_roster<T: Transport + ?Sized>(
    transport: &T,
    community: &CommunityV2,
    member: &PublicKey,
    role_ids: Vec<String>,
    roster: &crate::community::roles::CommunityRoles,
) -> Result<(), String> {
    grant_roles_with_roster_sealing(transport, community, member, role_ids, roster, Seal::Strict).await
}

async fn grant_roles_with_roster_sealing<T: Transport + ?Sized>(
    transport: &T,
    community: &CommunityV2,
    member: &PublicKey,
    role_ids: Vec<String>,
    roster: &crate::community::roles::CommunityRoles,
    seal: Seal,
) -> Result<(), String> {
    // Every Role a Grant takes away seals what the member decided with it first (CORD-04 §9).
    // A strip to nothing seals whatever the plane says they held, stale roster or not.
    if role_ids.is_empty() || roster.roles_of(&member.to_hex()).any(|r| !role_ids.contains(&r.role_id)) {
        seal_standing(transport, community, std::slice::from_ref(member), seal).await?;
    }
    // A grant that leaves the member staff carries the staff write key in the
    // edition itself (CORD-04 §3) — promotion and delivery are one signed
    // edition: nothing separate to send, race, or watch an inbox for. The owner
    // holds the key by right.
    let owner_self = community.owner().is_ok_and(|o| o == *member);
    let control_wrap = control_wrap_owed(community, !owner_self && roster.roles_make_staff(&role_ids), member).await?;
    let grant = crate::community::roles::MemberGrant { member: member.to_hex(), role_ids };
    let content = super::roles::grant_content_json_with_wrap(&grant, control_wrap)?;
    let eid = super::derive::grant_locator(community.id(), &member.to_bytes());
    publish_control_edition(transport, community, vsk::GRANT, &eid, &content).await
}

/// The community's @admin role id: the folded Server-scope ADMIN_ALL role when one
/// exists, else (with `create_if_missing`) a DETERMINISTIC mint — the same id on
/// every device, so concurrent grants converge as editions of ONE entity instead
/// of forking two Admin roles.
pub async fn ensure_admin_role<T: Transport + ?Sized>(
    transport: &T,
    community: &CommunityV2,
    view: &AuthorityView,
    create_if_missing: bool,
) -> Result<Option<String>, String> {
    use crate::community::roles::{Permissions, Role, RoleScope};
    // The finder tests the FROZEN founding mask, never ADMIN_ALL: published
    // Admin roles predate later bits (PIN_MESSAGES...), and requiring a bit
    // they can't have would orphan every one of them and mint a duplicate.
    if let Some(r) = view
        .roles
        .roles
        .iter()
        .find(|r| matches!(r.scope, RoleScope::Server) && r.permissions.contains(Permissions::ADMIN_FOUNDING_MASK))
    {
        return Ok(Some(r.role_id.clone()));
    }
    if !create_if_missing {
        return Ok(None);
    }
    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
    let role_id = crate::crypto::sha256_hex(format!("vector/v2/role/admin/{cid_hex}").as_bytes());
    set_role(transport, community, &Role::admin(role_id.clone())).await?;
    Ok(Some(role_id))
}

/// Grant the @admin role (minting it deterministically when absent), MERGED into
/// the member's existing grant — a grant entity replaces whole (CORD-04 §2), so a
/// blind push would erase their other roles. Owner-only: the position-1 Admin is
/// manageable only by position 0 (an equal never outranks it), and refusing
/// before any publish keeps an unauthorized edition of the DETERMINISTIC admin
/// entity from advancing this device's own floor onto a head readers reject.
pub async fn grant_admin<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, member: &PublicKey) -> Result<(), String> {
    crate::db::scoped(async move {
        // Guard spans the multi-page fetch below: a swap mid-fetch must not let the
        // downstream publish's own (post-swap) guard write account A's floor into B.
        let my_pk = me_pk()?;
        if my_pk != community.owner()? {
            return Err("only the community owner can grant @admin".to_string());
        }
        let view = fetch_authority(transport, community).await;
        let member_hex = member.to_hex();
        require_grant_head(community, &view, &member_hex)?;
        let role_id = ensure_admin_role(transport, community, &view, true)
            .await?
            .expect("create_if_missing yields an id");
        let mut role_ids = view
            .roles
            .grants
            .iter()
            .find(|g| g.member == member_hex)
            .map(|g| g.role_ids.clone())
            .unwrap_or_default();
        if role_ids.contains(&role_id) {
            return Ok(()); // already admin — don't bump the grant edition for nothing.
        }
        role_ids.push(role_id.clone());
        // Judge staff-ness against a roster that HOLDS the admin definition: a
        // just-minted role hasn't folded into the fetched view yet, and missing it
        // would seat an admin without the write key (CORD-04 §3).
        let mut roster = view.roles.clone();
        if roster.role(&role_id).is_none() {
            roster.roles.push(crate::community::roles::Role::admin(role_id));
        }
        grant_roles_with_roster(transport, community, member, role_ids, &roster).await
    })
    .await
}

/// Strip the @admin role from the member's grant, preserving their other roles.
/// A no-op when they don't hold it. Owner-only, like [`grant_admin`].
pub async fn revoke_admin<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, member: &PublicKey) -> Result<(), String> {
    crate::db::scoped(async move {
        let my_pk = me_pk()?;
        if my_pk != community.owner()? {
            return Err("only the community owner can revoke @admin".to_string());
        }
        let view = fetch_authority(transport, community).await;
        let member_hex = member.to_hex();
        require_grant_head(community, &view, &member_hex)?;
        let Some(role_id) = ensure_admin_role(transport, community, &view, false).await? else {
            return Ok(()); // no admin role exists — nothing to revoke.
        };
        let mut role_ids = view
            .roles
            .grants
            .iter()
            .find(|g| g.member == member_hex)
            .map(|g| g.role_ids.clone())
            .unwrap_or_default();
        let before = role_ids.len();
        role_ids.retain(|r| r != &role_id);
        if role_ids.len() == before {
            return Ok(());
        }
        // A demotion can still leave the member staff through a KEPT role — the
        // fetched view holds every kept definition, so judge against it.
        grant_roles_with_roster(transport, community, member, role_ids, &view.roles).await
    })
    .await
}

// ── Role authoring (CORD-04 §2/§3) ──────────────────────────────────────────
//
// Every check below is the rule a READER applies, run before publishing so this
// device never signs an edition the fold drops. That matters beyond wasted work:
// editions are version-chained, and a dropped head still advances the author's own
// floor onto a state nobody honours.

/// Who is authoring a role change, and from what standing.
struct RoleAuthor {
    me_hex: String,
    owner_hex: String,
    is_owner: bool,
    /// The owner is 0; otherwise the highest (lowest-numbered) role position held.
    rank: u32,
    /// The roster the author acts against, for downward support.
    roles: crate::community::roles::CommunityRoles,
}

impl RoleAuthor {
    /// Strictly above `position`: equal never acts on equal (CORD-04 §3).
    fn outranks(&self, position: u32) -> bool {
        self.is_owner || self.rank < position
    }
    /// Whether an edition touching everything down to `reach` and carrying `bits` is one
    /// readers admit (CORD-04 §3): MANAGE_ROLES, and every bit, from the author's roles
    /// positioned strictly above it. Judged on the edition alone, as readers judge it.
    fn supports(&self, reach: u32, bits: u64) -> bool {
        use crate::community::roles::Permissions;
        if self.is_owner {
            return true;
        }
        let support = self.roles.permissions_above(&self.me_hex, reach);
        support.contains(Permissions::MANAGE_ROLES) && bits & !support.0 == 0
    }
}

fn role_author(community: &CommunityV2, view: &AuthorityView) -> Result<RoleAuthor, String> {
    use crate::community::roles::Permissions;
    let me = me_pk()?;
    let owner = community.owner()?;
    let (me_hex, owner_hex) = (me.to_hex(), owner.to_hex());
    let is_owner = me == owner;
    if !is_owner {
        if view.banned.contains(&me_hex) {
            return Err("you are banned from this community".to_string());
        }
        if !view.roles.is_authorized(&me_hex, Some(&owner_hex), Permissions::MANAGE_ROLES) {
            return Err("managing roles needs the Manage Roles permission".to_string());
        }
    }
    let rank = if is_owner { 0 } else { view.roles.highest_position(&me_hex).unwrap_or(u32::MAX) };
    Ok(RoleAuthor { me_hex, owner_hex, is_owner, rank, roles: view.roles.clone() })
}

/// A role's current head must be in hand before replacing it, or this edition could
/// chain from a stale version and lose to (or fork from) the one the relays hold.
fn require_role_head(view: &AuthorityView, role_id: &str) -> Result<(), String> {
    let eid = role_id.to_ascii_lowercase();
    if view.floored.contains(&eid) && !view.head_entities.contains(&eid) {
        return Err("this role's current state could not be fetched; try again once relays serve the control plane".to_string());
    }
    Ok(())
}

/// Mint a Role beneath everything that exists, including its author: a new role
/// starts at the bottom, as in Discord, and no role may sit at or above its minter.
/// Returns the new `role_id`.
pub async fn create_role<T: Transport + ?Sized>(
    transport: &T,
    community: &CommunityV2,
    name: &str,
    color: u32,
    permissions: u64,
    scope: crate::community::roles::RoleScope,
) -> Result<String, String> {
    crate::db::scoped(async move {
        use crate::community::roles::{Permissions, Role};
        let view = fetch_authority(transport, community).await;
        let author = role_author(community, &view)?;
        if view.roles.roles.len() >= super::roles::MAX_ROLES_PER_COMMUNITY {
            return Err(format!("a community holds at most {} roles", super::roles::MAX_ROLES_PER_COMMUNITY));
        }
        let name = name.trim();
        if name.is_empty() {
            return Err("a role needs a name".to_string());
        }
        // Channel access roles are parked at the bottom band on purpose (see
        // `channel_access_role`), so a new role lands just above that band rather than
        // in the one slot left beneath it, where the next would saturate into a peer.
        let floor = view
            .roles
            .roles
            .iter()
            .map(|r| r.position)
            .filter(|p| *p < ACCESS_ROLE_POSITION)
            .max()
            .unwrap_or(0)
            .max(author.rank);
        if floor.saturating_add(1) >= ACCESS_ROLE_POSITION {
            return Err("there's no room beneath your role for a new one; reorder the roles first".to_string());
        }
        if !author.supports(floor.saturating_add(1), permissions) {
            return Err("you can't give a role permissions you don't hold".to_string());
        }
        let role = Role {
            role_id: crate::simd::hex::bytes_to_hex_32(&super::super::random_32()),
            name: name.to_string(),
            position: floor.saturating_add(1),
            permissions: Permissions(permissions),
            scope,
            color,
            rank: None, display: false, mentionable: false,
            extra: Default::default(),
        };
        set_role(transport, community, &role).await?;
        Ok(role.role_id)
    })
    .await
}

/// Edit a Role's name, colour and permissions, keeping its position, its scope and
/// every field another client wrote. Both CORD-04 §3 gates hold: the author outranks the
/// role as it stands, and the edition claims nothing at or above them.
pub async fn edit_role<T: Transport + ?Sized>(
    transport: &T,
    community: &CommunityV2,
    role_id: &str,
    name: &str,
    color: u32,
    permissions: u64,
    scope: crate::community::roles::RoleScope,
) -> Result<(), String> {
    crate::db::scoped(async move {
        use crate::community::roles::Permissions;
        let view = fetch_authority(transport, community).await;
        let author = role_author(community, &view)?;
        let current = view.roles.role(role_id).cloned().ok_or("no such role")?;
        require_role_head(&view, role_id)?;
        if !author.outranks(current.position) {
            return Err("you can only edit roles beneath your own".to_string());
        }
        if !author.supports(current.position, permissions) {
            return Err("you can't give a role permissions you don't hold".to_string());
        }
        let name = name.trim();
        if name.is_empty() {
            return Err("a role needs a name".to_string());
        }
        // A scope is a channel's access list: moving it would re-entitle every holder at
        // once, and keys follow grants, not role edits. It is fixed at creation.
        if scope != current.scope {
            return Err("a role's channel can't be changed once it's created".to_string());
        }
        let mut next = current.clone();
        next.name = name.to_string();
        next.color = color;
        next.permissions = Permissions(permissions);
        if next == current {
            return Ok(());
        }
        set_role(transport, community, &next).await
    })
    .await
}

/// Reorder the roles beneath the author, top to bottom as `ordered` lists them.
///
/// Positions are the whole of CORD-04's ordering (no RoleOrder entity), so a reorder
/// republishes each role whose position moves, and nothing else. The author's own
/// rank and everything above it stay put: the moved set is renumbered from just
/// beneath them, which also resolves any ties into one definite order. Returns how
/// many roles were republished.
pub async fn reorder_roles<T: Transport + ?Sized>(
    transport: &T,
    community: &CommunityV2,
    ordered: &[String],
) -> Result<usize, String> {
    crate::db::scoped(async move {
        let view = fetch_authority(transport, community).await;
        let author = role_author(community, &view)?;
        let mut movable: Vec<crate::community::roles::Role> = view
            .roles
            .roles
            .iter()
            .filter(|r| author.outranks(r.position))
            .cloned()
            .collect();
        // The requested order first; anything it omits keeps its current relative place.
        movable.sort_by(|a, b| a.position.cmp(&b.position).then_with(|| a.role_id.cmp(&b.role_id)));
        let rank_of = |id: &str| ordered.iter().position(|o| o.eq_ignore_ascii_case(id));
        let mut keyed: Vec<(usize, usize, crate::community::roles::Role)> = movable
            .into_iter()
            .enumerate()
            .map(|(i, r)| (rank_of(&r.role_id).unwrap_or(usize::MAX), i, r))
            .collect();
        keyed.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.cmp(&b.1)));
        let mut changed = Vec::new();
        for (i, (_, _, role)) in keyed.into_iter().enumerate() {
            let position = author.rank.saturating_add(1).saturating_add(i as u32);
            if role.position != position {
                if !author.supports(role.position.min(position), role.permissions.0) {
                    return Err(format!("you can't move \"{}\": it has permissions you don't hold", role.name));
                }
                require_role_head(&view, &role.role_id)?;
                let mut next = role;
                next.position = position;
                changed.push(next);
            }
        }
        for role in &changed {
            set_role(transport, community, role).await?;
        }
        Ok(changed.len())
    })
    .await
}

/// Publish a Roles v2 edition of `role` (vsk 13, CORD-04 §2).
pub async fn set_role_v2<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, role: &crate::community::roles::Role) -> Result<(), String> {
    if role.name.len() > super::roles::MAX_ROLE_NAME_BYTES {
        return Err("role name over 64 bytes".to_string());
    }
    let content = super::roles::role_v2_content_json(role)?;
    let role_id = crate::simd::hex::hex_to_bytes_32_checked(&role.role_id).ok_or("role_id must be 32-byte hex")?;
    publish_control_edition(transport, community, vsk::ROLE_V2, &role_id, &content).await
}

/// Who holds `role_id`.
fn holders_of(view: &AuthorityView, role_id: &str) -> Vec<PublicKey> {
    view.roles
        .grants
        .iter()
        .filter(|g| g.role_ids.iter().any(|r| r == role_id))
        .filter_map(|g| PublicKey::from_hex(&g.member).ok())
        .collect()
}

/// The live Roles in rank order, top first, as the fold ordered them.
fn ranked(view: &AuthorityView) -> Vec<&crate::community::roles::Role> {
    let mut roles: Vec<&crate::community::roles::Role> = view.roles.roles.iter().filter(|r| r.rank.is_some()).collect();
    roles.sort_by(|a, b| a.rank.as_deref().unwrap_or("").as_bytes().cmp(b.rank.as_deref().unwrap_or("").as_bytes()).then_with(|| a.role_id.cmp(&b.role_id)));
    roles
}

fn require_activated(view: &AuthorityView) -> Result<(), String> {
    if !view.activated {
        return Err("this community still uses the legacy roster".to_string());
    }
    // A read that lost @everyone would diff every member into or out of every channel.
    if view.roles.everyone.is_none() || !view.everyone_served {
        return Err("the community's roles couldn't be read; try again".to_string());
    }
    Ok(())
}

/// Mint a Roles v2 Role at the bottom, beneath everything, as in Discord. Returns its id.
pub async fn create_role_v2<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, name: &str, color: u32, permissions: u64) -> Result<String, String> {
    crate::db::scoped(async move {
        use crate::community::roles::{Permissions, Role, RoleScope};
        let view = fetch_authority(transport, community).await;
        require_activated(&view)?;
        let author = role_author(community, &view)?;
        if view.roles.roles.len() >= super::roles::MAX_ROLES_PER_COMMUNITY {
            return Err(format!("a community holds at most {} roles", super::roles::MAX_ROLES_PER_COMMUNITY));
        }
        let name = name.trim();
        if name.is_empty() {
            return Err("a role needs a name".to_string());
        }
        let order = ranked(&view);
        let bottom = order.iter().map(|r| r.position).max().unwrap_or(0).saturating_add(1);
        if !author.supports(bottom, permissions) {
            return Err("you can't give a role permissions you don't hold".to_string());
        }
        let rank = crate::community::rank::between(order.last().and_then(|r| r.rank.as_deref()), None).ok_or("no room left at the bottom; reorder the roles first")?;
        let role = Role {
            role_id: crate::simd::hex::bytes_to_hex_32(&super::super::random_32()),
            name: name.to_string(),
            position: bottom,
            permissions: Permissions(permissions),
            scope: RoleScope::Server,
            color,
            rank: Some(rank),
            display: false,
            mentionable: false,
            extra: Default::default(),
        };
        set_role_v2(transport, community, &role).await?;
        Ok(role.role_id)
    })
    .await
}

/// Edit a Roles v2 Role in place, keeping its rank and every field another client wrote.
#[allow(clippy::too_many_arguments)]
pub async fn edit_role_v2<T: Transport + ?Sized>(
    transport: &T,
    community: &CommunityV2,
    role_id: &str,
    name: &str,
    color: u32,
    permissions: u64,
    display: bool,
    mentionable: bool,
) -> Result<(), String> {
    crate::db::scoped(async move {
        use crate::community::roles::Permissions;
        let view = fetch_authority(transport, community).await;
        require_activated(&view)?;
        let author = role_author(community, &view)?;
        let current = view.roles.role(role_id).cloned().ok_or("no such role")?;
        require_role_head(&view, role_id)?;
        if !author.outranks(current.position) {
            return Err("you can only edit roles beneath your own".to_string());
        }
        if !author.supports(current.position, permissions) {
            return Err("you can't give a role permissions you don't hold".to_string());
        }
        let name = name.trim();
        if name.is_empty() {
            return Err("a role needs a name".to_string());
        }
        if current.permissions.0 & !permissions != 0 {
            seal_standing(transport, community, &holders_of(&view, role_id), Seal::Strict).await?;
        }
        let mut next = current;
        next.name = name.to_string();
        next.color = color;
        next.permissions = Permissions(permissions);
        next.display = display;
        next.mentionable = mentionable;
        set_role_v2(transport, community, &next).await?;
        let mut after = view.roles.clone();
        if let Some(slot) = after.roles.iter_mut().find(|r| r.role_id == next.role_id) {
            *slot = next;
        }
        settle_access(transport, community, &view.roles, &after).await
    })
    .await
}

/// Move a Roles v2 Role to `index` in the rank order (0 is the top): one edition, on the
/// moved Role alone, its key minted between its new neighbours.
pub async fn move_role_v2<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, role_id: &str, index: usize) -> Result<(), String> {
    crate::db::scoped(async move {
        let mut view = fetch_authority(transport, community).await;
        let before = view.roles.clone();
        move_role_in(transport, community, &mut view, role_id, index).await?;
        let after = roster_after_moves(transport, community, &view, &before, &[role_id.to_string()]).await;
        settle_access(transport, community, &before, &after).await
    })
    .await
}

/// Reorder the Roles to `ordered` (top first; Roles it leaves out keep their order after
/// it). The longest run already in order stays put and each other Role moves once, all
/// judged against one fold carried forward, so a relay slow to serve one move can't skew
/// the next.
pub async fn reorder_roles_v2<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, ordered: &[String]) -> Result<usize, String> {
    crate::db::scoped(async move {
        let mut view = fetch_authority(transport, community).await;
        require_activated(&view)?;
        let before = view.roles.clone();
        let mut cur: Vec<String> = ranked(&view).into_iter().map(|r| r.role_id.clone()).collect();
        let mut target: Vec<String> = ordered.iter().filter(|id| cur.contains(id)).cloned().collect();
        target.extend(cur.iter().filter(|id| !ordered.contains(id)).cloned());
        let seq: Vec<usize> = target.iter().map(|id| cur.iter().position(|c| c == id).expect("from cur")).collect();
        let n = seq.len();
        let (mut len, mut prev) = (vec![1usize; n], vec![usize::MAX; n]);
        for i in 0..n {
            for j in 0..i {
                if seq[j] < seq[i] && len[j] + 1 > len[i] {
                    len[i] = len[j] + 1;
                    prev[i] = j;
                }
            }
        }
        let mut keep = vec![false; n];
        let mut at = (0..n).max_by_key(|&i| (len[i], std::cmp::Reverse(i)));
        while let Some(k) = at {
            keep[k] = true;
            at = (prev[k] != usize::MAX).then_some(prev[k]);
        }
        // Each moved Role lands just after its predecessor in the target order.
        let mut moved = Vec::new();
        for i in (0..n).filter(|&i| !keep[i]) {
            let id = target[i].clone();
            let index = match i.checked_sub(1) {
                None => 0,
                Some(p) => cur.iter().filter(|c| **c != id).position(|c| *c == target[p]).map_or(0, |at| at + 1),
            };
            move_role_in(transport, community, &mut view, &id, index).await?;
            cur.retain(|c| *c != id);
            cur.insert(index.min(cur.len()), id.clone());
            moved.push(id);
        }
        if !moved.is_empty() {
            let after = roster_after_moves(transport, community, &view, &before, &moved).await;
            settle_access(transport, community, &before, &after).await?;
        }
        Ok(moved.len())
    })
    .await
}

/// The Roster to settle Role moves against. Readers re-judge every overwrite against the
/// new ranks, so their fold when a fresh read is whole and serves every move; else `local`,
/// carried forward from a whole read, which a failed read can't empty.
/// A local settle can't see which overwrites readers now drop, so the cut is owed against
/// `before` until a whole read lands.
async fn roster_after_moves<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, local: &AuthorityView, before: &crate::community::roles::CommunityRoles, moved: &[String]) -> crate::community::roles::CommunityRoles {
    let fresh = fetch_authority(transport, community).await;
    let serves = |id: &String| fresh.roles.role(id).is_some_and(|r| local.roles.role(id).is_some_and(|l| l.rank == r.rank));
    if fresh.everyone_served && !fresh.gapped && moved.iter().all(serves) {
        return fresh.roles;
    }
    crate::log_warn!("[Concord] role move settled against the local fold: the fresh read was partial");
    owe_settle(&crate::simd::hex::bytes_to_hex_32(&community.id().0), before);
    local.roles.clone()
}

/// Remember the Roster a change started from, when who lost access couldn't be read; kept
/// the earliest, so the owed settle covers every change since.
fn owe_settle(cid_hex: &str, before: &crate::community::roles::CommunityRoles) {
    if owed_settle(cid_hex).is_some() {
        return;
    }
    if let Ok(v) = serde_json::to_string(before) {
        let _ = crate::db::settings::set_sql_setting(format!("v2_settle:{cid_hex}"), v);
    }
}

fn owed_settle(cid_hex: &str) -> Option<crate::community::roles::CommunityRoles> {
    crate::db::settings::get_sql_setting(format!("v2_settle:{cid_hex}")).ok().flatten().and_then(|v| serde_json::from_str(&v).ok())
}

pub(crate) fn has_owed_settle(cid_hex: &str) -> bool {
    owed_settle(cid_hex).is_some()
}

/// Settle an owed change against a whole read: cut who lost access since, invite who gained.
async fn run_owed_settle<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> Result<bool, String> {
    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
    let Some(before) = owed_settle(&cid_hex) else { return Ok(false) };
    let fresh = fetch_authority(transport, community).await;
    if !fresh.everyone_served || fresh.gapped {
        return Err("the roster couldn't be read whole; the settle stays owed".to_string());
    }
    settle_access(transport, community, &before, &fresh.roles).await?;
    let _ = crate::db::settings::set_sql_setting(format!("v2_settle:{cid_hex}"), String::new());
    Ok(true)
}

async fn move_role_in<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, view: &mut AuthorityView, role_id: &str, index: usize) -> Result<(), String> {
    {
        require_activated(view)?;
        let author = role_author(community, view)?;
        let current = view.roles.role(role_id).cloned().ok_or("no such role")?;
        require_role_head(view, role_id)?;
        let others: Vec<&crate::community::roles::Role> = ranked(view).into_iter().filter(|r| r.role_id != current.role_id).collect();
        let index = index.min(others.len());
        let (above, below) = (index.checked_sub(1).map(|i| others[i]), others.get(index).copied());
        // The new spot sits just beneath `above`: the author must outrank it and the old one,
        // and hold the Role's bits through Roles above both.
        let spot = above.map_or(1, |a| a.position.saturating_add(1));
        if !author.outranks(current.position) || !(author.is_owner || above.is_some_and(|a| author.rank <= a.position)) {
            return Err("you can only move roles beneath your own, to a place beneath your own".to_string());
        }
        if !author.supports(current.position.min(spot), current.permissions.0) {
            return Err(format!("you can't move \"{}\": it has permissions you don't hold", current.name));
        }
        let rank = crate::community::rank::between(above.and_then(|r| r.rank.as_deref()), below.and_then(|r| r.rank.as_deref()))
            .ok_or("no room between those roles; move a neighbour first")?;
        if current.rank.as_deref().is_some_and(|old| old.as_bytes() < rank.as_bytes()) {
            seal_standing(transport, community, &holders_of(view, role_id), Seal::Strict).await?;
        }
        // A Grant is judged on the Role's rank as it stands, so moving the Role up past the
        // Grant's signer would take it from the member: re-sign those Grants as the mover.
        let resign: Vec<&crate::community::roles::MemberGrant> = view
            .roles
            .grants
            .iter()
            .filter(|g| g.role_ids.iter().any(|r| r == role_id))
            .filter(|g| view.grant_authors.get(&g.member).is_some_and(|a| *a != author.owner_hex && view.roles.highest_position(a).is_none_or(|p| p >= spot)))
            .collect();
        for g in &resign {
            let reach = g.role_ids.iter().filter_map(|r| view.roles.role(r).map(|x| x.position)).chain([spot, view.roles.highest_position(&g.member).unwrap_or(u32::MAX)]).min().unwrap_or(spot);
            if !author.outranks(view.roles.highest_position(&g.member).unwrap_or(u32::MAX)) || !author.supports(reach.min(spot), 0) {
                return Err(format!("moving \"{}\" there would take it from members you can't give it to", current.name));
            }
        }
        let resign: Vec<crate::community::roles::MemberGrant> = resign.into_iter().cloned().collect();
        let mut next = current;
        next.rank = Some(rank.clone());
        set_role_v2(transport, community, &next).await?;
        for g in &resign {
            let member = PublicKey::from_hex(&g.member).map_err(|e| e.to_string())?;
            grant_roles_with_roster(transport, community, &member, g.role_ids.clone(), &view.roles).await?;
        }
        // Carry the move forward in the view, as the next fold will read it.
        if let Some(r) = view.roles.roles.iter_mut().find(|r| r.role_id == role_id) {
            r.rank = Some(rank);
        }
        let keys: Vec<String> = view.roles.roles.iter().filter_map(|r| r.rank.clone()).collect();
        let ranks = crate::community::rank::dense_ranks(keys.iter().map(String::as_str));
        for r in view.roles.roles.iter_mut() {
            if let Some(p) = r.rank.as_deref().and_then(|k| ranks.get(k)) {
                r.position = *p;
            }
        }
        for g in &resign {
            view.grant_authors.insert(g.member.clone(), author.me_hex.clone());
        }
        Ok(())
    }
}

/// Delete a Roles v2 Role: terminal, it leaves every holder and frees its slot.
pub async fn delete_role_v2<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, role_id: &str) -> Result<(), String> {
    crate::db::scoped(async move {
        let view = fetch_authority(transport, community).await;
        require_activated(&view)?;
        let author = role_author(community, &view)?;
        let current = view.roles.role(role_id).cloned().ok_or("no such role")?;
        require_role_head(&view, role_id)?;
        if !author.outranks(current.position) || !author.supports(current.position, 0) {
            return Err("you can only delete roles beneath your own".to_string());
        }
        seal_standing(transport, community, &holders_of(&view, role_id), Seal::Strict).await?;
        let eid = crate::simd::hex::hex_to_bytes_32_checked(role_id).ok_or("role_id must be 32-byte hex")?;
        publish_control_edition(transport, community, vsk::ROLE_V2, &eid, &super::roles::role_v2_deleted_json(&current.role_id)).await?;
        let mut after = view.roles.clone();
        after.roles.retain(|r| r.role_id != current.role_id);
        settle_access(transport, community, &view.roles, &after).await
    })
    .await
}

/// Set what `@everyone` holds. Its editor holds every bit it carries through their Roles.
pub async fn set_everyone<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, permissions: u64) -> Result<(), String> {
    crate::db::scoped(async move {
        let view = fetch_authority(transport, community).await;
        // The owner can always restate @everyone: it is how a refused head is repaired.
        if me_pk()? != community.owner()? {
            require_activated(&view)?;
        } else if !view.activated {
            return Err("this community still uses the legacy roster".to_string());
        }
        let author = role_author(community, &view)?;
        if !author.supports(u32::MAX, permissions) {
            return Err("you can't give everyone permissions you don't hold".to_string());
        }
        let eid = super::derive::everyone_locator(community.id());
        let legacy = view.roles.legacy_channels.clone().or(crate::db::community::get_community_roles(&crate::simd::hex::bytes_to_hex_32(&community.id().0))?.legacy_channels);
        publish_control_edition(transport, community, vsk::ROLE_V2, &eid, &super::roles::everyone_content_json_with(permissions, legacy.as_ref())).await?;
        let mut after = view.roles.clone();
        after.everyone = Some(crate::community::roles::Permissions(permissions));
        settle_access(transport, community, &view.roles, &after).await
    })
    .await
}

/// Set, or with no bits clear, one overwrite on a Channel or Category (CORD-04 §8): judged
/// as readers judge it, on MANAGE_ROLES and every bit it touches held through Roles above
/// its target. Keys then follow View Channel in every Private Channel it reaches.
pub async fn set_overwrite<T: Transport + ?Sized>(
    transport: &T,
    community: &CommunityV2,
    scope: [u8; 32],
    target: crate::community::roles::OverwriteTarget,
    allow: u64,
    deny: u64,
) -> Result<(), String> {
    use crate::community::roles::{Overwrite, OverwriteTarget, Permissions, OVERWRITABLE};
    crate::db::scoped(async move {
        let view = fetch_authority(transport, community).await;
        require_activated(&view)?;
        let author = role_author(community, &view)?;
        if (allow | deny) & !OVERWRITABLE != 0 {
            return Err("only channel permissions can be set per channel".to_string());
        }
        if !community.channels.iter().any(|c| c.id.0 == scope) && !community.categories.iter().any(|k| k.id == scope) {
            return Err("no such channel or category".to_string());
        }
        // Keys follow the change: a private channel this device can't key can't be settled,
        // whether the rule is its own or its Category's.
        let scope_hex = crate::simd::hex::bytes_to_hex_32(&scope);
        if community.channels.iter().any(|c| c.private && c.key.is_none() && (c.id.0 == scope || view.roles.syncs.get(&crate::simd::hex::bytes_to_hex_32(&c.id.0)) == Some(&scope_hex))) {
            return Err(NO_KEY_TO_SHARE.to_string());
        }
        // Who might gain or lose a key must be readable before anything is published.
        access_candidates(community, &view.roles)?;
        let rank = match &target {
            OverwriteTarget::Everyone => u32::MAX,
            OverwriteTarget::Role(id) => view.roles.role(id).map(|r| r.position).ok_or("no such role")?,
            OverwriteTarget::Member(m) if *m == author.owner_hex => return Err("the owner holds every permission everywhere".to_string()),
            OverwriteTarget::Member(m) => view.roles.highest_position(m).unwrap_or(u32::MAX),
        };
        let current = view.roles.overwrites.iter().find(|o| o.scope == scope_hex && o.target == target);
        let (was_allow, was_deny) = current.map_or((0, 0), |o| (o.allow.0, o.deny.0));
        if !author.supports(rank, allow | deny | ((was_allow ^ allow) | (was_deny ^ deny))) {
            return Err("you can only set permissions you hold, for roles and members beneath you".to_string());
        }
        let target_bytes = super::roles::overwrite_target_bytes(community.id(), &target).ok_or("malformed target")?;
        let eid = super::derive::acl_locator(community.id(), &scope, &target_bytes);
        if !author.is_owner {
            require_role_head(&view, &crate::simd::hex::bytes_to_hex_32(&eid))?;
        }
        let o = Overwrite { scope: scope_hex.clone(), target: target.clone(), allow: Permissions(allow), deny: Permissions(deny) };
        publish_control_edition(transport, community, vsk::CHANNEL_ACL, &eid, &super::roles::overwrite_content_json(&o)).await?;
        let mut after = view.roles.clone();
        after.overwrites.retain(|x| !(x.scope == scope_hex && x.target == target));
        if allow != 0 || deny != 0 {
            after.overwrites.push(o);
        }
        settle_access(transport, community, &view.roles, &after).await
    })
    .await
}

/// Sync a Channel to `category`'s overwrites, or (`None`) back to its own (CORD-04 §8).
/// Every rule on both sides swaps at once, so the writer must be able to write them all.
pub async fn set_channel_sync<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, channel_id: &ChannelId, category: Option<[u8; 32]>) -> Result<(), String> {
    crate::db::scoped(async move {
        let view = fetch_authority(transport, community).await;
        require_activated(&view)?;
        let author = role_author(community, &view)?;
        let channel = community.channel(channel_id).ok_or("no such channel")?;
        if channel.private && channel.key.is_none() {
            return Err(NO_KEY_TO_SHARE.to_string());
        }
        if category.is_some_and(|k| !community.categories.iter().any(|c| c.id == k)) {
            return Err("no such category".to_string());
        }
        let chan = crate::simd::hex::bytes_to_hex_32(&channel_id.0);
        let cat = category.map(|k| crate::simd::hex::bytes_to_hex_32(&k));
        let mut scopes = vec![chan.as_str()];
        scopes.extend(cat.as_deref());
        scopes.extend(view.roles.syncs.get(&chan).map(String::as_str));
        if !may_swap_overwrites(&view.roles, Some(&author.owner_hex), &author.me_hex, &scopes, &|_| 0) {
            return Err("syncing swaps permissions you can't set; ask someone who can".to_string());
        }
        access_candidates(community, &view.roles)?;
        let eid = super::derive::sync_locator(community.id(), channel_id);
        if !author.is_owner {
            require_role_head(&view, &crate::simd::hex::bytes_to_hex_32(&eid))?;
        }
        publish_control_edition(transport, community, vsk::CHANNEL_SYNC, &eid, &super::roles::sync_content_json(&chan, cat.as_deref())).await?;
        let mut after = view.roles.clone();
        match cat {
            Some(k) => after.syncs.insert(chan, k),
            None => after.syncs.remove(&chan),
        };
        settle_access(transport, community, &view.roles, &after).await
    })
    .await
}

/// Why a change that opens a private channel this device can't key is refused (CORD-03 §5).
const NO_KEY_TO_SHARE: &str = "You can't change who can see this private channel: you don't have access to it yourself.";

/// Move Private Channel keys from what `before` entitled to what `after` does (CORD-03 §5):
/// the newly entitled get one Direct Invite carrying every key they gained, and a Channel
/// anyone lost is rekeyed without them. The roster this device holds is brought forward
/// first, so the invite and the rekey are built from `after`.
async fn settle_access<T: Transport + ?Sized>(
    transport: &T,
    community: &CommunityV2,
    before: &crate::community::roles::CommunityRoles,
    after: &crate::community::roles::CommunityRoles,
) -> Result<(), String> {
    if after.everyone.is_none() {
        return Ok(());
    }
    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
    let owner_hex = community.owner()?.to_hex();
    let me = me_pk()?;
    {
        // Only what this change touched: anything else the stored roster holds stays, so a
        // short read can't erase what the withholding defence is guarding.
        let mut stored = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
        if before.everyone != after.everyone {
            stored.everyone = after.everyone;
        }
        for o in before.overwrites.iter().filter(|o| !after.overwrites.contains(o)) {
            stored.overwrites.retain(|x| !(x.scope == o.scope && x.target == o.target));
        }
        for o in &after.overwrites {
            if !stored.overwrites.contains(o) {
                stored.overwrites.retain(|x| !(x.scope == o.scope && x.target == o.target));
                stored.overwrites.push(o.clone());
            }
        }
        for (ch, _) in before.syncs.iter().filter(|(c, k)| after.syncs.get(*c) != Some(*k)) {
            stored.syncs.remove(ch);
        }
        for (ch, k) in &after.syncs {
            stored.syncs.insert(ch.clone(), k.clone());
        }
        for r in before.roles.iter().filter(|r| after.role(&r.role_id).is_none()) {
            stored.roles.retain(|x| x.role_id != r.role_id);
        }
        for r in &after.roles {
            match stored.roles.iter_mut().find(|x| x.role_id == r.role_id) {
                Some(slot) => *slot = r.clone(),
                None => stored.roles.push(r.clone()),
            }
        }
        for g in &after.grants {
            if !stored.grants.contains(g) {
                stored.grants.retain(|x| x.member != g.member);
                stored.grants.push(g.clone());
            }
        }
        let at = crate::db::community::get_community_roles_at(&cid_hex).unwrap_or(0);
        if let Err(e) = crate::db::community::set_community_roles(&cid_hex, &stored, at) {
            crate::log_warn!("v2: local roster merge failed (heals on the next control fold): {e}");
        }
    }
    // Before's too: someone only a removed overwrite named still holds what it let them read.
    let mut candidates = access_candidates(community, after)?;
    for pk in access_candidates(community, before)? {
        if !candidates.contains(&pk) {
            candidates.push(pk);
        }
    }
    let mut gained: std::collections::BTreeMap<PublicKey, ()> = Default::default();
    // Readers take a Channel rotation only from its managers (CORD-06): without the
    // standing, the cut waits for one of them rather than forking this device.
    let may_rotate = me.to_hex() == owner_hex || after.is_authorized(&me.to_hex(), Some(&owner_hex), crate::community::roles::Permissions::MANAGE_CHANNELS);
    // Per Channel: who lost it, how many come in without its history, and who reads it whole.
    let mut rotating: Vec<(ChannelId, Vec<PublicKey>, Vec<PublicKey>)> = Vec::new();
    let mut steady: Vec<(ChannelId, Vec<PublicKey>)> = Vec::new();
    for ch in community.channels.iter().filter(|c| c.private && c.key.is_some()) {
        let chan = crate::simd::hex::bytes_to_hex_32(&ch.id.0);
        let (mut lost, mut fresh, mut readers) = (Vec::new(), 0usize, Vec::new());
        for pk in &candidates {
            let hex = pk.to_hex();
            if *pk == me || hex == owner_hex {
                continue;
            }
            let (was, now) = (before.is_entitled(Some(&owner_hex), &hex, &chan, &[], &[]), after.is_entitled(Some(&owner_hex), &hex, &chan, &[], &[]));
            if now && !was {
                // Without history they come in at a fresh epoch, which the rotation below mints.
                if after.reads_history(Some(&owner_hex), &hex, &chan, &[], &[]) {
                    gained.insert(*pk, ());
                    readers.push(*pk);
                } else {
                    fresh += 1;
                }
            } else if was && !now {
                lost.push(*pk);
            }
        }
        // Readers adopt a delivery only from a deliverer their fold entitles.
        if !(me.to_hex() == owner_hex || after.is_entitled(Some(&owner_hex), &me.to_hex(), &chan, &[], &[])) {
            readers.clear();
        }
        if (!lost.is_empty() || fresh > 0) && !may_rotate {
            crate::log_warn!("[v2:access] {} lost and {fresh} gained a channel's View; a channel manager's rotation will settle them", lost.len());
            steady.push((ch.id, readers));
        } else if !lost.is_empty() || fresh > 0 {
            rotating.push((ch.id, lost, readers));
        } else {
            steady.push((ch.id, readers));
        }
    }
    steady.retain(|(_, readers)| !readers.is_empty());
    // A Channel that stays at its epoch is delivered before any other is rotated: its key is one
    // round trip away, and must not wait out a rotation it has no part in.
    deliver_gained(transport, community, &steady).await?;
    let mut moved: Vec<(ChannelId, Vec<PublicKey>)> = Vec::new();
    for (channel, lost, readers) in rotating {
        let held = crate::db::community::load_community_v2(community.id())?.ok_or("v2 community not found")?;
        rekey_channel_excluding(transport, &held, &channel, after, &[], &lost).await?;
        if !readers.is_empty() {
            moved.push((channel, readers));
        }
    }
    // At the epoch each now holds.
    deliver_gained(transport, community, &moved).await?;
    if !gained.is_empty() {
        let held = crate::db::community::load_community_v2(community.id())?.ok_or("v2 community not found")?;
        let signer = crate::signer::active_signer()?;
        for pk in gained.keys() {
            let bundle = bundle_of_with_overlay(&held, BundleAudience::Member(*pk), Some(me), None, None, &[], &[]);
            let wrap = invite::build_direct_invite_signed(&signer, me, pk, &bundle).await.map_err(|e| e.to_string())?;
            transport.publish(&wrap, &held.relays).await?;
            // The planes above already carry the key: the inbox copy only gets it there sooner,
            // and resolving a stranger's inbox relays must not hold up the grant.
            let pk = *pk;
            crate::db::spawn_bound(async move { send_to_inbox(&wrap, &pk).await });
        }
    }
    writing::settle_writers(transport, community, before, after).await
}

/// Deliver each Channel's key, and every past epoch this device reads, to the members who just
/// gained it with its history: on the Channel's access plane, which a member's client sweeps as
/// soon as its roster moves, rather than leaving them to another holder's duty. Every Channel in
/// one wave, so a Role that opens several keeps its member waiting one round trip, not one each.
/// One that fails is logged and left to that duty.
async fn deliver_gained<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, gained: &[(ChannelId, Vec<PublicKey>)]) -> Result<(), String> {
    if gained.is_empty() {
        return Ok(());
    }
    let held = crate::db::community::load_community_v2(community.id())?.ok_or("v2 community not found")?;
    let ledger = crate::db::current_session().scoped::<AccessLedger, std::sync::Mutex<std::collections::HashSet<([u8; 32], u64, [u8; 32])>>>();
    let delivered = in_one_wave(
        gained
            .iter()
            .map(|(channel, readers)| {
                let held = &held;
                async move {
                    deliver_access(transport, held, channel, readers).await?;
                    deliver_history(transport, held, channel, readers).await
                }
            })
            .collect(),
    )
    .await;
    for ((channel, readers), delivered) in gained.iter().zip(delivered) {
        let Some(epoch) = held.channel(channel).map(|c| c.epoch) else { continue };
        match delivered {
            Ok(_) => ledger.lock().unwrap_or_else(|e| e.into_inner()).extend(readers.iter().map(|pk| (channel.0, epoch.0, pk.to_bytes()))),
            Err(e) => crate::log_warn!("[v2:access] delivering a gained channel's key failed (a holder's duty retries): {e}"),
        }
    }
    Ok(())
}

/// A gift wrap to `recipient`'s DM inbox as well: their client reads gift wraps there, and a
/// Community's relays only for its planes.
async fn send_to_inbox(wrap: &Event, recipient: &PublicKey) {
    let Some(client) = crate::state::nostr_client() else { return };
    let targets = crate::inbox_relays::resolve_gift_wrap_targets(&client, recipient).await;
    if let Err(e) = crate::inbox_relays::publish_gift_wrap_to_targets(&client, &targets, wrap).await {
        crate::log_warn!("[v2:access] a Direct Invite didn't reach the recipient's inbox (the community relays carry it): {e}");
    }
    crate::inbox_relays::teardown_gift_wrap_targets(&client, &targets).await;
}

/// A Channel's access plane at the community's root epoch (CORD-03 §5).
fn access_group(community: &CommunityV2, channel: &ChannelId) -> super::derive::GroupKey {
    super::derive::channel_access_group_key(&community.community_root, channel, community.root_epoch)
}

/// Every access delivery for a Channel on its plane, paged as the plane key: the address is
/// root-derived, so any root holder can bury the real deliveries under a single page.
async fn fetch_access_deliveries<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, channel: &ChannelId) -> Result<Vec<rekey::AccessDelivery>, String> {
    fetch_plane_deliveries(transport, community, channel, rekey::RekeyScope::Channel(*channel)).await
}

tokio::task_local! {
    /// The access planes one settling action has read, by address: `None` once the action wrote
    /// to the plane itself, after which every read of it goes to the relays again.
    static ACCESS_READS: std::cell::RefCell<std::collections::HashMap<[u8; 32], Option<std::sync::Arc<Vec<Event>>>>>;
}

/// Run `action` asking the relays for each access plane once, however many kinds of record it
/// takes from one: a plane holds the Channel's keys, its history, its writer keys and their
/// certifiers, and each is read by a step of its own. A plane the action writes to is read
/// afresh from then on, so it never judges on a copy from before its own delivery.
async fn reading_planes_once<F: std::future::Future>(action: F) -> F::Output {
    if ACCESS_READS.try_with(|_| ()).is_ok() {
        return action.await;
    }
    ACCESS_READS.scope(Default::default(), action).await
}

/// Every wrap on an access plane, from this action's earlier read of it when it has one.
async fn access_plane_wraps<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, group: &GroupKey) -> Result<std::sync::Arc<Vec<Event>>, String> {
    let address = group.pk().to_bytes();
    let read = ACCESS_READS.try_with(|reads| reads.borrow().get(&address).cloned()).ok().flatten();
    if let Some(Some(wraps)) = read {
        return Ok(wraps);
    }
    let wraps = std::sync::Arc::new(plane_wraps(transport, community, group).await?);
    if read.is_none() {
        let _ = ACCESS_READS.try_with(|reads| reads.borrow_mut().entry(address).or_insert_with(|| Some(wraps.clone())).is_some());
    }
    Ok(wraps)
}

/// This action is about to write to an access plane: what it read of it before no longer stands.
fn wrote_access_plane(group: &GroupKey) {
    let _ = ACCESS_READS.try_with(|reads| reads.borrow_mut().insert(group.pk().to_bytes(), None));
}

/// The deliveries of `scope`'s keys on a Channel's access plane.
async fn fetch_plane_deliveries<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, channel: &ChannelId, scope: rekey::RekeyScope) -> Result<Vec<rekey::AccessDelivery>, String> {
    let group = access_group(community, channel);
    let wraps = access_plane_wraps(transport, community, &group).await?;
    Ok(wraps
        .iter()
        .filter_map(|w| stream::open_wrap(w, &group).ok().and_then(|o| rekey::parse_access_delivery(&o).ok()))
        .filter(|d| d.scope.id32() == scope.id32())
        .collect())
}

/// Whether `member` holds a blob for `epoch` on the plane from a deliverer `trusted` admits:
/// anyone can put a blob at anyone's locator, so only a delivery a reader would take counts.
fn served_on_plane(deliveries: &[rekey::AccessDelivery], member: &PublicKey, channel: &ChannelId, epoch: Epoch, trusted: &dyn Fn(&PublicKey) -> bool) -> bool {
    served_at(deliveries, member, rekey::RekeyScope::Channel(*channel), epoch, trusted)
}

fn served_at(deliveries: &[rekey::AccessDelivery], member: &PublicKey, scope: rekey::RekeyScope, epoch: Epoch, trusted: &dyn Fn(&PublicKey) -> bool) -> bool {
    deliveries
        .iter()
        .filter(|d| d.epoch == epoch && trusted(&d.deliverer))
        .any(|d| rekey::find_my_blob(&d.blobs, &d.deliverer.to_bytes(), &member.to_bytes(), scope, epoch).is_some())
}

struct MintedRotations;
type MintedMap = std::sync::Mutex<std::collections::HashMap<([u8; 32], u64), std::sync::Arc<Vec<(PublicKey, Vec<rekey::RekeyBlob>)>>>>;

/// The complete rotations that minted a Channel's `epoch`, each as its rotator and blobs.
/// A complete rotation never changes, so a found set is held for the session.
async fn minting_rotations<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, channel: &ChannelId, epoch: Epoch) -> Result<std::sync::Arc<Vec<(PublicKey, Vec<rekey::RekeyBlob>)>>, String> {
    let cache = crate::db::current_session().scoped::<MintedRotations, MintedMap>();
    if let Some(held) = cache.lock().unwrap_or_else(|e| e.into_inner()).get(&(channel.0, epoch.0)) {
        return Ok(held.clone());
    }
    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
    let mut out = Vec::new();
    for root in channel_rekey_addressing_roots(community.community_root, &cid_hex) {
        let group = channel_rekey_group_key(&root, channel, epoch);
        for r in rekey::collect_rotations(&fetch_rekey_chunks(transport, &community, &group).await?) {
            if r.is_complete() && r.new_epoch == epoch && matches!(r.scope, rekey::RekeyScope::Channel(c) if c.0 == channel.0) {
                out.push((r.rotator, r.blobs));
            }
        }
    }
    let out = std::sync::Arc::new(out);
    if !out.is_empty() {
        cache.lock().unwrap_or_else(|e| e.into_inner()).insert((channel.0, epoch.0), out.clone());
    }
    Ok(out)
}

/// Whether an authorized one of `rotations` carried `member` a blob.
fn rotation_carries(rotations: &[(PublicKey, Vec<rekey::RekeyBlob>)], authorized: &dyn Fn(&PublicKey) -> bool, member: &PublicKey, channel: &ChannelId, epoch: Epoch) -> bool {
    let scope = rekey::RekeyScope::Channel(*channel);
    rotations
        .iter()
        .filter(|(rotator, _)| authorized(rotator))
        .any(|(rotator, blobs)| rekey::find_my_blob(blobs, &rotator.to_bytes(), &member.to_bytes(), scope, epoch).is_some())
}

/// Deliver the key this device holds for `channel` to `recipients` on its access plane.
async fn deliver_access<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, channel: &ChannelId, recipients: &[PublicKey]) -> Result<(), String> {
    let ch = community.channel(channel).ok_or("no such channel")?;
    let key = ch.key.ok_or("this device doesn't hold that channel's key")?;
    deliver_on_plane(transport, community, channel, rekey::RekeyScope::Channel(*channel), ch.epoch, None, &key, recipients).await
}

/// Deliver `key`, `scope`'s at `epoch`, to `recipients` on `channel`'s access plane; a writer key
/// names the address it derives to.
#[allow(clippy::too_many_arguments)]
async fn deliver_on_plane<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, channel: &ChannelId, scope: rekey::RekeyScope, epoch: Epoch, writer: Option<[u8; 32]>, key: &[u8; 32], recipients: &[PublicKey]) -> Result<(), String> {
    deliver_certified(transport, community, channel, scope, epoch, writer, key, recipients, &Default::default()).await
}

/// [`deliver_on_plane`], each recipient's writer certificate riding the event that carries its blob.
#[allow(clippy::too_many_arguments)]
async fn deliver_certified<T: Transport + ?Sized>(
    transport: &T,
    community: &CommunityV2,
    channel: &ChannelId,
    scope: rekey::RekeyScope,
    epoch: Epoch,
    writer: Option<[u8; 32]>,
    key: &[u8; 32],
    recipients: &[PublicKey],
    certs: &std::collections::HashMap<PublicKey, chat::WriterCert>,
) -> Result<(), String> {
    for wrap in build_deliveries(community, channel, scope, epoch, writer, key, recipients, certs, false).await? {
        transport.publish(&wrap, &community.relays).await?;
    }
    Ok(())
}

/// The sealed events of a delivery, built whole before any is sent: every blob is a signer
/// round trip. `mint` marks each as a part of a writer epoch's minting delivery.
#[allow(clippy::too_many_arguments)]
async fn build_deliveries(
    community: &CommunityV2,
    channel: &ChannelId,
    scope: rekey::RekeyScope,
    epoch: Epoch,
    writer: Option<[u8; 32]>,
    key: &[u8; 32],
    recipients: &[PublicKey],
    certs: &std::collections::HashMap<PublicKey, chat::WriterCert>,
    mint: bool,
) -> Result<Vec<Event>, String> {
    use nostr_sdk::prelude::AsyncGetPublicKey;
    let signer = crate::signer::active_signer()?;
    let me = me_pk()?;
    // The signer is resolved process-wide; never let another account's sign for this one.
    if signer.get_public_key_async().await.map_err(|e| e.to_string())? != me {
        return Err("the active signer isn't this account".to_string());
    }
    let group = access_group(community, channel);
    wrote_access_plane(&group);
    let mut blobs = Vec::with_capacity(recipients.len());
    for r in recipients {
        blobs.push(rekey::build_blob(&signer, &me.to_bytes(), r, scope, epoch, key).await.map_err(|e| e.to_string())?);
    }
    let at = now_ms() / 1000;
    let per_event = if certs.is_empty() { rekey::MAX_REKEY_BLOBS_PER_EVENT } else { rekey::MAX_CERTIFIED_BLOBS_PER_EVENT };
    let parts = blobs.len().div_ceil(per_event).max(1);
    let mut out = Vec::with_capacity(parts);
    for (i, (part, who)) in blobs.chunks(per_event).zip(recipients.chunks(per_event)).enumerate() {
        let mut whole: Vec<([u8; 32], [u8; 64])> = Vec::new();
        let mut scoped: Vec<([u8; 32], [u8; 64], u64)> = Vec::new();
        for r in who {
            match certs.get(r) {
                Some(chat::WriterCert::Full(c)) => whole.push((r.to_bytes(), *c)),
                Some(chat::WriterCert::Scoped(c, rights)) => scoped.push((r.to_bytes(), *c, *rights)),
                None => {}
            }
        }
        let rumor = rekey::build_access_rumor_scoped(me, scope, epoch, writer, part, &whole, &scoped, at).map_err(|e| e.to_string())?;
        let rumor = if mint { rekey::as_mint_part(rumor, i + 1, parts) } else { rumor };
        let (wrap, _) = stream::seal_and_wrap_signed(&signer, me, &rumor, stream::SealForm::Encrypted, &group, stream::KIND_WRAP, Timestamp::from_secs(at), &[])
            .await
            .map_err(|e| e.to_string())?;
        out.push(wrap);
    }
    Ok(out)
}

/// Deliver every past epoch of `channel` this device can read, read-only, to `recipients`:
/// one history event per epoch on the access plane (CORD-03 §5). Returns the epochs sent.
async fn deliver_history<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, channel: &ChannelId, recipients: &[PublicKey]) -> Result<usize, String> {
    use nostr_sdk::prelude::AsyncGetPublicKey;
    let ch = community.channel(channel).ok_or("no such channel")?;
    let (cid_hex, ch_hex) = (crate::simd::hex::bytes_to_hex_32(&community.id().0), crate::simd::hex::bytes_to_hex_32(&channel.0));
    let mut views: std::collections::BTreeMap<u64, rekey::HistoryView> = crate::db::community::history_views(&cid_hex, &ch_hex)?
        .into_iter()
        .filter(|(e, _)| *e < ch.epoch)
        .map(|(e, v)| (e.0, v))
        .collect();
    for (e, secret) in crate::db::community::held_epoch_keys(&cid_hex, &ch_hex)? {
        if e < ch.epoch && secret != community.community_root {
            views.insert(e.0, rekey::HistoryView::of(&channel_group_key(&secret, channel, e)));
        }
    }
    if views.is_empty() || recipients.is_empty() {
        return Ok(0);
    }
    let signer = crate::signer::active_signer()?;
    let me = me_pk()?;
    if signer.get_public_key_async().await.map_err(|e| e.to_string())? != me {
        return Err("the active signer isn't this account".to_string());
    }
    let group = access_group(community, channel);
    wrote_access_plane(&group);
    let at = now_ms() / 1000;
    for (epoch, view) in &views {
        let epoch = Epoch(*epoch);
        let mut blobs = Vec::with_capacity(recipients.len());
        for r in recipients {
            blobs.push(rekey::build_history_blob(&signer, &me.to_bytes(), r, channel, epoch, view).await.map_err(|e| e.to_string())?);
        }
        for part in blobs.chunks(rekey::MAX_WIDE_BLOBS_PER_EVENT) {
            let rumor = rekey::build_history_rumor(me, channel, epoch, part, at).map_err(|e| e.to_string())?;
            let (wrap, _) = stream::seal_and_wrap_signed(&signer, me, &rumor, stream::SealForm::Encrypted, &group, stream::KIND_WRAP, Timestamp::from_secs(at), &[])
                .await
                .map_err(|e| e.to_string())?;
            transport.publish(&wrap, &community.relays).await?;
        }
    }
    Ok(views.len())
}

/// Every history delivery for `channel` on its access plane.
async fn fetch_history_deliveries<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, channel: &ChannelId) -> Result<Vec<rekey::HistoryDelivery>, String> {
    let group = access_group(community, channel);
    let wraps = access_plane_wraps(transport, community, &group).await?;
    Ok(wraps.iter().filter_map(|w| stream::open_wrap(w, &group).ok().and_then(|o| rekey::parse_history_delivery(&o, channel).ok())).collect())
}

struct OpenedHistory;
struct HistoryCollectClock;

/// How often a member re-reads history deliveries when nothing moved.
const HISTORY_COLLECT_PERIOD_MS: u64 = 10 * 60 * 1000;

/// Whether to read history deliveries for a community now: when the roster moved or a key was
/// just adopted, else once per period. Marks it read.
pub(crate) fn history_collect_due(id: &crate::community::CommunityId, moved: bool) -> bool {
    let clock = crate::db::current_session().scoped::<HistoryCollectClock, std::sync::Mutex<std::collections::HashMap<[u8; 32], u64>>>();
    let mut last = clock.lock().unwrap_or_else(|e| e.into_inner());
    let now = now_ms();
    let due = moved || last.get(&id.0).is_none_or(|t| now.saturating_sub(*t) > HISTORY_COLLECT_PERIOD_MS);
    if due {
        last.insert(id.0, now);
    }
    due
}

/// Read Message History, member side (CORD-03 §5): for each private channel this member reads
/// with READ_MESSAGE_HISTORY, archive every past epoch it lacks that a deliverer the channel
/// lets in sent it read-only. Returns how many epochs were archived.
pub async fn collect_history<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> Result<usize, String> {
    let mut archived = 0;
    for (_, n) in collect_history_rooms(transport, community).await? {
        archived += n;
    }
    Ok(archived)
}

/// [`collect_history`], by Channel: each that took a past epoch, and how many. What those epochs
/// hold is read by nothing yet.
pub async fn collect_history_rooms<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> Result<Vec<(ChannelId, usize)>, String> {
    use crate::community::roles::Permissions;
    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
    let roster = crate::db::community::get_community_roles(&cid_hex)?;
    if roster.everyone.is_none() {
        return Ok(Vec::new());
    }
    let owner_hex = community.owner()?.to_hex();
    let banned = crate::db::community::get_community_banlist(&cid_hex).unwrap_or_default();
    let me = me_pk()?;
    let signer = crate::signer::active_signer()?;
    let opened = crate::db::current_session().scoped::<OpenedHistory, Opened>();
    let mut archived: Vec<(ChannelId, usize)> = Vec::new();
    let readable: Vec<_> = community
        .channels
        .iter()
        .filter(|c| c.private && c.key.is_some())
        .filter(|ch| roster.channel_permissions(Some(&owner_hex), &me.to_hex(), &crate::simd::hex::bytes_to_hex_32(&ch.id.0), true).contains(Permissions::READ_MESSAGE_HISTORY))
        .collect();
    let reads = in_one_wave(readable.iter().map(|ch| fetch_history_deliveries(transport, community, &ch.id)).collect()).await;
    let mut unread = None;
    for (ch, read) in readable.into_iter().zip(reads) {
        let chan = crate::simd::hex::bytes_to_hex_32(&ch.id.0);
        let read = match read {
            Ok(read) => read,
            Err(e) => {
                unread.get_or_insert(e);
                continue;
            }
        };
        let mut held: std::collections::HashSet<u64> = crate::db::community::held_epoch_keys(&cid_hex, &chan)?.into_iter().map(|(e, _)| e.0).collect();
        held.extend(crate::db::community::history_views(&cid_hex, &chan)?.into_iter().map(|(e, _)| e.0));
        held.insert(ch.epoch.0);
        for d in read {
            let h = d.deliverer.to_hex();
            let trusted = h == owner_hex || (!banned.contains(&h) && roster.is_entitled(Some(&owner_hex), &h, &chan, &[], &[]));
            if !trusted || d.epoch >= ch.epoch || held.contains(&d.epoch.0) {
                continue;
            }
            let Some(blob) = d.blobs.iter().find(|b| b.locator == rekey::history_locator(&d.deliverer.to_bytes(), &me.to_bytes(), &ch.id, d.epoch)) else { continue };
            if !opened.lock().unwrap_or_else(|e| e.into_inner()).insert((ch.id.0, d.deliverer.to_bytes(), me.to_bytes(), d.epoch.0)) {
                continue;
            }
            if let Ok(view) = rekey::open_history_blob(&signer, &d.deliverer, &ch.id, d.epoch, blob).await {
                crate::db::community::store_history_view(&cid_hex, &chan, d.epoch.0, &view)?;
                held.insert(d.epoch.0);
                match archived.last_mut() {
                    Some((last, n)) if *last == ch.id => *n += 1,
                    _ => archived.push((ch.id, 1)),
                }
            }
        }
    }
    match unread {
        Some(e) => Err(e),
        None => Ok(archived),
    }
}

struct AccessDutyClock;

/// How often a holder re-checks its channels' access planes when nothing in the roster moved.
const ACCESS_DUTY_PERIOD_MS: u64 = 10 * 60 * 1000;

/// Whether the access duty should run for a community now: whenever the roster moved, else
/// once per period. Marks it run.
pub(crate) fn access_duty_due(id: &crate::community::CommunityId, roster_moved: bool) -> bool {
    let clock = crate::db::current_session().scoped::<AccessDutyClock, std::sync::Mutex<std::collections::HashMap<[u8; 32], u64>>>();
    let mut last = clock.lock().unwrap_or_else(|e| e.into_inner());
    let now = now_ms();
    let due = roster_moved || last.get(&id.0).is_none_or(|t| now.saturating_sub(*t) > ACCESS_DUTY_PERIOD_MS);
    if due {
        last.insert(id.0, now);
    }
    due
}

struct AccessLedger;
struct OpenedDeliveries;

type Opened = std::sync::Mutex<std::collections::HashSet<([u8; 32], [u8; 32], [u8; 32], u64)>>;

/// Drop this session's marks of key, history and writer deliveries already opened.
fn forget_opened_deliveries() {
    let session = crate::db::current_session();
    *session.scoped::<OpenedDeliveries, Opened>().lock().unwrap_or_else(|e| e.into_inner()) = Default::default();
    *session.scoped::<OpenedHistory, Opened>().lock().unwrap_or_else(|e| e.into_inner()) = Default::default();
    writing::forget_opened_writer_blobs();
}
struct AccessCollectClock;

/// How often a keyless member re-reads its access planes when nothing in the roster moved.
const ACCESS_COLLECT_PERIOD_MS: u64 = 60 * 1000;

fn access_collect_clock() -> std::sync::Arc<std::sync::Mutex<std::collections::HashMap<[u8; 32], u64>>> {
    crate::db::current_session().scoped::<AccessCollectClock, std::sync::Mutex<std::collections::HashMap<[u8; 32], u64>>>()
}

/// Make the next follow pass run the access duty.
pub(crate) fn access_duty_now(id: &crate::community::CommunityId) {
    crate::db::current_session().scoped::<AccessDutyClock, std::sync::Mutex<std::collections::HashMap<[u8; 32], u64>>>().lock().unwrap_or_else(|e| e.into_inner()).remove(&id.0);
}

/// Let the next follow read a community's access planes whatever the period says.
pub(crate) fn access_collect_now(id: &crate::community::CommunityId) {
    access_collect_clock().lock().unwrap_or_else(|e| e.into_inner()).remove(&id.0);
}

/// Whether to read the access planes for a community now: whenever the roster moved, else once
/// per period. Marks it read.
pub(crate) fn access_collect_due(id: &crate::community::CommunityId, roster_moved: bool) -> bool {
    let clock = access_collect_clock();
    let mut last = clock.lock().unwrap_or_else(|e| e.into_inner());
    let now = now_ms();
    let due = roster_moved || last.get(&id.0).is_none_or(|t| now.saturating_sub(*t) > ACCESS_COLLECT_PERIOD_MS);
    if due {
        last.insert(id.0, now);
    }
    due
}

/// Of `out`, whom a whole read of the Roster taken now still leaves out of `chan`. A read that
/// can't be taken whole cuts nobody: the duty runs again.
async fn still_left_out<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, chan: &str, owner_hex: &str, out: Vec<PublicKey>) -> Vec<PublicKey> {
    let now = fetch_authority(transport, community).await;
    if !now.everyone_served || now.gapped {
        return Vec::new();
    }
    out.into_iter().filter(|pk| now.banned.contains(&pk.to_hex()) || !now.roles.is_entitled(Some(owner_hex), &pk.to_hex(), chan, &[], &[])).collect()
}

/// What one run of the access duty did.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct AccessDuty {
    /// Keys delivered on access planes.
    pub delivered: usize,
    /// Holders cut by a rotation because the channel no longer lets them in.
    pub cut: usize,
    /// What the writer duty did for restricted Channels (CORD-03 §1).
    pub writers: WriterDuty,
    /// Private Channels whose metadata was sealed under their current key (CORD-03 §2).
    pub resealed: usize,
    /// Public Channels whose earlier planes this device published for every member (CORD-03 §2).
    pub history: usize,
}

/// The holder's duty (CORD-03 §5): for every private Channel this device holds and may read,
/// deliver the key to each entitled member nobody has served at its epoch: not a reader-trusted
/// delivery on the plane, not the rotation that minted it, and not this device before. A member
/// who held the previous epoch and that rotation left out was cut, whatever the roster says.
/// As the revocation backstop, a manager who outranks a holder the channel no longer lets in
/// rotates them out.
pub async fn access_duty<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> Result<AccessDuty, String> {
    reading_planes_once(access_duty_once(transport, community)).await
}

async fn access_duty_once<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> Result<AccessDuty, String> {
    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
    if crate::db::community::get_community_roles(&cid_hex)?.everyone.is_none() {
        return Ok(AccessDuty::default());
    }
    // Judged on a whole read, never the stored roster: a stale entitlement would hand a new
    // epoch's key to someone its rotation just cut.
    let fresh = fetch_authority(transport, community).await;
    if !fresh.everyone_served || fresh.gapped {
        return Err("the roster couldn't be read whole; no key was delivered".to_string());
    }
    let (roster, banned) = (fresh.roles, fresh.banned);
    let owner_hex = community.owner()?.to_hex();
    let me = me_pk()?;
    let candidates = access_candidates(community, &roster)?;
    let rotator_ok = |r: &PublicKey| rotates_channels(&roster, &owner_hex, banned.iter(), &r.to_hex());
    let ledger = crate::db::current_session().scoped::<AccessLedger, std::sync::Mutex<std::collections::HashSet<([u8; 32], u64, [u8; 32])>>>();
    let me_hex = me.to_hex();
    let may_rotate = me_hex == owner_hex || roster.is_authorized(&me_hex, Some(&owner_hex), crate::community::roles::Permissions::MANAGE_CHANNELS);
    let banned_pks: Vec<PublicKey> = banned.iter().filter_map(|h| PublicKey::from_hex(h).ok()).collect();
    let mut done = AccessDuty::default();
    // One half's failure never stops the other: the writer duty runs whatever the keys did.
    let keys: Result<(), String> = async {
        for ch in community.channels.iter().filter(|c| c.private && c.key.is_some()) {
            let chan = crate::simd::hex::bytes_to_hex_32(&ch.id.0);
            let entitled_here = |pk: &PublicKey| pk.to_hex() == owner_hex || (!banned.contains(&pk.to_hex()) && roster.is_entitled(Some(&owner_hex), &pk.to_hex(), &chan, &[], &[]));
            // Readers adopt only from a deliverer their fold entitles.
            if !entitled_here(&me) {
                continue;
            }
            let epoch = ch.epoch;
            let held = ledger.lock().unwrap_or_else(|e| e.into_inner()).clone();
            let entitled: Vec<PublicKey> = candidates
                .iter()
                .filter(|pk| **pk != me && entitled_here(pk) && !held.contains(&(ch.id.0, epoch.0, pk.to_bytes())))
                .copied()
                .collect();
            if entitled.is_empty() && !may_rotate {
                continue;
            }
            let deliveries = fetch_access_deliveries(transport, community, &ch.id).await?;
            let minted = minting_rotations(transport, community, &ch.id, epoch).await?;
            let prior = match epoch.0.checked_sub(1) {
                Some(p) if p > 0 => minting_rotations(transport, community, &ch.id, Epoch(p)).await?,
                _ => Default::default(),
            };
            let prev = Epoch(epoch.0.saturating_sub(1));
            if may_rotate {
                let out: Vec<PublicKey> = candidates
                    .iter()
                    .chain(banned_pks.iter())
                    .filter(|pk| **pk != me && !entitled_here(pk))
                    .filter(|pk| rotation_carries(&minted, &rotator_ok, pk, &ch.id, epoch) || served_on_plane(&deliveries, pk, &ch.id, epoch, &entitled_here))
                    .filter(|pk| me_hex == owner_hex || roster.can_act_on_member(&me_hex, Some(&owner_hex), &pk.to_hex(), crate::community::roles::Permissions::MANAGE_CHANNELS))
                    .copied()
                    .collect::<std::collections::BTreeSet<_>>()
                    .into_iter()
                    .collect();
                // The Roster was read before the plane: someone let in between the two reads holds a
                // delivery the read can't account for. Cut only who a fresh read still leaves out.
                let out = match out.is_empty() {
                    true => out,
                    false => still_left_out(transport, community, &chan, &owner_hex, out).await,
                };
                if !out.is_empty() {
                    if rekey_channel_at(transport, community, &ch.id, &rotation_roster(roster.clone(), &cid_hex), &[], &out, Some(epoch)).await? {
                        done.cut += out.len();
                    }
                    // Whoever is owed this channel is owed its next epoch now; the next run serves them.
                    continue;
                }
            }
            let unserved: Vec<PublicKey> = entitled
                .into_iter()
                .filter(|pk| {
                    let carried = rotation_carries(&minted, &rotator_ok, pk, &ch.id, epoch);
                    let cut = !carried
                        && minted.iter().any(|(r, _)| rotator_ok(r))
                        && (rotation_carries(&prior, &rotator_ok, pk, &ch.id, prev) || served_on_plane(&deliveries, pk, &ch.id, prev, &entitled_here));
                    !carried && !cut && !served_on_plane(&deliveries, pk, &ch.id, epoch, &entitled_here)
                })
                .collect();
            // With Read Message History they take this epoch and every past one this device can
            // read; without it, only a fresh epoch, so history starts where access did.
            let (readers, fresh): (Vec<PublicKey>, Vec<PublicKey>) = unserved.into_iter().partition(|pk| roster.reads_history(Some(&owner_hex), &pk.to_hex(), &chan, &[], &[]));
            if !readers.is_empty() {
                deliver_access(transport, community, &ch.id, &readers).await?;
                deliver_history(transport, community, &ch.id, &readers).await?;
                ledger.lock().unwrap_or_else(|e| e.into_inner()).extend(readers.iter().map(|pk| (ch.id.0, epoch.0, pk.to_bytes())));
                done.delivered += readers.len();
            }
            if !fresh.is_empty() && may_rotate && rekey_channel_at(transport, community, &ch.id, &rotation_roster(roster.clone(), &cid_hex), &[], &[], Some(epoch)).await? {
                done.delivered += fresh.len();
            }
        }
        Ok(())
    }
    .await;
    let writers = writing::writer_duty(transport, community, &roster, &banned).await;
    if may_rotate {
        done.resealed = reseal_backstop(transport, community, &roster).await;
        done.history = history_backstop(transport, community, &roster).await;
    }
    done.writers = writers?;
    keys.map(|_| done)
}

/// Fetch the keys delivered to me for every private Channel I'm entitled to but can't read,
/// and park them for the vend judge to adopt (CORD-03 §5). Returns how many were parked.
pub async fn collect_access<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> Result<usize, String> {
    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
    let roster = crate::db::community::get_community_roles(&cid_hex)?;
    if roster.everyone.is_none() {
        return Ok(0);
    }
    let owner_hex = community.owner()?.to_hex();
    let banned = crate::db::community::get_community_banlist(&cid_hex).unwrap_or_default();
    let me = me_pk()?;
    let signer = crate::signer::active_signer()?;
    let opened = crate::db::current_session().scoped::<OpenedDeliveries, Opened>();
    let mut parked = 0;
    let owed: Vec<_> = community
        .channels
        .iter()
        .filter(|c| c.private && c.key.is_none())
        .filter(|ch| roster.is_entitled(Some(&owner_hex), &me.to_hex(), &crate::simd::hex::bytes_to_hex_32(&ch.id.0), &[], &[]))
        .collect();
    // One wave for every plane: a member let into several channels waits one round trip, not
    // one each. A plane that can't be read keeps nobody from the others.
    let reads = in_one_wave(owed.iter().map(|ch| fetch_access_deliveries(transport, community, &ch.id)).collect()).await;
    let mut unread = None;
    for (ch, read) in owed.into_iter().zip(reads) {
        let chan = crate::simd::hex::bytes_to_hex_32(&ch.id.0);
        let read = match read {
            Ok(read) => read,
            Err(e) => {
                unread.get_or_insert(e);
                continue;
            }
        };
        let scope = rekey::RekeyScope::Channel(ch.id);
        // Only deliverers the channel lets in, and only an epoch the keyless walk has reached
        // or its next: a keyless channel seats whatever it adopts first, so neither a stale key
        // nor one claimed far ahead may ever be on offer.
        let window = ch.epoch.0..=ch.epoch.0.saturating_add(1);
        let deliveries: Vec<rekey::AccessDelivery> = read
            .into_iter()
            .filter(|d| window.contains(&d.epoch.0))
            .filter(|d| {
                // A manager counts: the creator rule that may let them in is sealed from a keyless reader.
                let h = d.deliverer.to_hex();
                h == owner_hex
                    || (!banned.contains(&h)
                        && (roster.is_entitled(Some(&owner_hex), &h, &chan, &[], &[]) || roster.is_authorized(&h, Some(&owner_hex), crate::community::roles::Permissions::MANAGE_CHANNELS)))
            })
            .collect();
        let Some(newest) = deliveries.iter().map(|d| d.epoch).max() else { continue };
        for d in deliveries.iter().filter(|d| d.epoch == newest) {
            let mine: Vec<&rekey::RekeyBlob> = rekey::find_my_blobs(&d.blobs, &d.deliverer.to_bytes(), &me.to_bytes(), scope, d.epoch).collect();
            // Opened once a session: parking again would trim other candidates out of the cap.
            if mine.is_empty() || !opened.lock().unwrap_or_else(|e| e.into_inner()).insert((ch.id.0, d.deliverer.to_bytes(), me.to_bytes(), d.epoch.0)) {
                continue;
            }
            for blob in mine {
                if let Ok(key) = rekey::open_blob(&signer, &d.deliverer, scope, d.epoch, blob).await {
                    crate::db::community::park_channel_key(&cid_hex, &chan, d.epoch.0, &key, &d.deliverer.to_hex())?;
                    parked += 1;
                    break;
                }
            }
        }
    }
    match unread {
        Some(e) => Err(e),
        None => Ok(parked),
    }
}

/// Run `reads` together, a few at a time, and hand back what each came to in the order given.
async fn in_one_wave<F: std::future::Future>(reads: Vec<F>) -> Vec<F::Output> {
    use futures_util::stream::StreamExt;
    futures_util::stream::iter(reads).buffered(CHANNEL_FAN_CONCURRENCY).collect().await
}

/// Whether `member` holds any Role here by the stored Roster.
pub(crate) fn holds_grant(community: &CommunityV2, member: &PublicKey) -> bool {
    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
    let hex = member.to_hex();
    crate::db::community::get_community_roles(&cid_hex).is_ok_and(|r| r.grants.iter().any(|g| g.member == hex && !g.role_ids.is_empty()))
}

/// Whether the stored Roster still owes this member a key someone else must deliver: a Private
/// Channel's, or a restricted Channel's writer key.
pub(crate) fn owed_keys(community: &CommunityV2) -> bool {
    owed_channel_keys(community) || writing::owed_writer_keys(community)
}

/// Whether a restricted Channel's writer key, certificate or certifier is still owed to this member.
pub(crate) fn owed_writer_keys(community: &CommunityV2) -> bool {
    writing::owed_writer_keys(community)
}

/// Whether the stored Roster lets this member into a Private Channel it holds no key for, with
/// its history: the key is then delivered on the access plane. Without history it comes in the
/// rotation that mints the member a fresh epoch, which the rekey walk takes.
pub(crate) fn owed_channel_keys(community: &CommunityV2) -> bool {
    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
    let (Ok(roster), Ok(owner), Ok(me)) = (crate::db::community::get_community_roles(&cid_hex), community.owner(), me_pk()) else { return false };
    if roster.everyone.is_none() {
        return false;
    }
    let (owner_hex, me_hex) = (owner.to_hex(), me.to_hex());
    community
        .channels
        .iter()
        .filter(|c| c.private && c.key.is_none())
        .map(|ch| crate::simd::hex::bytes_to_hex_32(&ch.id.0))
        .any(|chan| roster.is_entitled(Some(&owner_hex), &me_hex, &chan, &[], &[]) && roster.reads_history(Some(&owner_hex), &me_hex, &chan, &[], &[]))
}

/// Everyone a Private Channel's key could be owed to: every Grant holder, every member an
/// overwrite names, and every member this device knows.
fn access_candidates(community: &CommunityV2, roster: &crate::community::roles::CommunityRoles) -> Result<Vec<PublicKey>, String> {
    use crate::community::roles::OverwriteTarget;
    // A memberlist we can't read would leave roleless entitled members off a rekey.
    let mut out: std::collections::BTreeSet<PublicKey> = stored_memberlist(community)?.into_iter().collect();
    out.extend(roster.grants.iter().filter_map(|g| PublicKey::from_hex(&g.member).ok()));
    out.extend(roster.overwrites.iter().filter_map(|o| match &o.target {
        OverwriteTarget::Member(m) => PublicKey::from_hex(m).ok(),
        _ => None,
    }));
    let banned = crate::db::community::get_community_banlist(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap_or_default();
    Ok(out.into_iter().filter(|pk| !banned.contains(&pk.to_hex())).collect())
}

/// Move a Community to Roles v2 (CORD-04 §2), owner only: each legacy Role is carried
/// across in the same order, names, colours and bits, continuing its own chain so its
/// Grants keep resolving, then `@everyone` is published, which is the switch itself.
pub async fn activate_roles_v2<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, everyone: u64) -> Result<usize, String> {
    crate::db::scoped(async move {
        if me_pk()? != community.owner()? {
            return Err("only the owner moves a community to the new roles".to_string());
        }
        let view = fetch_authority(transport, community).await;
        if view.activated {
            return Err("this community already uses the new roles".to_string());
        }
        // The switch lists every Channel that stands; one it can't list would vanish for joiners.
        let community = &follow_fresh(transport, community.id()).await?.1;
        if community.channels.len() > super::roles::MAX_LEGACY_CHANNELS {
            return Err(format!("a community moves to the new roles with at most {} channels", super::roles::MAX_LEGACY_CHANNELS));
        }
        let mut legacy: Vec<crate::community::roles::Role> = view.roles.roles.clone();
        legacy.sort_by(|a, b| a.position.cmp(&b.position).then_with(|| a.role_id.cmp(&b.role_id)));
        let mut last: Option<String> = None;
        let mut prev_position: Option<u32> = None;
        for role in &legacy {
            require_role_head(&view, &role.role_id)?;
            // Legacy peers stay peers.
            let rank = match (&last, prev_position) {
                (Some(k), Some(p)) if p == role.position => k.clone(),
                _ => crate::community::rank::between(last.as_deref(), None).ok_or("too many roles to carry across")?,
            };
            let mut next = role.clone();
            next.rank = Some(rank.clone());
            next.scope = crate::community::roles::RoleScope::Server;
            // A managing Role predates the channel bits; it keeps managing channel access.
            if next.permissions.contains(crate::community::roles::Permissions::MANAGE_ROLES) {
                next.permissions = crate::community::roles::Permissions(next.permissions.0 | super::roles::EVERYONE_DEFAULT);
            }
            // The legacy member list set admins apart; they stay apart.
            next.display |= role.permissions.is_management();
            set_role_v2(transport, community, &next).await?;
            last = Some(rank);
            prev_position = Some(role.position);
        }
        // A channel access role becomes a Role its private Channel lets through, which is
        // closed to everyone else by default. Who holds the key is unchanged.
        use crate::community::roles::{Overwrite, OverwriteTarget, Permissions, RoleScope};
        let view_bit = Permissions(Permissions::VIEW_CHANNEL);
        let mut scoped: std::collections::BTreeMap<String, Vec<String>> = Default::default();
        for role in &legacy {
            if let RoleScope::Channel(c) = &role.scope {
                scoped.entry(c.to_ascii_lowercase()).or_default().push(role.role_id.clone());
            }
        }
        for (chan, role_ids) in &scoped {
            let Some(scope) = crate::simd::hex::hex_to_bytes_32_checked(chan) else { continue };
            let targets = role_ids.iter().map(|id| (OverwriteTarget::Role(id.clone()), view_bit, Permissions(0)));
            for (target, allow, deny) in targets {
                let bytes = super::roles::overwrite_target_bytes(community.id(), &target).ok_or("malformed target")?;
                let o = Overwrite { scope: chan.clone(), target, allow, deny };
                publish_control_edition(transport, community, vsk::CHANNEL_ACL, &super::derive::acl_locator(community.id(), &scope, &bytes), &super::roles::overwrite_content_json(&o)).await?;
            }
        }
        let eid = super::derive::everyone_locator(community.id());
        let standing: std::collections::BTreeSet<String> = community.channels.iter().map(|c| crate::simd::hex::bytes_to_hex_32(&c.id.0)).collect();
        publish_control_edition(transport, community, vsk::ROLE_V2, &eid, &super::roles::everyone_content_json_with(everyone, Some(&standing))).await?;
        Ok(legacy.len())
    })
    .await
}

/// The heads a Tenure seals for a member, in the order a budget keeps them: their deletions,
/// which are terminal, then their authority heads, then the rest of what they decided.
fn seal_order(authority: &[FoldedHead], control: &[FoldedHead], theirs: impl Fn(&FoldedHead) -> bool, deletes: impl Fn(&FoldedHead) -> bool) -> Vec<[u8; 32]> {
    let mut out: Vec<[u8; 32]> = Vec::new();
    let ordered = control
        .iter()
        .filter(|h| theirs(h) && deletes(h))
        .chain(authority.iter().filter(|h| theirs(h)))
        .chain(control.iter().filter(|h| theirs(h) && !deletes(h)));
    for h in ordered {
        if !out.contains(&h.self_hash) {
            out.push(h.self_hash);
        }
    }
    out
}

/// How a reduction treats a member whose standing its writer can't seal whole.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum Seal {
    /// Refuse the reduction: a role edit waits for someone who holds the member's bits.
    Strict,
    /// Seal what the writer can and go ahead: a removal is never held hostage.
    BestEffort,
}

/// Before a reduction, publish each member's Tenure sealing their current heads at the
/// standing they hold now (CORD-04 §9), so what they decided outlives the change.
async fn seal_standing<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, members: &[PublicKey], mode: Seal) -> Result<(), String> {
    // The owner's Roles are display alone, so no Tenure names the owner (CORD-04 §3).
    let owner = community.owner().ok();
    let members: Vec<PublicKey> = members.iter().filter(|m| Some(**m) != owner).copied().collect();
    if members.is_empty() {
        return Ok(());
    }
    let members = members.as_slice();
    crate::db::scoped(async move {
        let cid = community.id();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&cid.0);
        let floors: Floors = crate::db::community::get_all_edition_heads_full(&cid_hex)?
            .into_iter()
            .filter(|(_, f)| f.0 == community.root_epoch.0)
            .map(|(entity, f)| (entity, (f.1, f.2, f.3, f.4, f.5)))
            .collect();
        let Some(editions) = fetch_control_plane_whole(transport, community).await else {
            // Nothing to seal before Roles v2, and a removal never waits on a read.
            let everyone_hex = crate::simd::hex::bytes_to_hex_32(&super::derive::everyone_locator(cid));
            if floors.contains_key(&everyone_hex) && mode == Seal::Strict {
                return Err("the control plane couldn't be read whole; nothing was changed".to_string());
            }
            if floors.contains_key(&everyone_hex) {
                crate::log_warn!("[v2:tenure] the control plane couldn't be read whole; removing without sealing");
            }
            return Ok(());
        };
        let authority = fold_authority(community, &editions, &floors);
        if !authority.activated {
            return Ok(());
        }
        let control = apply_control_fold(community, &editions, &floors, &authority);
        let me = me_pk()?;
        let me_hex = me.to_hex();
        let is_owner = me == community.owner()?;
        for member in members {
            let member_hex = member.to_hex();
            // Then authority heads: a budget cut drops a channel edit before a Grant. A Tenure
            // of theirs listing an edition nobody has seen is left out: sealing it would let
            // whoever signed that edition publish it later on this standing.
            // A decided head's predecessor was seen too, served or compacted away.
            let decided: std::collections::HashSet<[u8; 32]> = authority.heads.iter().chain(control.heads.iter()).map(|h| h.inner_id).collect();
            let served: std::collections::HashSet<[u8; 32]> = editions
                .iter()
                .map(|e| e.self_hash)
                .chain(editions.iter().filter(|e| decided.contains(&e.inner_id)).filter_map(|e| e.prev_hash))
                .collect();
            let vouches_only_for_served = |h: &FoldedHead| {
                editions
                    .iter()
                    .find(|e| e.inner_id == h.inner_id && e.vsk == vsk::TENURE)
                    .and_then(|e| super::roles::parse_tenure_content(&e.content))
                    .is_none_or(|t| t.sealed.iter().flat_map(|x| x.heads.iter()).all(|x| crate::simd::hex::hex_to_bytes_32_checked(x).is_some_and(|b| served.contains(&b))))
            };
            // Deletions first of all: they are terminal, so a budget cut must never take one.
            let deletes = |h: &FoldedHead| {
                editions.iter().find(|e| e.inner_id == h.inner_id).is_some_and(|e| {
                    (e.vsk == vsk::CHANNEL_METADATA || e.vsk == vsk::CATEGORY) && deletes_entity(e.vsk == vsk::CATEGORY, &e.content)
                })
            };
            let theirs = |h: &FoldedHead| h.author == member.to_bytes() && vouches_only_for_served(h);
            let mut mine = seal_order(&authority.heads, &control.heads, theirs, deletes);
            if mine.is_empty() {
                continue;
            }
            let roles: Vec<&crate::community::roles::Role> = authority.roles.roles_of(&member_hex).collect();
            let Some(top) = roles.iter().filter(|r| r.rank.is_some()).min_by_key(|r| r.position) else { continue };
            let mut bits = roles.iter().fold(0u64, |acc, r| acc | r.permissions.0);
            if !is_owner {
                let support = authority.roles.permissions_above(&me_hex, top.position);
                let whole = support.contains(crate::community::roles::Permissions::MANAGE_ROLES) && bits & !support.0 == 0;
                match (whole, mode) {
                    (true, _) => {}
                    (false, Seal::Strict) => {
                        return Err("this member holds permissions you don't, so their decisions can't be kept; ask someone who holds them".to_string());
                    }
                    (false, Seal::BestEffort) if !support.contains(crate::community::roles::Permissions::MANAGE_ROLES) => continue,
                    (false, Seal::BestEffort) => bits &= support.0,
                }
            }
            if mine.len() > super::roles::TENURE_HEAD_BUDGET {
                if mode == Seal::Strict {
                    return Err("this member decided more than one record can keep; nothing was changed".to_string());
                }
                mine.truncate(super::roles::TENURE_HEAD_BUDGET);
            }
            let eid = super::derive::tenure_locator(cid, &member.to_bytes(), &me.to_bytes());
            let eid_hex = crate::simd::hex::bytes_to_hex_32(&eid);
            let held = authority.heads.iter().find(|h| h.entity_hex == eid_hex).and_then(|h| editions.iter().find(|e| e.inner_id == h.inner_id));
            // Replacing a Tenure this fold can't see would drop what it sealed.
            if held.is_none() && floors.contains_key(&eid_hex) && !authority.refused.contains(&eid_hex) {
                match mode {
                    Seal::Strict => return Err("this member's earlier record isn't being served; nothing was changed, try again shortly".to_string()),
                    Seal::BestEffort => continue,
                }
            }
            let prior = held.and_then(|e| super::roles::parse_tenure_content(&e.content)).map(|t| t.sealed).unwrap_or_default();
            let entry = super::roles::TenureEntry { rank: top.rank.clone().expect("a ranked role"), permissions: bits, heads: mine.iter().map(crate::simd::hex::bytes_to_hex_32).collect() };
            let Some(sealed) = super::roles::tenure_with(prior, entry, &mine) else { continue };
            let tenure = super::roles::TenureContent { member: member_hex, sealed };
            publish_control_edition(transport, community, vsk::TENURE, &eid, &super::roles::tenure_content_json(&tenure)?).await?;
        }
        Ok(())
    })
    .await
}

/// Set exactly which Roles `member` holds. A Grant replaces the member's whole set
/// (CORD-04 §2), so this is the one place a set is written: every change is judged
/// against the author's rank, and ids this device can't resolve ride through
/// untouched rather than being stripped by the device that knows least.
pub async fn set_member_roles<T: Transport + ?Sized>(
    transport: &T,
    community: &CommunityV2,
    member: &PublicKey,
    role_ids: Vec<String>,
) -> Result<(), String> {
    change_member_roles(transport, community, member, move |_| role_ids).await
}

/// [`set_member_roles`] to what `next` makes of the Roles the member holds by the freshest
/// view, so a Role granted or taken elsewhere meanwhile is kept as it now stands.
pub async fn change_member_roles<T: Transport + ?Sized, F: FnOnce(&[String]) -> Vec<String> + Send>(
    transport: &T,
    community: &CommunityV2,
    member: &PublicKey,
    next: F,
) -> Result<(), String> {
    crate::db::scoped(async move {
        let view = fetch_authority(transport, community).await;
        let author = role_author(community, &view)?;
        let member_hex = member.to_hex();
        // The owner may hold Roles, for display alone, and only the owner sets them (CORD-04 §3).
        let owner_self = member_hex == author.owner_hex;
        if owner_self && author.me_hex != author.owner_hex {
            return Err("only the owner sets the owner's roles".to_string());
        }
        if owner_self && view.roles.everyone.is_none() {
            return Err("the owner holds roles only on the new roles".to_string());
        }
        require_grant_head(community, &view, &member_hex)?;
        let member_rank = view.roles.highest_position(&member_hex).unwrap_or(u32::MAX);
        if !owner_self && (author.me_hex == member_hex || !author.supports(member_rank, 0)) {
            return Err("you can only change the roles of members beneath you".to_string());
        }
        let current: Vec<String> = view
            .roles
            .grants
            .iter()
            .find(|g| g.member == member_hex)
            .map(|g| g.role_ids.clone())
            .unwrap_or_default();
        let role_ids = next(&current);
        let mut next: Vec<String> = Vec::new();
        for id in role_ids.iter().map(|r| r.to_ascii_lowercase()) {
            if !next.contains(&id) {
                next.push(id);
            }
        }
        for id in next.iter().filter(|id| !current.contains(id)) {
            let role = view.roles.role(id).ok_or("no such role")?;
            if !author.supports(role.position, 0) {
                return Err(format!("you can't grant \"{}\": it isn't beneath your own role", role.name));
            }
        }
        let dropped: Vec<String> = current.iter().filter(|id| !next.contains(id)).cloned().collect();
        for id in dropped {
            // An unresolvable id can't be judged, so it can't be removed either.
            match view.roles.role(&id) {
                Some(role) if !author.supports(role.position, 0) => {
                    return Err(format!("you can't remove \"{}\": it isn't beneath your own role", role.name));
                }
                Some(_) => {}
                None => next.push(id),
            }
        }
        if next.len() > super::roles::MAX_ROLES_PER_MEMBER {
            return Err(format!("a member holds at most {} roles", super::roles::MAX_ROLES_PER_MEMBER));
        }
        let mut a = current.clone();
        let mut b = next.clone();
        a.sort();
        b.sort();
        if a == b {
            return Ok(());
        }
        // Keys follow the grant: one that opens a private channel this device can't key leaves
        // the member at its door (CORD-03 §5).
        if view.roles.everyone.is_some() {
            let mut after = view.roles.clone();
            after.grants.retain(|g| g.member != member_hex);
            after.grants.push(crate::community::roles::MemberGrant { member: member_hex.clone(), role_ids: next.clone() });
            let owner = Some(author.owner_hex.as_str());
            let opened = community
                .channels
                .iter()
                .filter(|c| c.private && c.key.is_none())
                .map(|c| crate::simd::hex::bytes_to_hex_32(&c.id.0))
                .filter(|chan| !view.roles.is_entitled(owner, &member_hex, chan, &[], &[]) && after.is_entitled(owner, &member_hex, chan, &[], &[]))
                .count();
            if opened > 0 {
                let what = if next.iter().filter(|id| !current.contains(id)).count() > 1 { "these roles" } else { "this role" };
                let channels = if opened == 1 { "a private channel".to_string() } else { format!("{opened} private channels") };
                return Err(format!("You can't give {what}: it opens {channels} you don't have access to. Someone with access has to, or get access first."));
            }
        }
        grant_roles_with_roster(transport, community, member, next.clone(), &view.roles).await?;
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        merge_local_roster(&cid_hex, None, Some(&crate::community::roles::MemberGrant { member: member_hex.clone(), role_ids: next.clone() }));
        if owner_self {
            return Ok(()); // the owner already holds every channel's key
        }
        settle_channel_keys(transport, community, &view, member, &current, &next).await
    })
    .await
}

/// Move Private Channel keys to match a role change (CORD-03: a key is "delivered on
/// grant and rekeyed on removal"). A role scoped to a channel IS its access list, so
/// gaining one owes the member that channel's key, and losing the last one that
/// entitled them rotates the channel without them. Without this a Grant would move
/// entitlement while the keys stayed where they were.
async fn settle_channel_keys<T: Transport + ?Sized>(
    transport: &T,
    community: &CommunityV2,
    view: &AuthorityView,
    member: &PublicKey,
    before: &[String],
    after: &[String],
) -> Result<(), String> {
    use crate::community::roles::RoleScope;
    if view.roles.everyone.is_some() {
        let mut next = view.roles.clone();
        let member_hex = member.to_hex();
        next.grants.retain(|g| g.member != member_hex);
        next.grants.push(crate::community::roles::MemberGrant { member: member_hex, role_ids: after.to_vec() });
        return settle_access(transport, community, &view.roles, &next).await;
    }
    let added: Vec<String> = after.iter().filter(|id| !before.contains(id)).cloned().collect();
    let removed: Vec<String> = before.iter().filter(|id| !after.contains(id)).cloned().collect();
    let owner_hex = community.owner()?.to_hex();
    let member_hex = member.to_hex();
    let channel_of = |id: &String| match view.roles.role(id).map(|r| &r.scope) {
        Some(RoleScope::Channel(c)) => Some(c.to_ascii_lowercase()),
        _ => None,
    };
    let held = |hex: &str| {
        crate::simd::hex::hex_to_bytes_32_checked(hex)
            .and_then(|b| community.channel(&ChannelId(b)).map(|c| (c.private, c.key.is_some(), ChannelId(b))))
    };

    // One Direct Invite carries every channel the new set entitles them to.
    if added.iter().filter_map(channel_of).any(|c| matches!(held(&c), Some((true, true, _)))) {
        let my_pk = me_pk()?;
        let bundle = bundle_of_with_overlay(community, BundleAudience::Member(*member), Some(my_pk), None, None, &added, &removed);
        let signer = crate::signer::active_signer()?;
        let wrap = invite::build_direct_invite_signed(&signer, my_pk, member, &bundle).await.map_err(|e| e.to_string())?;
        transport.publish(&wrap, &community.relays).await?;
    }

    let mut severed: Vec<String> = Vec::new();
    for chan in removed.iter().filter_map(channel_of) {
        if severed.contains(&chan) {
            continue;
        }
        severed.push(chan.clone());
        let Some((true, true, channel_id)) = held(&chan) else { continue };
        if view.roles.is_entitled(Some(&owner_hex), &member_hex, &chan, &added, &removed) {
            continue; // another role they keep still opens it
        }
        let access_ids = view.roles.channel_role_ids(&chan);
        rekey_channel_excluding(transport, community, &channel_id, &view.roles, &access_ids, std::slice::from_ref(member)).await?;
    }
    Ok(())
}

/// A grant replaces whole — refuse the merge when this member's grant is FLOORED
/// locally but no head folded (withheld / evicted): a blind push at that point
/// would erase their other roles at a higher version.
fn require_grant_head(community: &CommunityV2, view: &AuthorityView, member_hex: &str) -> Result<(), String> {
    let Some(member) = crate::simd::hex::hex_to_bytes_32_checked(member_hex) else {
        return Err("malformed member key".to_string());
    };
    let eid_hex = crate::simd::hex::bytes_to_hex_32(&super::derive::grant_locator(community.id(), &member));
    if view.floored.contains(&eid_hex) && !view.head_entities.contains(&eid_hex) {
        return Err("this member's current grant could not be fetched; try again once relays serve the control plane".to_string());
    }
    Ok(())
}

/// Replace the Banlist (vsk 4, CORD-04 §4) with `banned` (lowercase-hex npubs), the
/// whole list on every edit. Gated on the reader side by `BAN` per head plus strict
/// outrank per entry — mirrored here BEFORE the publish, so an unauthorized caller
/// (an SDK bot without the bit, a demoted moderator) fails loudly instead of
/// publishing an edition every reader silently rejects while its own local echo
/// caches the phantom ban.
pub async fn set_banlist<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, banned: &[String]) -> Result<(), String> {
    crate::db::scoped(async move {
        super::roles::validate_banlist(banned)?;
        {
            let my_pk = me_pk()?;
            let owner = community.owner()?;
            if my_pk != owner {
                let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
                let me_hex = my_pk.to_hex();
                let current = crate::db::community::get_community_banlist(&cid_hex).unwrap_or_default();
                if current.contains(&me_hex) {
                    return Err("you are banned from this community".to_string());
                }
                let roster = crate::db::community::get_community_roles(&cid_hex)?;
                let owner_hex = owner.to_hex();
                if !roster.is_authorized(&me_hex, Some(&owner_hex), crate::community::roles::Permissions::BAN) {
                    return Err("editing the banlist needs the BAN permission".to_string());
                }
                // Only the entries this edit ADDS need the per-target outrank (the fold
                // keeps prior authorized bans alive through its per-candidate history).
                for target in banned.iter().filter(|t| !current.contains(*t)) {
                    if !roster.can_act_on_member(&me_hex, Some(&owner_hex), target, crate::community::roles::Permissions::BAN) {
                        return Err("you do not outrank a member this ban targets".to_string());
                    }
                }
            }
        }
        let content = super::roles::banlist_content_json(banned)?;
        let eid = super::derive::banlist_locator(community.id());
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let entity_hex = crate::simd::hex::bytes_to_hex_32(&eid);
        // The version this publish will chain to — mirrors publish_control_edition.
        let version = match crate::db::community::get_edition_head(&cid_hex, &entity_hex)? {
            Some((v, _)) => v + 1,
            None => 1,
        };
        publish_control_edition(transport, community, vsk::BANLIST, &eid, &content).await?;
        // ECHO the published list into the local cache at once. Without this, the
        // cache only moves on a successful control-plane fold — and a caller
        // composing ban steps (banlist → grant strip → refound) re-reads the STALE
        // list if any later step trips before the fold, so each new banlist
        // edition it builds ERASES every ban since the last fold. Nineteen bans in
        // production each overwrote their predecessor exactly this way.
        store_banlist(&cid_hex, banned, version as i64);
        Ok(())
    })
    .await
}

/// Store a banlist, telling the UI when the set moved.
fn store_banlist(cid_hex: &str, banned: &[String], version: i64) {
    if crate::db::community::set_community_banlist(cid_hex, banned, version).unwrap_or(false) {
        announce_banlist(cid_hex);
    }
}

/// A ban hides what its target already posted (in SQL), and an un-ban shows it again: a painted
/// timeline is stale only when the set moves, so this, not every control change, re-reads it.
fn announce_banlist(cid_hex: &str) {
    crate::emit_event("community_banlist_changed", &serde_json::json!({ "community_id": cid_hex }));
}

/// Per-community moderation-unit locks. Session-scoped: an account swap drops the
/// map with its session, so no cross-account carry-over and nothing to clear.
struct ModerationLocks;
fn moderation_lock(cid: &crate::community::CommunityId) -> std::sync::Arc<tokio::sync::Mutex<()>> {
    let map = crate::db::current_session()
        .scoped::<ModerationLocks, std::sync::Mutex<std::collections::HashMap<[u8; 32], std::sync::Arc<tokio::sync::Mutex<()>>>>>();
    let mut m = map.lock().unwrap_or_else(|e| e.into_inner());
    if let Some(lock) = m.get(&cid.0) {
        return std::sync::Arc::clone(lock);
    }
    // A lock only the map holds has no holder or waiter, so a left community's goes here.
    m.retain(|_, lock| std::sync::Arc::strong_count(lock) > 1);
    std::sync::Arc::clone(m.entry(cid.0).or_default())
}

/// Fold control + guestbook so a moderation unit composes over the freshest view
/// another moderator may have advanced. Best-effort: on a dead network the local
/// cache (kept fresh by `set_banlist`'s own echo) is still the best basis.
async fn converge_authority<T: Transport + ?Sized>(transport: &T, id: &crate::community::CommunityId) {
    if let Ok(Some(fresh)) = crate::db::community::load_community_v2(id) {
        let _ = follow_control(transport, &fresh).await;
        // Membership is part of the converged view: a Join that legally raced a ban
        // window may exist only on the relays, and our own just-published edition
        // doesn't echo back to trigger a follow.
        if let Ok(added) = sync_guestbook(transport, &fresh).await {
            if !added.is_empty() {
                crate::traits::emit_event_json(
                    "community_refreshed",
                    serde_json::json!({ "community_id": crate::simd::hex::bytes_to_hex_32(&id.0) }),
                );
            }
        }
    }
}

/// One queued ban/unban intent, answered on `done` when its batch completes.
struct ModIntent {
    id: u64,
    targets: Vec<PublicKey>,
    banned: bool,
    done: tokio::sync::oneshot::Sender<Result<(), String>>,
}

/// Per-community pending moderation intents — the coalescing queue behind
/// [`moderation_lock`]. Session-scoped for the same reason as the lock.
struct PendingModeration;
fn pending_moderation(cid: &crate::community::CommunityId) -> std::sync::Arc<std::sync::Mutex<std::collections::HashMap<[u8; 32], Vec<ModIntent>>>> {
    let _ = cid;
    crate::db::current_session()
        .scoped::<PendingModeration, std::sync::Mutex<std::collections::HashMap<[u8; 32], Vec<ModIntent>>>>()
}

/// Ban or unban members as ONE moderation unit — the CORD-04 §6 three-removal
/// composition, once for the whole wave: one Banlist edition (instant silence),
/// one grant-strip pass (authority removal), and one read cut (a private
/// community re-founds ONCE with every target removed; a public one rotates each
/// reachable private channel ONCE excluding them all).
///
/// Serialized AND coalesced per community. Without the lock, concurrent bans
/// (the SDK spawns a handler task per message, so a spam wave is exactly this)
/// each build their edition from a pre-sibling banlist snapshot, and the fold
/// takes the HEAD's content — so the last racing head silently un-bans the
/// earlier target at every reader, and the refound then compacts that erasure
/// into the new epoch permanently.
///
/// The coalescing half: a unit's read cut holds the lock for a whole multi-
/// publish rotation, so serial single bans arriving meanwhile would each queue
/// up a rotation of their own. Instead every caller deposits an intent; whoever
/// next takes the lock drains ALL of them into one edition + one read cut,
/// applied in arrival order (ban-then-unban of one npub nets to unban). Each
/// intent is judged individually — a target the caller cannot outrank, or an
/// add past the 500-entry ceiling, fails only its own caller, never the batch.
pub async fn set_members_banned<T: Transport + ?Sized>(
    transport: &T,
    community_id: &crate::community::CommunityId,
    members: &[PublicKey],
    banned: bool,
) -> Result<(), String> {
    crate::db::scoped(async move {
        // Dedup — a doubled target must not strip or rotate twice.
        let mut targets: Vec<PublicKey> = Vec::with_capacity(members.len());
        for m in members {
            if !targets.contains(m) {
                targets.push(*m);
            }
        }
        if targets.is_empty() {
            return Ok(());
        }
        // Plain uniqueness source for intent ids — not per-account state.
        static INTENT_IDS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
        let my_id = INTENT_IDS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        let (tx, rx) = tokio::sync::oneshot::channel();
        {
            let map = pending_moderation(community_id);
            let mut m = map.lock().unwrap_or_else(|e| e.into_inner());
            m.entry(community_id.0).or_default().push(ModIntent { id: my_id, targets, banned, done: tx });
        }
        let unit = moderation_lock(community_id);
        // `biased` so a verdict delivered by another leader wins over a lock we
        // happen to also hold — a drained intent must never run twice.
        tokio::select! {
            biased;
            res = rx => res.unwrap_or_else(|_| Err("moderation unit aborted before completing".to_string())),
            _guard = unit.lock() => {
                // Leader: drain EVERYTHING pending right now. Every ban/unban that
                // stacked while the previous unit's rotation ran coalesces here.
                let batch: Vec<ModIntent> = {
                    let map = pending_moderation(community_id);
                    let mut m = map.lock().unwrap_or_else(|e| e.into_inner());
                    m.remove(&community_id.0).unwrap_or_default()
                };
                run_moderation_batch(transport, community_id, batch, my_id).await
            }
        }
    })
    .await
}

/// Execute one drained batch of moderation intents under the held lock: judge
/// each intent in arrival order against the evolving list, publish the coalesced
/// edition, strip + read-cut the net newly-banned set once, then answer every
/// intent with its own verdict. Returns the LEADER's verdict.
async fn run_moderation_batch<T: Transport + ?Sized>(
    transport: &T,
    community_id: &crate::community::CommunityId,
    batch: Vec<ModIntent>,
    leader_id: u64,
) -> Result<(), String> {
    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community_id.0);

    // SYNC BEFORE COMPOSING: a banlist edition replaces the whole list on the
    // wire, so the mutation must start from the freshest view — another
    // moderator's ban this device hasn't folded yet would otherwise be
    // silently erased by ours.
    converge_authority(transport, community_id).await;

    let original = crate::db::community::get_community_banlist(&cid_hex)?;
    let roster = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
    let community0 = crate::db::community::load_community_v2(community_id)?
        .ok_or_else(|| "v2 community not found".to_string())?;
    let owner = community0.owner()?;
    let my_pk = me_pk()?;
    let my_hex = my_pk.to_hex();
    let owner_hex = owner.to_hex();

    // Judge intents in arrival order against the EVOLVING list, so the last
    // intent naming an npub wins — exactly serial semantics, minus the churn.
    let mut list = original.clone();
    let mut pk_of: std::collections::HashMap<String, PublicKey> = std::collections::HashMap::new();
    let mut verdicts: std::collections::HashMap<u64, Result<(), String>> = std::collections::HashMap::new();
    for intent in &batch {
        let hexes: Vec<String> = intent.targets.iter().map(|p| p.to_hex()).collect();
        for (pk, hex) in intent.targets.iter().zip(&hexes) {
            pk_of.insert(hex.clone(), *pk);
        }
        let verdict = (|| {
            // Mirror of set_banlist's authority gate, per intent, so one refused
            // intent cannot sink its batch-mates.
            if my_pk != owner {
                if original.contains(&my_hex) {
                    return Err("you are banned from this community".to_string());
                }
                if !roster.is_authorized(&my_hex, Some(&owner_hex), crate::community::roles::Permissions::BAN) {
                    return Err("editing the banlist needs the BAN permission".to_string());
                }
                if intent.banned {
                    for t in hexes.iter().filter(|t| !list.contains(*t)) {
                        if !roster.can_act_on_member(&my_hex, Some(&owner_hex), t, crate::community::roles::Permissions::BAN) {
                            return Err("you do not outrank a member this ban targets".to_string());
                        }
                    }
                }
            }
            let mut next = list.clone();
            next.retain(|h| !hexes.contains(h));
            if intent.banned {
                next.extend(hexes.iter().cloned());
            }
            super::roles::validate_banlist(&next)?;
            list = next;
            Ok(())
        })();
        verdicts.insert(intent.id, verdict);
    }

    let changed = {
        let mut a = original.clone();
        let mut b = list.clone();
        a.sort();
        b.sort();
        a != b
    };
    let newly_banned: Vec<PublicKey> = list
        .iter()
        .filter(|h| !original.contains(*h))
        .filter_map(|h| pk_of.get(h).copied())
        .collect();

    // Publish the coalesced edition + strips, then the single read cut.
    let unit_result: Result<(), String> = async {
        if !changed {
            return Ok(());
        }
        // Rotation barrier: a sibling refound holds this lock for its whole
        // multi-publish rotation while the row still names the OLD root. Dropped
        // before `refound_community`, which re-acquires it (non-reentrant).
        let (community, stripped) = {
            let lock = super::realtime::follow_lock(community_id);
            let _rotation = lock.lock().await;
            let community = crate::db::community::load_community_v2(community_id)?
                .ok_or_else(|| "v2 community not found".to_string())?;
            // A ban drops what its target says, never what they decided (CORD-04 §9).
            seal_standing(transport, &community, &newly_banned, Seal::BestEffort).await?;
            // The departure goes first: between the two, the banlist still holds them out.
            let unbanned: Vec<PublicKey> = original.iter().filter(|h| !list.contains(*h)).filter_map(|h| pk_of.get(h).copied()).collect();
            if !unbanned.is_empty() {
                publish_ban_departures(transport, &community, &unbanned).await;
            }
            set_banlist(transport, &community, &list).await?;
            let mut stripped: Vec<(PublicKey, Vec<String>)> = Vec::new();
            // Pre-strip role capture: the read-severance below judges which
            // private channels each member could reach, and after the strip
            // the fold may no longer show it.
            for pk in &newly_banned {
                let hex = pk.to_hex();
                let roles: Vec<String> = roster.roles_of(&hex).map(|r| r.role_id.clone()).collect();
                // Nothing granted = nothing to strip: a bulk ban of roleless
                // spammers must not publish one empty Grant edition apiece.
                let has_grant = roster.grants.iter().any(|g| g.member == hex && !g.role_ids.is_empty());
                if has_grant {
                    // Strip on the kick doctrine (skip, not refuse): readers honor a
                    // grant strip only from MANAGE_ROLES + outrank, and a BAN-only
                    // moderator still bans — the banlist silences regardless, and
                    // publishing a strip readers reject would only poison our own
                    // floor for that grant entity.
                    let can_strip = my_pk == owner
                        || roster.can_act_on_member(&my_hex, Some(&owner_hex), &hex, crate::community::roles::Permissions::MANAGE_ROLES);
                    if can_strip {
                        grant_roles_sealing(transport, &community, pk, vec![], Seal::BestEffort).await?;
                    } else {
                        crate::log_warn!("[Ban] grant strip skipped (no MANAGE_ROLES over the target); the banlist still silences");
                    }
                }
                stripped.push((*pk, roles));
            }
            (community, stripped)
        };
        if !newly_banned.is_empty() {
            // CORD-05 §5 gate: a PUBLIC community — any live invite link — must NOT
            // refound on ban. The link refresh re-posts the bundle with the new root
            // behind the same URL, so the banned member re-fetches and reads on: the
            // rotation severs nothing and can strand foreign-link joiners on a buried
            // epoch. The Banlist does all the real work in Public mode.
            if community_is_public(transport, &community).await {
                crate::log_info!("[Ban] public community — banlist + grant strip, no refound (CORD-05 §5)");
                // CORD-06 §1 still applies per channel: only rotation severs the
                // private-channel reads their held keys still allow.
                match sever_banned_private_reads(transport, &community, &stripped, Some(&roster)).await {
                    Ok(0) => {}
                    Ok(n) => crate::log_info!("[Ban] rotated {n} private channel(s) the banned member(s) could read"),
                    Err(e) => crate::log_warn!("[Ban] private-channel read severance incomplete: {e}"),
                }
            } else if let Err(e) = refound_community(transport, &community, &newly_banned).await {
                // Best-effort escalation, NEVER the ban's verdict. The banlist
                // edition (instant silence at every honest reader) and the grant
                // strip ARE the ban; the refound's §3 coverage gate demands the
                // relay serve back heads published milliseconds ago, so propagation
                // lag makes it fail-closed — and propagating that error out of here
                // once left every ban half-applied AND skipped the converge below,
                // so each next ban rebuilt from a stale list and erased its
                // predecessors.
                crate::log_warn!("[Ban] refound deferred (banlist + grant strip landed): {e}");
            }
        }
        Ok(())
    }
    .await;
    converge_authority(transport, community_id).await;

    // Answer every intent: its own judgment first, then the shared publish fate.
    let mut my_verdict = Err("leader intent missing from its own batch".to_string());
    for intent in batch {
        let final_verdict = verdicts
            .remove(&intent.id)
            .unwrap_or_else(|| Err("intent was never judged".to_string()))
            .and_then(|()| unit_result.clone());
        if intent.id == leader_id {
            my_verdict = final_verdict;
        } else {
            let _ = intent.done.send(final_verdict);
        }
    }
    my_verdict
}

// ── Raid containment (CORD-06 Severing Refounding) ──────────────────────────

/// What a containment actually accomplished. Every field is an honest count —
/// a caller (Sentinel, a moderation console) reports these to a human, so a
/// half-done containment must never read as a closed door.
#[derive(Debug, Clone, Default, serde::Serialize)]
pub struct ContainmentReport {
    /// Raiders added to the Banlist.
    pub banned: usize,
    /// Members cut for joining inside the raid window without being convicted.
    pub window_cut: usize,
    /// Root epoch before and after. Equal = the refound did NOT land.
    pub epoch_before: u64,
    pub epoch_after: u64,
    /// True only if the severing refound published.
    pub refound_ok: bool,
    /// My own public links revoked here. Other creators' links die as their
    /// clients adopt the severed rotation.
    pub own_links_revoked: usize,
    /// Creators whose links are still live pending their client's adoption.
    pub foreign_link_creators: Vec<String>,
    /// Non-fatal problems worth showing a human.
    pub warnings: Vec<String>,
}

/// Contain a raid: ban the raiders, cut everyone who walked in through the door
/// during the raid window, then perform a SEVERING Refounding — the rotation
/// that revokes the invite links instead of carrying them into the new epoch.
///
/// This is the raid lane, not a general ban. An ordinary ban (even in a Public
/// community) keeps its shipped behaviour — [`set_members_banned`] decides
/// internally, and a public one deliberately does NOT roll the root. Here the
/// door itself is the vector, so it closes with the rotation.
///
/// `window_start_secs` is the raid's opening edge: unconvicted members who
/// joined at-or-after it are cut from the new epoch (NOT banned — an innocent
/// caught in the window rejoins through the owner's next link). Members already
/// present before the window are never cut, however quiet.
pub async fn contain_raid<T: Transport + ?Sized>(
    transport: &T,
    community_id: &crate::community::CommunityId,
    raiders: &[PublicKey],
    window_start_secs: u64,
    cut_also: &[PublicKey],
) -> Result<ContainmentReport, String> {
    crate::db::scoped(async move {
        let mut report = ContainmentReport::default();
        let community = crate::db::community::load_community_v2(community_id)?
            .ok_or_else(|| "v2 community not found".to_string())?;
        report.epoch_before = community.root_epoch.0;
        report.epoch_after = community.root_epoch.0;
        let owner = community.owner()?;
        let my_pk = me_pk()?;

        // 1. Ban the convicted. Goes through the coalescer: the banlist edition is
        //    a read-modify-write, and a concurrent single ban would otherwise
        //    rebuild from a stale list and erase this one. A FAILED ban (most
        //    plausibly the 500-entry banlist ceiling under a mega-raid) must not
        //    abort the containment: the refound below cuts the raiders
        //    cryptographically whether or not the list could name them.
        if !raiders.is_empty() {
            match set_members_banned(transport, community_id, raiders, true).await {
                Ok(()) => report.banned = raiders.len(),
                Err(e) => report.warnings.push(format!("banlist did not land ({e}) — the refound still cuts every named raider")),
            }
        }

        // Re-read: the ban published a Banlist edition and stripped grants.
        let community = crate::db::community::load_community_v2(community_id)?
            .ok_or_else(|| "v2 community not found".to_string())?;

        // 2. The window cut. A raid arrives THROUGH the link, so everyone who
        //    walked in during it is part of the wave for containment purposes —
        //    conviction only ever names the ones who spoke. Never the owner, never
        //    staff, never anyone whose earliest trace predates the window.
        //
        //    `cut_also` first: Join timestamps are AUTHOR-claimed, so a quiet
        //    raider who backdated their Join slides under any window this fold
        //    can compute. A caller watching arrivals on its own clock (Sentinel's
        //    receive log) names them here and they are cut regardless.
        let mut cut: Vec<PublicKey> = raiders.to_vec();
        for pk in cut_also {
            if !cut.contains(pk) {
                cut.push(*pk);
                report.window_cut += 1;
            }
        }
        if window_start_secs > 0 {
            let roster = crate::db::community::get_community_roles(
                &crate::simd::hex::bytes_to_hex_32(&community.id().0),
            )
            .unwrap_or_default();
            let owner_hex = owner.to_hex();
            match fetch_guestbook_events(transport, &community, 0).await {
                Ok((events, _, _)) => {
                    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
                    let (held, _) = crate::db::community::get_guestbook(&cid_hex).unwrap_or_default();
                    let watched = guestbook_observed_since(&cid_hex).is_some_and(|since| since < window_start_secs);
                    let first_seen = earliest_arrivals(&events, &held, watched, |pk| {
                        *pk == owner || roster.is_authorized(&pk.to_hex(), Some(&owner_hex), crate::community::roles::Permissions::BAN)
                    });
                    for (pk, joined) in first_seen {
                        if joined < window_start_secs || pk == owner || pk == my_pk || cut.contains(&pk) {
                            continue;
                        }
                        // Staff are never cut by a window: a moderator who joined
                        // moments before a raid is still a moderator.
                        if roster.is_staff(&pk.to_hex(), Some(&owner_hex)) {
                            continue;
                        }
                        cut.push(pk);
                        report.window_cut += 1;
                    }
                }
                Err(e) => report
                    .warnings
                    .push(format!("guestbook unreadable — no window cut applied, only convicted raiders are severed ({e})")),
            }
        }

        // 3. The severing refound. Private channels are deliberately NOT rotated
        //    separately: the root roll re-keys every plane, and link-borne raiders
        //    were never entitled to a private channel in the first place.
        //
        //    Under the MODERATION lock, exactly as `run_moderation_batch` holds it
        //    across ITS refound: an ordinary ban racing this rotation would publish
        //    a banlist edition the compaction fetch below has already read past,
        //    and the new epoch would carry it away — a ban silently erased at the
        //    moment bans matter most. Lock order (moderation → follow) matches the
        //    shipped path. Retried: the refound's coverage gate fails closed under
        //    exactly the relay lag a mid-raid flood produces.
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let links_before = crate::db::community::list_public_invites(&cid_hex).map(|l| l.len()).unwrap_or(0);
        let unit = moderation_lock(community_id);
        let _guard = unit.lock().await;
        let mut refound = Err("severing refound never attempted".to_string());
        for attempt in 0..3u8 {
            refound = refound_community_severing(transport, &community, &cut, window_start_secs).await;
            if refound.is_ok() {
                break;
            }
            if attempt < 2 {
                crate::rt::time::sleep(std::time::Duration::from_millis(400 * (attempt as u64 + 1))).await;
            }
        }
        match refound {
            Ok(updated) => {
                report.refound_ok = true;
                report.epoch_after = updated.root_epoch.0;
                let links_after = crate::db::community::list_public_invites(&cid_hex).map(|l| l.len()).unwrap_or(0);
                report.own_links_revoked = links_before.saturating_sub(links_after);
                if links_after > 0 {
                    report.warnings.push(format!(
                        "{links_after} of my own link(s) survived the sever — the mark retries them on the next follow"
                    ));
                }
                report.foreign_link_creators = crate::db::community::invite_link_set_creators(&cid_hex)
                    .unwrap_or_default()
                    .into_iter()
                    .filter(|c| *c != my_pk.to_hex())
                    .collect();
            }
            Err(e) => {
                // The banlist landed and silences the named raiders at every honest
                // reader, but the DOOR IS STILL OPEN. Never dress this as success.
                report.warnings.push(format!("SEVERING REFOUND FAILED — the invite door may still be open: {e}"));
            }
        }
        Ok(report)
    })
    .await
}

/// Edit the community metadata (vsk 0, CORD-02 §6). Gated on the reader side by
/// `MANAGE_METADATA`.
pub async fn edit_community_metadata<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, meta: &control::CommunityMetadata) -> Result<(), String> {
    ensure_folded_permission(community, &me_pk()?, crate::community::roles::Permissions::MANAGE_METADATA, "editing the community metadata")?;
    control::validate_community_metadata(meta).map_err(|e| e.to_string())?;
    let content = serde_json::to_string(meta).map_err(|e| e.to_string())?;
    let lock = super::realtime::follow_lock(community.id());
    let _guard = lock.lock().await;
    publish_control_edition(transport, community, vsk::COMMUNITY_METADATA, &community.id().0, &content).await?;
    // Applied locally too: the fold that would otherwise land it runs on a later control pass.
    if let Ok(Some(mut held)) = crate::db::community::load_community_v2(community.id()) {
        if apply_community_metadata(&mut held, meta.clone()) {
            crate::db::community::save_community_v2(&held)?;
        }
    }
    Ok(())
}

/// Persist a freshly-published icon/banner onto the held row and return the fresh
/// row. Reloads under the community's follow lock: `save_community_v2` is a
/// whole-row save that prunes channels absent from the passed struct, so writing
/// a stale pre-upload copy would drop rows a concurrent fold just landed.
pub async fn persist_community_image(
    id: &crate::community::CommunityId,
    img: Option<control::ImageRef>,
    is_banner: bool,
) -> Option<CommunityV2> {
    let lock = super::realtime::follow_lock(id);
    let _guard = lock.lock().await;
    let mut fresh = crate::db::community::load_community_v2(id).ok()??;
    if is_banner {
        fresh.banner = img;
    } else {
        fresh.icon = img;
    }
    crate::db::community::save_community_v2(&fresh).ok()?;
    Some(fresh)
}

/// Add or edit a channel's metadata (vsk 2, CORD-03 §2). `channel_id` is the
/// coordinate. Gated on the reader side by `MANAGE_CHANNELS`.
pub async fn edit_channel_metadata<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, channel_id: &ChannelId, meta: &control::ChannelMetadata) -> Result<(), String> {
    crate::db::scoped(edit_channel_metadata_bound(transport, community, channel_id, meta)).await
}

async fn edit_channel_metadata_bound<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, channel_id: &ChannelId, meta: &control::ChannelMetadata) -> Result<(), String> {
    let my_pk = me_pk()?;
    ensure_channel_manager(community, &my_pk)?;
    let old_name = community.channel(channel_id).map(|c| c.name.clone());
    let base = community.channel(channel_id).map(|c| c.metadata());
    // Making a Channel private is a key rotation of its own (CORD-03 §2).
    if meta.private && community.channel(channel_id).is_some_and(|c| !c.private) {
        return Err("make a channel private with privatize_channel".to_string());
    }
    // The edition chains from the head this lock keeps still until it is published.
    let lock = super::realtime::follow_lock(community.id());
    let guard = lock.lock().await;
    let fresh = crate::db::community::load_community_v2(community.id())?.unwrap_or_else(|| community.clone());
    // A sealed rename goes under the newest key, never one a member just cut still holds.
    let refreshed;
    let community = if meta.private && roles_v2_held(&fresh) {
        follow_rekeys(transport, &fresh, &crate::db::current_session()).await?;
        refreshed = crate::db::community::load_community_v2(community.id())?.ok_or("v2 community not found")?;
        &refreshed
    } else {
        &fresh
    };
    let held = community.channel(channel_id);
    if held.is_some_and(|c| c.sealed.as_ref().is_some_and(|s| !s.open && !s.junk)) {
        return Err("this private channel's details are sealed under a key this device lacks".to_string());
    }
    // Only what the caller changed goes over what folded since it read the Channel.
    let merged = match (&base, held) {
        (Some(base), Some(now)) => merge_channel_metadata(base, meta, &now.metadata()),
        _ => meta.clone(),
    };
    let meta = &merged;
    let prev = channel_head(community, channel_id)?;
    let content = channel_edition_content(community, channel_id, meta, held.and_then(|c| c.key.map(|k| (k, c.epoch))), prev.as_ref())?;
    publish_control_edition(transport, community, vsk::CHANNEL_METADATA, &channel_id.0, &content).await?;
    let sealed = sealed_held(&content, prev);
    // Apply locally too. The fold is the authority but runs later, so without this
    // an edit we just made reads back stale until some future control pass — the
    // rename appears to have silently failed.
    if let Ok(Some(mut held)) = crate::db::community::load_community_v2(community.id()) {
        if let Some(ch) = held.channels.iter_mut().find(|c| c.id.0 == channel_id.0) {
            ch.name = meta.name.clone();
            ch.private = meta.private;
            ch.voice = meta.voice;
            ch.meta_custom = meta.custom.clone();
            ch.meta_extra = meta.extra.clone();
            ch.sealed = sealed;
            crate::db::community::save_community_v2(&held)?;
        }
    }
    drop(guard);
    // Keep the companion access role's label in step with the channel it gates.
    if meta.private {
        if let Some(old) = old_name.filter(|o| *o != meta.name) {
            rename_channel_access_role(transport, community, channel_id, &old, &meta.name).await;
        }
    }
    Ok(())
}

/// `ours` as its writer meant it against the `base` they read: each field they changed, over
/// `theirs`, the Channel as it stands now.
fn merge_channel_metadata(base: &control::ChannelMetadata, ours: &control::ChannelMetadata, theirs: &control::ChannelMetadata) -> control::ChannelMetadata {
    fn pick<T: Clone + PartialEq>(base: &T, ours: &T, theirs: &T) -> T {
        if ours != base { ours.clone() } else { theirs.clone() }
    }
    let mut extra = theirs.extra.clone();
    for key in base.extra.keys().chain(ours.extra.keys()) {
        if base.extra.get(key) != ours.extra.get(key) {
            match ours.extra.get(key) {
                Some(v) => extra.insert(key.clone(), v.clone()),
                None => extra.remove(key),
            };
        }
    }
    let custom = match (&base.custom, &ours.custom, &theirs.custom) {
        (b, o, t) if o == b => t.clone(),
        (b, Some(o), t) => {
            let (b, mut out) = (b.clone().unwrap_or_default(), t.clone().unwrap_or_default());
            for key in b.keys().chain(o.keys()) {
                if b.get(key) != o.get(key) {
                    match o.get(key) {
                        Some(v) => out.insert(key.clone(), v.clone()),
                        None => out.remove(key),
                    };
                }
            }
            Some(out)
        }
        (_, None, _) => None,
    };
    control::ChannelMetadata {
        name: pick(&base.name, &ours.name, &theirs.name),
        private: pick(&base.private, &ours.private, &theirs.private),
        voice: pick(&base.voice, &ours.voice, &theirs.voice),
        deleted: pick(&base.deleted, &ours.deleted, &theirs.deleted),
        custom,
        extra,
    }
}

/// Rename a private channel's companion access role to follow the channel (CORD-04 §2).
/// Best-effort and never fatal: the channel rename has already published, and a role's
/// name is cosmetic — entitlement is carried by the scope, not the label.
///
/// Only renames a label still equal to the channel's OLD name, so a deliberately
/// customised role name survives a channel rename untouched.
async fn rename_channel_access_role<T: Transport + ?Sized>(
    transport: &T,
    community: &CommunityV2,
    channel_id: &ChannelId,
    old_name: &str,
    new_name: &str,
) {
    crate::db::scoped(async move {
        let (Ok(my_pk), Ok(owner)) = (me_pk(), community.owner()) else {
            return;
        };
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let chan_hex = crate::simd::hex::bytes_to_hex_32(&channel_id.0);
        // Fetched, not cached: `set_role` republishes the WHOLE role body, so a stale
        // cache would clobber a permission edit this client has not folded yet.
        let mut roster = fetch_authority(transport, community).await.roles;
        let cached = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
        for r in cached.roles {
            if !roster.roles.iter().any(|x| x.role_id == r.role_id) {
                roster.roles.push(r);
            }
        }
        // MANAGE_CHANNELS got us the rename; the role edition needs MANAGE_ROLES + outrank
        // of its own. Publishing one readers reject would wedge our later, legitimate role
        // edits behind a rejected chain, so verify before publishing rather than after.
        let (me_hex, owner_hex) = (my_pk.to_hex(), owner.to_hex());
        if !roster.is_authorized_in(&me_hex, Some(&owner_hex), &chan_hex, crate::community::roles::Permissions::MANAGE_ROLES) {
            return;
        }
        // Same selector `grant_channel_access` vends: the permission-less scoped role. A
        // per-channel moderator role sharing the scope is NOT the access list.
        let Some(mut role) = roster
            .channel_roles(&chan_hex)
            .into_iter()
            .find(|r| r.permissions == crate::community::roles::Permissions::empty() && r.name == old_name)
            .cloned()
        else {
            return;
        };
        if !roster.can_act_on_position(&me_hex, Some(&owner_hex), role.position, crate::community::roles::Permissions::MANAGE_ROLES) {
            return;
        }
        role.name = new_name.to_string();
        if let Err(e) = set_role(transport, community, &role).await {
            crate::log_warn!("v2: channel renamed but its access role did not follow: {e}");
            return;
        }
        merge_local_roster(&cid_hex, Some(&role), None);
    })
    .await
}

/// The local mirror of a reader-side permission fold gate: the owner, or a
/// roster-authorized holder of `needed` who isn't banned. Refusing BEFORE any
/// publish keeps an unauthorized device from advancing its own edition floor onto
/// a head every reader rejects (wedging its later, legitimately-authorized edits
/// behind a rejected chain). Fail-closed: an empty/unfolded roster collapses to
/// owner-only — it can over-restrict, never grant authority no one has.
fn ensure_folded_permission(
    community: &CommunityV2,
    me: &PublicKey,
    needed: u64,
    verb: &str,
) -> Result<(), String> {
    let owner = community.owner()?;
    if *me == owner {
        return Ok(());
    }
    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
    let me_hex = me.to_hex();
    if crate::db::community::get_community_banlist(&cid_hex).unwrap_or_default().contains(&me_hex) {
        return Err("you are banned from this community".to_string());
    }
    let roster = crate::db::community::get_community_roles(&cid_hex)?;
    if roster.is_authorized(&me_hex, Some(&owner.to_hex()), needed) {
        Ok(())
    } else {
        Err(format!("{verb} needs the {} permission", permission_label(needed)))
    }
}

fn permission_label(bits: u64) -> &'static str {
    use crate::community::roles::Permissions;
    match bits {
        Permissions::MANAGE_ROLES => "MANAGE_ROLES",
        Permissions::MANAGE_CHANNELS => "MANAGE_CHANNELS",
        Permissions::MANAGE_METADATA => "MANAGE_METADATA",
        Permissions::BAN => "BAN",
        Permissions::CREATE_INVITE => "CREATE_INVITE",
        _ => "required",
    }
}

/// [`ensure_folded_permission`] for `MANAGE_CHANNELS` (CORD-03 §2).
fn ensure_channel_manager(community: &CommunityV2, me: &PublicKey) -> Result<(), String> {
    ensure_folded_permission(community, me, crate::community::roles::Permissions::MANAGE_CHANNELS, "managing channels here")
}

/// Create a new PUBLIC channel (CORD-03 §2): mint a fresh id, publish its metadata
/// edition (vsk 2), and add it to the held community. A Public channel derives its Chat
/// Plane from the `community_root` (no per-channel key), so other members fold it in on
/// their next control follow with nothing to distribute. Returns the new channel id.
/// Reader-gated by `MANAGE_CHANNELS`.
pub async fn create_public_channel<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, name: &str) -> Result<ChannelId, String> {
    let channel_id = ChannelId(super::super::random_32());
    create_public_channel_with_id(transport, community, name, channel_id).await?;
    Ok(channel_id)
}

/// [`create_public_channel`] with a CALLER-CHOSEN id — the migration-only entry point
/// (§migration) that reuses an existing channel's id so chat history stitches through.
/// Asserts the id isn't already live in a DIFFERENT held v2 community before minting.
pub async fn create_public_channel_with_id<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, name: &str, channel_id: ChannelId) -> Result<(), String> {
    crate::db::scoped(async move {
        // Serialize with the follow worker: the save below writes the WHOLE community
        // row from this caller's struct, so an unserialized concurrent follow adopting
        // a rotation would be rolled back to a stale root (a deaf community).
        let lock = super::realtime::follow_lock(community.id());
        let _guard = lock.lock().await;
        let my_pk = me_pk()?;
        ensure_channel_manager(community, &my_pk)?;
        assert_channel_id_free(&channel_id, community.id())?;
        let meta = control::ChannelMetadata { name: name.to_string(), private: false, voice: None, deleted: None, custom: None, extra: Default::default() };
        control::validate_channel_metadata(&meta).map_err(|e| e.to_string())?;
        let content = serde_json::to_string(&meta).map_err(|e| e.to_string())?;
        publish_control_edition(transport, community, vsk::CHANNEL_METADATA, &channel_id.0, &content).await?;
        // Add locally + persist so the creator can post immediately (peers fold it in).
        let mut updated = community.clone();
        updated.channels.push(ChannelV2 { id: channel_id, name: name.to_string(), private: false, key: None, epoch: updated.root_epoch, voice: None, meta_custom: None, meta_extra: Default::default(), writers: None, sealed: None });
        crate::db::community::save_community_v2(&updated)?;
        Ok(())
    })
    .await
}

/// Refuse a channel id already live in a DIFFERENT held v2 community — the same
/// cross-community hijack the `save_community_v2` guard forecloses, checked up front so a
/// migration twin never adopts an id it doesn't own. Only a foreign v2 owner blocks; a
/// row under any other protocol is re-parented.
fn assert_channel_id_free(channel_id: &ChannelId, community_id: &crate::community::CommunityId) -> Result<(), String> {
    let ch_hex = crate::simd::hex::bytes_to_hex_32(&channel_id.0);
    if let Ok(Some(existing)) = crate::db::community::community_id_for_channel(&ch_hex) {
        let mine = crate::simd::hex::bytes_to_hex_32(&community_id.0);
        let existing_id = crate::community::CommunityId(crate::simd::hex::hex_to_bytes_32(&existing));
        if existing != mine
            && matches!(crate::db::community::community_held(&existing_id), Ok(true))
        {
            return Err("channel id is already live in another v2 community".to_string());
        }
    }
    Ok(())
}

/// Publish a Category edition and apply it locally, as a channel edit does: the fold
/// that would otherwise show it runs later.
async fn set_category<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, id: [u8; 32], meta: &control::CategoryMetadata) -> Result<(), String> {
    if meta.deleted != Some(true) && meta.name.trim().is_empty() {
        return Err("a category needs a name".to_string());
    }
    control::validate_category_metadata(meta).map_err(|e| e.to_string())?;
    let content = serde_json::to_string(meta).map_err(|e| e.to_string())?;
    publish_control_edition(transport, community, vsk::CATEGORY, &id, &content).await?;
    let lock = super::realtime::follow_lock(community.id());
    let _guard = lock.lock().await;
    if let Ok(Some(mut held)) = crate::db::community::load_community_v2(community.id()) {
        if apply_category_metadata(&mut held, id, meta.clone()) {
            crate::db::community::save_community_v2(&held)?;
        }
    }
    Ok(())
}

/// Create a Category at the bottom of the sidebar (CORD-03 §4).
pub async fn create_category<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, name: &str) -> Result<[u8; 32], String> {
    crate::db::scoped(async move {
        ensure_channel_manager(community, &me_pk()?)?;
        if community.categories.len() >= super::community::MAX_CATEGORIES {
            return Err(format!("a community holds at most {} categories", super::community::MAX_CATEGORIES));
        }
        let last = community.categories.iter().filter_map(|c| c.position.as_deref()).max_by(|a, b| a.as_bytes().cmp(b.as_bytes()));
        let position = crate::community::rank::between(last, None).ok_or("no room for another category")?;
        let id = super::super::random_32();
        set_category(transport, community, id, &control::CategoryMetadata { name: name.trim().to_string(), position: Some(position), deleted: None, extra: Default::default() }).await?;
        Ok(id)
    })
    .await
}

pub async fn rename_category<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, id: [u8; 32], name: &str) -> Result<(), String> {
    crate::db::scoped(async move {
        ensure_channel_manager(community, &me_pk()?)?;
        let current = community.categories.iter().find(|c| c.id == id).ok_or("no such category")?;
        let meta = control::CategoryMetadata { name: name.trim().to_string(), position: current.position.clone(), deleted: None, extra: current.extra.clone() };
        set_category(transport, community, id, &meta).await
    })
    .await
}

/// Delete a Category: terminal. Its Channels keep pointing at it and render uncategorized.
pub async fn delete_category<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, id: [u8; 32]) -> Result<(), String> {
    crate::db::scoped(async move {
        ensure_channel_manager(community, &me_pk()?)?;
        community.categories.iter().find(|c| c.id == id).ok_or("no such category")?;
        set_category(transport, community, id, &control::CategoryMetadata { deleted: Some(true), ..Default::default() }).await
    })
    .await
}

/// Move a Category to `index` among the Categories (0 is the top).
pub async fn move_category<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, id: [u8; 32], index: usize) -> Result<(), String> {
    crate::db::scoped(async move {
        ensure_channel_manager(community, &me_pk()?)?;
        let current = community.categories.iter().find(|c| c.id == id).ok_or("no such category")?.clone();
        let order: Vec<super::community::CategoryV2> = community.sidebar().into_iter().filter_map(|(c, _)| c.cloned()).filter(|c| c.id != id).collect();
        let keys = keyed(transport, community, order.iter().map(|c| (c.position.clone(), Keyed::Category(c.clone()))).collect()).await?;
        let index = index.min(keys.len());
        let position = crate::community::rank::between(index.checked_sub(1).map(|i| keys[i].as_str()), keys.get(index).map(String::as_str))
            .ok_or("no room between those categories")?;
        let meta = control::CategoryMetadata { name: current.name, position: Some(position), deleted: None, extra: current.extra };
        set_category(transport, community, id, &meta).await
    })
    .await
}

/// Move a Channel into `category` (`None` = uncategorized) at `index` among its
/// Channels: one edition, on the moved Channel (CORD-03 §2).
pub async fn move_channel<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, channel_id: &ChannelId, category: Option<[u8; 32]>, index: usize) -> Result<(), String> {
    crate::db::scoped(async move {
        ensure_channel_manager(community, &me_pk()?)?;
        let ch = community.channel(channel_id).ok_or("no such channel")?.clone();
        if category.is_some_and(|c| !community.categories.iter().any(|x| x.id == c)) {
            return Err("no such category".to_string());
        }
        let sidebar = community.sidebar();
        let group: Vec<ChannelV2> = sidebar
            .iter()
            .find(|(c, _)| c.map(|c| c.id) == category)
            .map(|(_, v)| v.iter().filter(|c| c.id.0 != channel_id.0).map(|c| (*c).clone()).collect())
            .unwrap_or_default();
        let keys = keyed(transport, community, group.iter().map(|c| (c.position().map(String::from), Keyed::Channel(c.clone()))).collect()).await?;
        let index = index.min(keys.len());
        let position = crate::community::rank::between(index.checked_sub(1).map(|i| keys[i].as_str()), keys.get(index).map(String::as_str))
            .ok_or("no room between those channels")?;
        let mut meta = ch.metadata();
        meta.extra.insert("position".into(), position.into());
        match category {
            Some(c) => meta.extra.insert("category".into(), crate::simd::hex::bytes_to_hex_32(&c).into()),
            None => meta.extra.remove("category"),
        };
        edit_channel_metadata(transport, community, channel_id, &meta).await
    })
    .await
}

/// Edit a Channel's name, topic and view, keeping every field another client wrote.
pub async fn edit_channel_details<T: Transport + ?Sized>(
    transport: &T,
    community: &CommunityV2,
    channel_id: &ChannelId,
    name: &str,
    topic: Option<&str>,
    view: super::community::ChannelView,
) -> Result<(), String> {
    let ch = community.channel(channel_id).ok_or("no such channel")?;
    let name = name.trim();
    if name.is_empty() {
        return Err("a channel needs a name".to_string());
    }
    let mut meta = ch.metadata();
    meta.name = name.to_string();
    match topic.map(str::trim).filter(|t| !t.is_empty()) {
        Some(t) => meta.extra.insert("topic".into(), t.into()),
        None => meta.extra.remove("topic"),
    };
    // An unchanged view a later revision defined stays as written.
    match view {
        _ if view == ch.view() && meta.extra.contains_key("view") => None,
        super::community::ChannelView::Chat if ch.voice != Some(true) => meta.extra.remove("view"),
        v => meta.extra.insert("view".into(), v.as_str().into()),
    };
    edit_channel_metadata(transport, community, channel_id, &meta).await
}

/// Create a Channel inside `category` (or uncategorized), at the end of its group.
pub async fn create_channel_in<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, name: &str, private: bool, category: Option<[u8; 32]>) -> Result<ChannelId, String> {
    // Unsynced, a public Channel in a Category with its own rules would sit open to everyone.
    if let Some(cat) = category.filter(|_| !private && roles_v2_held(community)) {
        let roster = crate::db::community::get_community_roles(&crate::simd::hex::bytes_to_hex_32(&community.id().0))?;
        let cat_hex = crate::simd::hex::bytes_to_hex_32(&cat);
        let owner = community.owner()?.to_hex();
        if roster.overwrites.iter().any(|o| o.scope == cat_hex) && !may_swap_overwrites(&roster, Some(&owner), &me_pk()?.to_hex(), &[cat_hex.as_str()], &|_| 0) {
            return Err("this category sets its own permissions, so a channel in it takes Manage Roles over them".to_string());
        }
    }
    let id = if private { create_private_channel(transport, community, name).await? } else { create_public_channel(transport, community, name).await? };
    // A keyless Channel already sorts last in its group.
    if category.is_some() {
        let held = crate::db::community::load_community_v2(community.id())?.ok_or("v2 community not found")?;
        move_channel(transport, &held, &id, category, usize::MAX).await?;
        // A public Channel made inside a Category takes its rules; a private one keeps its own.
        if !private && roles_v2_held(&held) {
            if let Err(e) = set_channel_sync(transport, &held, &id, category).await {
                crate::log_warn!("[v2:sync] the new channel keeps its own rules: {e}");
            }
        }
    }
    Ok(id)
}

/// A sidebar entry a reorder may need to key first.
enum Keyed {
    Channel(ChannelV2),
    Category(super::community::CategoryV2),
}

/// The keys of an ordered group, minting them for keyless entries (a Channel from before
/// positions existed) so a move can land between any two. Each minted key is one edition.
async fn keyed<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, group: Vec<(Option<String>, Keyed)>) -> Result<Vec<String>, String> {
    let mut keys: Vec<String> = Vec::with_capacity(group.len());
    for (key, entry) in group {
        let last = keys.last().map(String::as_str);
        let key = match key {
            Some(k) if last.is_none_or(|l| l.as_bytes() < k.as_bytes()) => k,
            _ => {
                let k = crate::community::rank::between(last, None).ok_or("no room to order these")?;
                match entry {
                    Keyed::Channel(ch) => {
                        let mut meta = ch.metadata();
                        meta.extra.insert("position".into(), k.clone().into());
                        edit_channel_metadata(transport, community, &ch.id, &meta).await?;
                    }
                    Keyed::Category(c) => {
                        set_category(transport, community, c.id, &control::CategoryMetadata { name: c.name, position: Some(k.clone()), deleted: None, extra: c.extra }).await?;
                    }
                }
                k
            }
        };
        keys.push(key);
    }
    Ok(keys)
}

/// Create a new PRIVATE channel (CORD-03 §2): mint a fresh id + an independent
/// random key at channel-epoch 1, mint a companion channel-scoped Role that is
/// the channel's access list (CORD-04 §2), deliver the key to the entitled over
/// the rekey plane (CORD-06 §1), then announce the channel (vsk 2, `private`).
/// Epoch 0 is the root generation ("the first privatisation is epoch 1"), so the
/// delivery commits its continuity to `(0, community_root)` — verifiable by every
/// member and bound to THIS community's root. The key ships BEFORE the
/// announcement: an aborted attempt leaves only an unannounced crate (invisible),
/// and a retry mints a fresh id, so there is no same-coordinate double-mint to
/// fork on. Live public links are refreshed; they carry no private key, so this
/// only re-states the public set.
pub async fn create_private_channel<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, name: &str) -> Result<ChannelId, String> {
    let channel_id = ChannelId(super::super::random_32());
    create_private_channel_with_id(transport, community, name, channel_id).await?;
    Ok(channel_id)
}

/// The companion Role minted alongside a Private channel — the channel's access
/// list (CORD-04 §2 `scope: {"kind":"channel"}`). Same name as the channel, and
/// **no permission bits**: it confers read access, which is key possession, never
/// authority. Position sits below every management role for the same reason.
/// Where channel access roles sit: the bottom, so anyone who can manage roles outranks
/// them and may hand out read access.
pub const ACCESS_ROLE_POSITION: u32 = u32::MAX - 1;

pub fn channel_access_role(channel_id: &ChannelId, name: &str) -> crate::community::roles::Role {
    use crate::community::roles::{Permissions, Role, RoleScope};
    Role {
        role_id: crate::simd::hex::bytes_to_hex_32(&super::super::random_32()),
        name: name.to_string(),
        position: ACCESS_ROLE_POSITION,
        permissions: Permissions::empty(),
        scope: RoleScope::Channel(crate::simd::hex::bytes_to_hex_32(&channel_id.0)),
        color: 0, rank: None, display: false, mentionable: false, extra: Default::default(),
    }
}

/// Who a reader takes a Channel rotation from (CORD-06 §3): the owner, or an unbanned holder of
/// `MANAGE_CHANNELS`, or of `BAN`, which a Refounding rides on and which can cut a member anyway.
pub(crate) fn rotates_channels<'a>(roster: &crate::community::roles::CommunityRoles, owner_hex: &str, banned: impl IntoIterator<Item = &'a String>, rotator_hex: &str) -> bool {
    use crate::community::roles::Permissions;
    rotator_hex == owner_hex
        || (!banned.into_iter().any(|b| b == rotator_hex)
            && (roster.is_authorized(rotator_hex, Some(owner_hex), Permissions::MANAGE_CHANNELS) || roster.is_authorized(rotator_hex, Some(owner_hex), Permissions::BAN)))
}

/// The bit a Channel rotator acts on members under: `MANAGE_CHANNELS` when it holds it, else `BAN`.
pub(crate) fn channel_rotation_bit(roster: &crate::community::roles::CommunityRoles, owner_hex: &str, rotator_hex: &str) -> u64 {
    use crate::community::roles::Permissions;
    if roster.is_authorized(rotator_hex, Some(owner_hex), Permissions::MANAGE_CHANNELS) { Permissions::MANAGE_CHANNELS } else { Permissions::BAN }
}

/// Make a Public Channel private (CORD-03 §2), on Roles v2: mint its own key at the next channel
/// epoch, deliver it to everyone the Channel lets in once private, then publish its first sealed
/// edition, naming this member as its creator and when it stopped being public.
pub async fn privatize_channel<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, channel_id: &ChannelId) -> Result<(), String> {
    crate::db::scoped(async move {
        let lock = super::realtime::follow_lock(community.id());
        let _guard = lock.lock().await;
        let signer = crate::signer::active_signer()?;
        let my_pk = me_pk()?;
        ensure_channel_manager(community, &my_pk)?;
        let community = &crate::db::community::load_community_v2(community.id())?.unwrap_or_else(|| community.clone());
        if !roles_v2_held(community) {
            return Err("making a channel private needs the community on the new roles".to_string());
        }
        let ch = community.channel(channel_id).ok_or("no such channel")?.clone();
        if ch.private {
            return Ok(());
        }
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let chan_hex = crate::simd::hex::bytes_to_hex_32(&channel_id.0);

        // One epoch past any it was private at before, the same one again on a retry.
        let pending_key = format!("v2_privatize:{cid_hex}:{chan_hex}");
        let pending = crate::db::get_sql_setting(pending_key.clone()).ok().flatten().and_then(|v| v.parse::<u64>().ok());
        let epoch = match pending {
            Some(e) => Epoch(e),
            None => {
                let mut top = crate::db::community::held_epoch_keys(&cid_hex, &chan_hex)?.into_iter().map(|(e, _)| e.0).max().unwrap_or(0);
                // An earlier private era may have rotated past what this device ever held. Only a
                // complete rotation a reader would honor takes an epoch: junk at an address doesn't.
                let roots = channel_rekey_addressing_roots(community.community_root, &cid_hex);
                let owner_hex = community.owner()?.to_hex();
                let banned = crate::db::community::get_community_banlist(&cid_hex).unwrap_or_default();
                let probe_roster = crate::db::community::get_community_roles(&cid_hex)?;
                for _ in 0..MAX_VEND_EPOCH_LEAD {
                    let next = Epoch(top.checked_add(1).ok_or("channel epoch overflow")?);
                    let mut taken = false;
                    for root in &roots {
                        let chunks = fetch_rekey_chunks(transport, &community, &channel_rekey_group_key(root, channel_id, next)).await?;
                        taken = rekey::collect_rotations(&chunks).iter().any(|r| {
                            r.scope.id32() == RekeyScope::Channel(*channel_id).id32()
                                && r.new_epoch == next
                                && r.is_complete()
                                && rotates_channels(&probe_roster, &owner_hex, banned.iter(), &r.rotator.to_hex())
                        });
                        if taken {
                            break;
                        }
                    }
                    if !taken {
                        break;
                    }
                    top = next.0;
                }
                let e = Epoch(top.checked_add(1).ok_or("channel epoch overflow")?);
                crate::db::set_sql_setting(pending_key.clone(), e.0.to_string())?;
                e
            }
        };
        let channel_key = mint_or_reuse_rotation_key(&cid_hex, &chan_hex, epoch.0)?;

        // Whom the Channel lets in once private: its rules as they stand, this member as creator.
        let mut roster = crate::db::community::get_community_roles(&cid_hex)?;
        roster.creators.insert(chan_hex.clone(), my_pk.to_hex());
        let owner = community.owner()?;
        let owner_hex = owner.to_hex();
        let mut recipients = vec![my_pk];
        if owner != my_pk {
            recipients.push(owner);
        }
        for pk in access_candidates(community, &roster)? {
            if !recipients.contains(&pk) && roster.is_entitled(Some(&owner_hex), &pk.to_hex(), &chan_hex, &[], &[]) {
                recipients.push(pk);
            }
        }
        let prev_epoch = Epoch(epoch.0 - 1);
        let prev_commit = super::derive::epoch_key_commitment(prev_epoch, &community.community_root);
        let mut blobs = Vec::with_capacity(recipients.len());
        for r in &recipients {
            blobs.push(rekey::build_blob(&signer, &my_pk.to_bytes(), r, RekeyScope::Channel(*channel_id), epoch, &channel_key).await.map_err(|e| e.to_string())?);
        }
        let group = channel_rekey_group_key(&community.community_root, channel_id, epoch);
        let at_ms = now_ms();
        let chunks = rekey::build_rekey_chunks(&signer, my_pk, &group, RekeyScope::Channel(*channel_id), epoch, prev_epoch, &prev_commit, &blobs, at_ms / 1000, my_authority_citation(community, &my_pk).as_ref(), false)
            .await
            .map_err(|e| e.to_string())?;
        for c in &chunks {
            transport.publish_durable(c, &community.relays).await?;
        }

        let mut meta = ch.metadata();
        meta.private = true;
        meta.extra.insert("creator".into(), my_pk.to_hex().into());
        meta.extra.insert("public_until".into(), at_ms.into());
        let prev = channel_head(community, channel_id)?;
        let content = channel_edition_content(community, channel_id, &meta, Some((channel_key, epoch)), prev.as_ref())?;
        publish_control_edition(transport, community, vsk::CHANNEL_METADATA, &channel_id.0, &content).await?;

        if !crate::db::community::community_held(community.id())? {
            return Err("community removed while making the channel private".to_string());
        }
        let mut updated = crate::db::community::load_community_v2(community.id())?.unwrap_or_else(|| community.clone());
        if let Some(held) = updated.channels.iter_mut().find(|c| c.id.0 == channel_id.0) {
            held.private = true;
            held.key = Some(channel_key);
            held.epoch = epoch;
            held.meta_extra = meta.extra.clone();
            held.sealed = sealed_held(&content, prev);
        }
        crate::db::community::save_community_v2(&updated)?;
        let at = crate::db::community::get_community_roles_at(&cid_hex).unwrap_or(0);
        crate::db::community::set_community_roles(&cid_hex, &roster, at)?;
        // Only once it's held: a retry before this reuses the epoch and key it minted.
        let _ = crate::db::set_sql_setting(pending_key, String::new());
        let _ = refresh_public_links(transport, &updated).await;
        Ok(())
    })
    .await
}

/// [`create_private_channel`] with a CALLER-CHOSEN id — the migration-only entry point
/// (§migration) reusing an existing private channel's id so history stitches through.
pub async fn create_private_channel_with_id<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, name: &str, channel_id: ChannelId) -> Result<(), String> {
    crate::db::scoped(async move {
        // Serialize with the follow worker across the whole fetch→publish→save span
        // (the memberlist fetch is seconds long; an unserialized follow adopting a
        // rotation meanwhile would be rolled back by the whole-row save below).
        let lock = super::realtime::follow_lock(community.id());
        let _guard = lock.lock().await;
        let signer = crate::signer::active_signer()?;
        let my_pk = me_pk()?;
        ensure_channel_manager(community, &my_pk)?;
        assert_channel_id_free(&channel_id, community.id())?;
        let v2 = roles_v2_held(community);
        // On Roles v2 the sealed metadata names its creator, who is let in on that (CORD-04 §8).
        let mut extra = serde_json::Map::new();
        if v2 {
            extra.insert("creator".into(), my_pk.to_hex().into());
        }
        let meta = control::ChannelMetadata { name: name.to_string(), private: true, voice: None, deleted: None, custom: None, extra };
        let channel_key = super::super::random_32();
        let epoch = Epoch(1);
        let content = channel_edition_content(community, &channel_id, &meta, Some((channel_key, epoch)), None)?;
        let sealed = control::parse_sealed_channel_meta(&content).map(|s| super::community::SealedMeta { epoch: s.epoch, raw: content.clone(), open: true, junk: false, prev: None });

        // The channel's access list: a companion channel-scoped Role (CORD-04 §2),
        // granted to me so the creator is entitled from the first edition.
        let access_role = channel_access_role(&channel_id, name);
        let access_role_ids = vec![access_role.role_id.clone()];

        // Recipients are the ENTITLED, not the memberlist: CORD-03's private channel
        // is "readable only by granted role-holders". At create that is me (plus the
        // owner, who is always entitled) — everyone else keys up when granted.
        let owner = community.owner()?;
        let mut recipients = vec![my_pk];
        if owner != my_pk {
            recipients.push(owner);
        }
        let prev_commit = super::derive::epoch_key_commitment(Epoch(0), &community.community_root);
        let mut blobs = Vec::with_capacity(recipients.len());
        for r in &recipients {
            blobs.push(
                rekey::build_blob(&signer, &my_pk.to_bytes(), r, RekeyScope::Channel(channel_id), epoch, &channel_key)
                    .await
                    .map_err(|e| e.to_string())?,
            );
        }
        let group = channel_rekey_group_key(&community.community_root, &channel_id, epoch);
        let at_secs = now_ms() / 1000;
        let chunks = rekey::build_rekey_chunks(&signer, my_pk, &group, RekeyScope::Channel(channel_id), epoch, Epoch(0), &prev_commit, &blobs, at_secs, my_authority_citation(community, &my_pk).as_ref(), false)
            .await
            .map_err(|e| e.to_string())?;
        for c in &chunks {
            transport.publish_durable(c, &community.relays).await?;
        }
        publish_control_edition(transport, community, vsk::CHANNEL_METADATA, &channel_id.0, &content).await?;
        if v2 {
            // On Roles v2 a Private Channel is closed to everyone but the owner and its creator
            // until they let a Role or a member in, so it opens nothing before its rules exist.
            let chan = crate::simd::hex::bytes_to_hex_32(&channel_id.0);
            let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
            if !crate::db::community::community_held(community.id())? {
                return Err("community removed during channel create".to_string());
            }
            let mut updated = community.clone();
            updated.channels.push(ChannelV2 { id: channel_id, name: name.to_string(), private: true, key: Some(channel_key), epoch, voice: None, meta_custom: None, meta_extra: meta.extra.clone(), writers: None, sealed: sealed.clone() });
            crate::db::community::save_community_v2(&updated)?;
            crate::db::community::store_epoch_key(&cid_hex, &chan, epoch.0, &channel_key)?;
            // The fold reads the creator back later; until then the stored Roster must let them in.
            let mut roster = crate::db::community::get_community_roles(&cid_hex)?;
            roster.creators.insert(chan.clone(), my_pk.to_hex());
            let at = crate::db::community::get_community_roles_at(&cid_hex).unwrap_or(0);
            crate::db::community::set_community_roles(&cid_hex, &roster, at)?;
            let _ = refresh_public_links(transport, &updated).await;
            return Ok(());
        }
        // Publish the access list AFTER the channel exists, so a peer folding the
        // Role always resolves the channel it scopes to. A failure here leaves a
        // channel only its creator can read — recoverable by re-granting, never a
        // leak.
        set_role(transport, community, &access_role).await?;
        // Judge staff-ness against a roster that HOLDS the role just minted above —
        // no fold has read it back yet, and the access role is permission-less, so
        // resolving it locally both skips a round trip and gets the right answer.
        let mut roster_with_access = crate::db::community::get_community_roles(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap_or_default();
        if roster_with_access.role(&access_role.role_id).is_none() {
            roster_with_access.roles.push(access_role.clone());
        }
        grant_roles_with_roster(transport, community, &my_pk, access_role_ids.clone(), &roster_with_access).await?;
        // The fold is the authority but runs later; without this the creator is not
        // yet entitled to their own channel and the next grant finds no access role.
        merge_local_roster(
            &crate::simd::hex::bytes_to_hex_32(&community.id().0),
            Some(&access_role),
            Some(&crate::community::roles::MemberGrant { member: my_pk.to_hex(), role_ids: access_role_ids }),
        );
        // A leave/delete raced the create: saving would resurrect the community row.
        if !crate::db::community::community_held(community.id())? {
            return Err("community removed during channel create".to_string());
        }
        let mut updated = community.clone();
        updated.channels.push(ChannelV2 { id: channel_id, name: name.to_string(), private: true, key: Some(channel_key), epoch, voice: None, meta_custom: None, meta_extra: Default::default(), writers: None, sealed: sealed.clone() });
        crate::db::community::save_community_v2(&updated)?;
        // Archive the epoch-1 key so this channel's history stays readable across its
        // future rotations (CORD-03 §3).
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        crate::db::community::store_epoch_key(&cid_hex, &crate::simd::hex::bytes_to_hex_32(&channel_id.0), epoch.0, &channel_key)?;
        // Re-state live links. They carry no private key (CORD-05 §2 — a link's
        // audience holds no Role), so this only refreshes the public set.
        let _ = refresh_public_links(transport, &updated).await;
        Ok(())
    })
    .await
}

// ── Receiving a key vend (CORD-03 "delivered on grant") ──────────────────────

/// What a client should do with a vended Private-Channel key right now.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VendVerdict {
    /// Every rule passed — adopt the key.
    Accept,
    /// Cannot judge YET: our fold lags the grant it delivers. Park quietly and
    /// re-judge after the next control follow. NOT an anomaly — a lagging fold
    /// is the normal case for a vend that races its own Grant.
    Park(&'static str),
    /// Judged invalid against evidence that cannot become true later. Alarm-worthy.
    Refuse(&'static str),
}

/// Judge a vended Private-Channel key against our OWN folded state.
///
/// The Grant is the authority half and rides the owner-rooted control plane, so
/// it cannot be forged; the vend is only delivery. Acceptance therefore rests
/// entirely on what our own fold proves — a bundle can never introduce a channel
/// our control plane doesn't define, which is what closes the hidden-channel
/// injection class.
///
/// `community` must already be the held (self-certified) community: the caller
/// resolves it by `community_id`, so a bundle naming a community we're not in is
/// never judged here at all.
pub fn judge_channel_key_vend(
    community: &CommunityV2,
    roster: &crate::community::roles::CommunityRoles,
    channel_id: &ChannelId,
    epoch: Epoch,
    sender_hex: &str,
) -> VendVerdict {
    let me = match me_pk() {
        Ok(pk) => pk.to_hex(),
        Err(_) => return VendVerdict::Park("no active identity"),
    };
    let owner_hex = match community.owner() {
        Ok(o) => o.to_hex(),
        Err(_) => return VendVerdict::Refuse("community has no resolvable owner"),
    };
    let chan_hex = crate::simd::hex::bytes_to_hex_32(&channel_id.0);

    // (2) The channel must exist in OUR fold, and be private there. The bundle's
    // own claims are ignored: a vend may deliver a key, never define a channel.
    let Some(ch) = community.channel(channel_id) else {
        return VendVerdict::Park("channel not in our fold yet");
    };
    if !ch.private {
        // Never heals: our owner-rooted fold says this channel is public, so a
        // "private key" for it is a spoof, not a lagging view.
        return VendVerdict::Refuse("vend names a channel our fold says is public");
    }

    // (5) Epoch sanity, BOTH directions. Below is superseded by the rotation that
    // produced our copy. Above matters more: the channel head is monotonic, so a
    // wildly-ahead epoch is not merely wrong, it is PERMANENT — every genuine
    // rotation afterwards lands at `head + 1`, is refused as stale, and the
    // channel dies for us with no heal path at all (not a rekey, not a re-grant,
    // not a refound). Rotations advance one epoch at a time, so a lead this large
    // is never a delivery we could place.
    if ch.key.is_some() && epoch.0 <= ch.epoch.0 {
        return VendVerdict::Refuse("superseded: we already hold this epoch or newer");
    }
    if epoch.0 > ch.epoch.0.saturating_add(MAX_VEND_EPOCH_LEAD) {
        return VendVerdict::Refuse("vend epoch is implausibly far ahead of the channel head");
    }

    // (3) OUR fold must show US granted a role scoped to this channel. This is
    // the rule that kills the spoof class: an attacker cannot forge the Grant,
    // so they cannot make us accept a key for a channel we were never granted.
    if !roster.is_entitled(Some(&owner_hex), &me, &chan_hex, &[], &[]) {
        return VendVerdict::Park("our grant for this channel has not folded yet");
    }

    // (4) The vendor must be entitled too — they hold the real key, so a wrong
    // key from them costs isolation, never confidentiality. A channel manager may be
    // let in by a creator rule only a holder can read, so they count as one. A banned
    // vendor delivers nothing (CORD-03 §5).
    if PublicKey::from_hex(sender_hex).is_ok_and(|pk| crate::db::community::is_author_banned_in(&community.id().0, &pk)) {
        return VendVerdict::Refuse("vendor is banned");
    }
    let manages = roster.is_authorized(sender_hex, Some(&owner_hex), crate::community::roles::Permissions::MANAGE_CHANNELS);
    if sender_hex != owner_hex && !manages && !roster.is_entitled(Some(&owner_hex), sender_hex, &chan_hex, &[], &[]) {
        return VendVerdict::Park("vendor's entitlement has not folded yet");
    }

    VendVerdict::Accept
}

/// How long an unprovable parked vend is kept. Deliberately long: the fallback
/// heal is the channel's next rotation, which may never come.
const PARKED_VEND_TTL_SECS: u64 = 30 * 24 * 3600;

/// How far above our channel head a vend may claim to be. Generous — a keyless
/// cursor can lag a busy channel by many rotations — but bounded, because the
/// head is monotonic and an over-advance can never be walked back.
const MAX_VEND_EPOCH_LEAD: u64 = 1024;

/// Re-judge every parked key vend for this community and adopt the ones that now
/// pass. Runs after a control follow (the fold moved, so verdicts can change) and
/// on the boot sweep.
///
/// Returns the channels newly keyed up.
pub fn absorb_parked_channel_keys(community: &CommunityV2, session: &std::sync::Arc<crate::db::Session>) -> Vec<ChannelId> {
    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
    let parked = match crate::db::community::get_pending_channel_keys(&cid_hex) {
        Ok(p) if !p.is_empty() => p,
        _ => return Vec::new(),
    };
    let roster = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
    let mut adopted = Vec::new();
    let now = now_ms() / 1000;
    for p in parked {
        // Several candidates may name one channel (parking is open to any sender,
        // so a stranger can never suppress the entitled vendor's key by holding a
        // slot). Once one is seated the rest are moot.
        if adopted.iter().any(|c: &ChannelId| crate::simd::hex::bytes_to_hex_32(&c.0) == p.channel_id) {
            let _ = crate::db::community::drop_pending_channel_key(p.id);
            continue;
        }
        // A vend we were never able to prove is not kept forever: an admin who
        // adds then immediately removes someone leaves a row nothing will ever
        // discharge. Generous by design — the alternative heal (the channel's
        // next rotation) can be arbitrarily far away, so this is hygiene, not a
        // deadline.
        if now.saturating_sub(p.received_at.max(0) as u64) > PARKED_VEND_TTL_SECS {
            let _ = crate::db::community::drop_pending_channel_key(p.id);
            continue;
        }
        let Some(id_bytes) = crate::simd::hex::hex_to_bytes_32_checked(&p.channel_id) else {
            let _ = crate::db::community::drop_pending_channel_key(p.id);
            continue;
        };
        let channel_id = ChannelId(id_bytes);
        match judge_channel_key_vend(community, &roster, &channel_id, Epoch(p.epoch), &p.sender) {
            VendVerdict::Accept => {
                if !session.is_live() {
                    return adopted;
                }
                // First delivery vs rotation. A keyless channel must bypass the
                // monotonic guard: it sits at the epoch-0 cursor, and a peer that
                // mints born-private channels at epoch 0 vends that same epoch, so
                // `new > current` would refuse the only key on offer.
                let keyless = community.channel(&channel_id).is_some_and(|c| c.key.is_none());
                let seated = if keyless {
                    crate::db::community::seat_channel_key(&cid_hex, &p.channel_id, p.epoch, &p.key)
                } else {
                    crate::db::community::advance_channel_epoch(&cid_hex, &p.channel_id, p.epoch, &p.key).map(|_| ())
                };
                if let Err(e) = seated {
                    crate::log_warn!("v2: adopting a vended channel key failed: {e}");
                    continue;
                }
                // The key landed — every other candidate for this channel is moot.
                let _ = crate::db::community::drop_pending_channel_keys_for(&cid_hex, &p.channel_id);
                adopted.push(channel_id);
            }
            VendVerdict::Refuse(why) => {
                crate::log_warn!("v2: refused a vended channel key for {}: {why}", p.channel_id);
                // Only THIS candidate — a sibling may still be the genuine vend.
                let _ = crate::db::community::drop_pending_channel_key(p.id);
            }
            // Quiet by design: the fold simply hasn't caught up.
            VendVerdict::Park(_) => {}
        }
    }
    // A key that just landed may open the channel's sealed metadata.
    if !adopted.is_empty() && session.is_live() {
        if let Ok(Some(mut held)) = crate::db::community::load_community_v2(community.id()) {
            if unseal_held(&mut held) {
                let _ = crate::db::community::save_community_v2(&held);
            }
        }
    }
    adopted
}

/// Grant `member` read access to a Private channel (CORD-03 "delivered on
/// grant"): publish a Grant adding the channel's access role, then vend the key
/// as a CORD-05 §6 Direct Invite whose bundle carries exactly the channels they
/// are now entitled to.
///
/// The Grant is the authority half and rides the owner-rooted control plane, so
/// it cannot be forged; the vend is only delivery. A recipient accepts the key
/// solely on the strength of their OWN fold showing this grant — the bundle can
/// never introduce a channel their control plane doesn't define.
/// This device has folded the community onto Roles v2.
/// What a channel edition carries: on Roles v2 a Private Channel seals its metadata under its
/// key (CORD-03 §2), so only a key holder writes one.
fn channel_edition_content(community: &CommunityV2, channel_id: &ChannelId, meta: &control::ChannelMetadata, key: Option<([u8; 32], Epoch)>, prev: Option<&[u8; 32]>) -> Result<String, String> {
    if !meta.private || !roles_v2_held(community) {
        control::validate_channel_metadata(meta).map_err(|e| e.to_string())?;
        return serde_json::to_string(meta).map_err(|e| e.to_string());
    }
    let (key, epoch) = key.ok_or("you can only edit a private channel you can read")?;
    control::seal_channel_metadata(meta, channel_group_key(&key, channel_id, epoch).conv_key(), epoch.0, prev)
}

/// The head a Channel's next edition builds on, as this device holds it.
fn channel_head(community: &CommunityV2, channel_id: &ChannelId) -> Result<Option<[u8; 32]>, String> {
    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
    Ok(crate::db::community::get_edition_head(&cid_hex, &crate::simd::hex::bytes_to_hex_32(&channel_id.0))?.map(|(_, h)| h))
}

/// What a just-published sealed edition, built on `prev`, leaves this device holding.
fn sealed_held(content: &str, prev: Option<[u8; 32]>) -> Option<super::community::SealedMeta> {
    let s = control::parse_sealed_channel_meta(content)?;
    Some(super::community::SealedMeta { epoch: s.epoch, raw: content.to_string(), open: true, junk: false, prev: prev.map(|p| crate::simd::hex::bytes_to_hex_32(&p)) })
}

/// Whether a Private Channel's metadata needs sealing under the key this device holds now: its
/// head is plain, or sealed under an earlier epoch this device could read.
fn needs_reseal(community: &CommunityV2, ch: &ChannelV2) -> bool {
    ch.private
        && ch.key.is_some()
        && !ch.name.is_empty()
        && match &ch.sealed {
            Some(s) => (s.open && s.epoch < ch.epoch.0) || s.junk,
            None => true,
        }
        && roles_v2_held(community)
}

/// Re-seal a Private Channel's metadata under its current key (CORD-03 §2): the rotator's duty
/// after a rekey, with any manager holding the key as backstop. Returns whether it published.
async fn reseal_channel<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, channel_id: &ChannelId) -> Result<bool, String> {
    // Sealed from the Channel as this device holds it now, so a rename that folded since the
    // caller read it is never written back over.
    let fresh = crate::db::community::load_community_v2(community.id())?.unwrap_or_else(|| community.clone());
    let Some(ch) = fresh.channel(channel_id).or_else(|| community.channel(channel_id)) else { return Ok(false) };
    let ch = ch.clone();
    if !needs_reseal(&fresh, &ch) {
        return Ok(false);
    }
    let meta = control::sanitize_channel_metadata(ch.metadata());
    let prev = channel_head(&fresh, channel_id)?;
    let content = channel_edition_content(&fresh, channel_id, &meta, ch.key.map(|k| (k, ch.epoch)), prev.as_ref())?;
    publish_control_edition(transport, &fresh, vsk::CHANNEL_METADATA, &channel_id.0, &content).await?;
    if let Ok(Some(mut held)) = crate::db::community::load_community_v2(community.id()) {
        if let Some(slot) = held.channels.iter_mut().find(|c| c.id.0 == channel_id.0) {
            slot.sealed = sealed_held(&content, prev);
            crate::db::community::save_community_v2(&held)?;
        }
    }
    Ok(true)
}

/// The reseal backstop (CORD-03 §2): after a rank-staggered wait, seal again what needs it.
/// One Channel's failure never stops the rest.
async fn reseal_backstop<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, roster: &crate::community::roles::CommunityRoles) -> usize {
    let Ok(Some(held)) = crate::db::community::load_community_v2(community.id()) else { return 0 };
    if !held.channels.iter().any(|ch| needs_reseal(&held, ch)) {
        return 0;
    }
    let (Ok(owner), Ok(me)) = (held.owner(), me_pk()) else { return 0 };
    let steps = if me == owner { 0 } else { roster.highest_position(&me.to_hex()).map_or(10, |p| p.saturating_add(1).min(10)) as u64 };
    crate::rt::time::sleep(std::time::Duration::from_millis(2_000 * steps + rand::random::<u64>() % 2_000)).await;
    if !crate::db::current_session().is_live() {
        return 0;
    }
    // Sealed from what the Control Plane says now: another manager's reseal or rename may have landed.
    let (_guard, held) = match follow_fresh(transport, held.id()).await {
        Ok(fresh) => fresh,
        Err(e) => {
            crate::log_warn!("v2: the reseal backstop couldn't read the Control Plane: {e}");
            return 0;
        }
    };
    let mut resealed = 0;
    for ch in held.channels.iter().filter(|c| c.private && c.key.is_some()) {
        match reseal_channel(transport, &held, &ch.id).await {
            Ok(true) => resealed += 1,
            Ok(false) => {}
            Err(e) => crate::log_warn!("v2: resealing a private channel's details failed: {e}"),
        }
    }
    resealed
}

/// The earlier planes of a Channel's history `held` lists or `add` brings, each address once,
/// oldest dropped past the cap; `None` when `add` brings nothing new.
fn merged_history(held: Vec<(Epoch, GroupKey)>, add: Vec<(Epoch, GroupKey)>) -> Option<serde_json::Value> {
    let mut all = held;
    let before = all.len();
    for (epoch, group) in add {
        if !all.iter().any(|(_, g)| g.pk() == group.pk()) {
            all.push((epoch, group));
        }
    }
    if all.len() == before {
        return None;
    }
    all.sort_by_key(|(e, _)| e.0);
    let drop = all.len().saturating_sub(super::community::MAX_HISTORY);
    Some(serde_json::Value::Array(
        all.into_iter().skip(drop).map(|(e, g)| serde_json::json!([e.0, crate::simd::hex::bytes_to_hex_32(&g.secret())])).collect(),
    ))
}

/// The planes of a Private Channel's own epochs this device holds.
fn private_planes(community: &CommunityV2, ch: &ChannelV2) -> Vec<(Epoch, GroupKey)> {
    let (cid_hex, ch_hex) = (crate::simd::hex::bytes_to_hex_32(&community.id().0), crate::simd::hex::bytes_to_hex_32(&ch.id.0));
    let mut keys = crate::db::community::held_epoch_keys(&cid_hex, &ch_hex).unwrap_or_default();
    if let Some(key) = ch.key.filter(|_| ch.private && !keys.iter().any(|(e, _)| *e == ch.epoch)) {
        keys.push((ch.epoch, key));
    }
    keys.into_iter().filter(|(_, k)| *k != community.community_root).map(|(e, k)| (e, channel_group_key(&k, &ch.id, e))).collect()
}

fn history_scan_key(community: &CommunityV2, ch: &ChannelV2) -> String {
    format!("history_scan:{}:{}", crate::simd::hex::bytes_to_hex_32(&community.id().0), crate::simd::hex::bytes_to_hex_32(&ch.id.0))
}

/// What of a public Channel's history this device can hand every member and its metadata doesn't
/// yet (CORD-03 §2): the private epochs it kept, and each past root epoch the Channel wrote
/// under, found from the oldest not yet looked at. With it, the root epoch looked at up to.
async fn owed_history<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, ch: &ChannelV2) -> (Vec<(Epoch, GroupKey)>, Option<u64>) {
    let listed: std::collections::HashSet<PublicKey> = ch.published_history().into_iter().map(|(_, g)| g.pk()).collect();
    let mut owed: Vec<(Epoch, GroupKey)> = private_planes(community, ch).into_iter().filter(|(_, g)| !listed.contains(&g.pk())).collect();
    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
    let from = crate::db::get_sql_setting(history_scan_key(community, ch)).ok().flatten().and_then(|v| v.parse::<u64>().ok()).map_or(0, |s| s + 1);
    let mut roots: Vec<(Epoch, [u8; 32])> = crate::db::community::held_epoch_keys(&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX)
        .unwrap_or_default()
        .into_iter()
        .filter(|(e, _)| e.0 >= from && *e < community.root_epoch)
        .collect();
    roots.sort_by_key(|(e, _)| e.0);
    let written: std::collections::HashSet<u64> = ch.writers.iter().flat_map(|l| l.roots()).map(|e| e.0).collect();
    let mut scanned = None;
    for (epoch, root) in roots {
        let group = channel_group_key(&root, &ch.id, epoch);
        if !listed.contains(&group.pk()) {
            let carries = written.contains(&epoch.0) || {
                let q = Query { kinds: vec![stream::KIND_WRAP], authors: vec![group.pk().to_hex()], limit: Some(1), ..Default::default() };
                match transport.fetch_plane(group.keys(), &q, &community.relays).await {
                    Ok(f) => !f.events.is_empty(),
                    Err(_) => break,
                }
            };
            if carries {
                owed.push((epoch, group));
            }
        }
        scanned = Some(epoch.0);
    }
    (owed, scanned)
}

/// Add `add` to a public Channel's published history (CORD-03 §2), read from the Channel as this
/// device holds it now. Returns whether an edition went out.
async fn publish_history<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, channel_id: &ChannelId, add: Vec<(Epoch, GroupKey)>) -> Result<bool, String> {
    let fresh = crate::db::community::load_community_v2(community.id())?.unwrap_or_else(|| community.clone());
    let Some(ch) = fresh.channel(channel_id).filter(|c| !c.private) else { return Ok(false) };
    let Some(history) = merged_history(ch.published_history(), add) else { return Ok(false) };
    let mut meta = ch.metadata();
    meta.extra.insert(super::community::HISTORY_FIELD.to_string(), history);
    edit_channel_metadata(transport, &fresh, channel_id, &meta).await?;
    Ok(true)
}

/// Make a Private Channel public (CORD-03 §2). While `@everyone` there reads history, the edition
/// publishes the private epochs this device holds, so a member who never held the key reads what
/// was said while it was private.
pub async fn publicize_channel<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, channel_id: &ChannelId) -> Result<(), String> {
    let ch = community.channel(channel_id).ok_or("unknown channel")?;
    if !ch.private {
        return Ok(());
    }
    let mut meta = ch.metadata();
    meta.private = false;
    meta.extra.remove("creator");
    meta.extra.remove("public_until");
    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
    let roster = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
    if roster.everyone_reads_history(&crate::simd::hex::bytes_to_hex_32(&channel_id.0)) {
        if let Some(history) = merged_history(ch.published_history(), private_planes(community, ch)) {
            meta.extra.insert(super::community::HISTORY_FIELD.to_string(), history);
        }
    }
    edit_channel_metadata(transport, community, channel_id, &meta).await
}

type Planes = Vec<(Epoch, GroupKey)>;

/// How often one Channel's history is looked at again by the backstop.
const HISTORY_CHECK_PERIOD_MS: u64 = 60 * 60 * 1000;

/// The history backstop (CORD-03 §2): what this device holds of a public Channel's earlier planes,
/// where `@everyone` reads history and the Channel's metadata doesn't publish them yet, it
/// publishes after a rank-staggered wait. One Channel's failure never stops the rest.
async fn history_backstop<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, roster: &crate::community::roles::CommunityRoles) -> usize {
    struct HistoryChecks;
    type Checks = std::sync::Mutex<std::collections::HashMap<[u8; 32], (u64, Epoch)>>;
    let Ok(Some(held)) = crate::db::community::load_community_v2(community.id()) else { return 0 };
    let checks = crate::db::current_session().scoped::<HistoryChecks, Checks>();
    let now = now_ms();
    let due: Vec<ChannelV2> = {
        let mut last = checks.lock().unwrap_or_else(|e| e.into_inner());
        let due: Vec<ChannelV2> = held
            .channels
            .iter()
            .filter(|ch| !ch.private && roster.everyone_reads_history(&crate::simd::hex::bytes_to_hex_32(&ch.id.0)))
            // A rotation closes an epoch to publish: due at once.
            .filter(|ch| last.get(&ch.id.0).is_none_or(|(t, e)| *e != held.root_epoch || now.saturating_sub(*t) > HISTORY_CHECK_PERIOD_MS))
            .cloned()
            .collect();
        for ch in &due {
            last.insert(ch.id.0, (now, held.root_epoch));
        }
        due
    };
    let mut owed: Vec<(ChannelV2, Planes, Option<u64>)> = Vec::new();
    for ch in due {
        let (add, scanned) = owed_history(transport, &held, &ch).await;
        if add.is_empty() {
            if let Some(s) = scanned {
                let _ = crate::db::set_sql_setting(history_scan_key(&held, &ch), s.to_string());
            }
        } else {
            owed.push((ch, add, scanned));
        }
    }
    if owed.is_empty() {
        return 0;
    }
    let (Ok(owner), Ok(me)) = (held.owner(), me_pk()) else { return 0 };
    let steps = if me == owner { 0 } else { roster.highest_position(&me.to_hex()).map_or(10, |p| p.saturating_add(1).min(10)) as u64 };
    crate::rt::time::sleep(std::time::Duration::from_millis(2_000 * steps + rand::random::<u64>() % 2_000)).await;
    if !crate::db::current_session().is_live() {
        return 0;
    }
    // Published against what the Control Plane says now: another manager may have done it. The
    // edit takes the follow lock itself.
    let fresh = match follow_fresh(transport, held.id()).await {
        Ok((_guard, fresh)) => fresh,
        Err(e) => {
            crate::log_warn!("v2: the history backstop couldn't read the Control Plane: {e}");
            return 0;
        }
    };
    let mut published = 0;
    for (ch, add, scanned) in owed {
        match publish_history(transport, &fresh, &ch.id, add).await {
            Ok(done) => {
                published += done as usize;
                if let Some(s) = scanned {
                    let _ = crate::db::set_sql_setting(history_scan_key(&fresh, &ch), s.to_string());
                }
            }
            Err(e) => crate::log_warn!("v2: publishing a channel's history failed: {e}"),
        }
    }
    published
}

fn roles_v2_held(community: &CommunityV2) -> bool {
    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
    let everyone = crate::simd::hex::bytes_to_hex_32(&super::derive::everyone_locator(community.id()));
    crate::db::community::get_community_roles(&cid_hex).is_ok_and(|r| r.everyone.is_some())
        || crate::db::community::get_edition_head(&cid_hex, &everyone).ok().flatten().is_some()
}

/// On Roles v2 a member's access to one Private Channel is their own overwrite there:
/// View Channel allowed to let them in, denied to keep them out, other bits kept.
async fn member_view_overwrite<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, channel_id: &ChannelId, member: &PublicKey, grant: bool) -> Result<(), String> {
    use crate::community::roles::{OverwriteTarget, Permissions};
    let ch = community.channel(channel_id).ok_or("unknown channel")?;
    if !ch.private {
        return Err("channel is public: every member already reads it".to_string());
    }
    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
    let chan = crate::simd::hex::bytes_to_hex_32(&channel_id.0);
    let target = OverwriteTarget::Member(member.to_hex());
    let roster = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
    let (allow, deny) = roster.overwrites.iter().find(|o| o.scope == chan && o.target == target).map_or((0, 0), |o| (o.allow.0, o.deny.0));
    let v = Permissions::VIEW_CHANNEL;
    let (allow, deny) = if grant { (allow | v, deny & !v) } else { (allow & !v, deny | v) };
    set_overwrite(transport, community, channel_id.0, target, allow, deny).await
}

pub async fn grant_channel_access<T: Transport + ?Sized>(
    transport: &T,
    community: &CommunityV2,
    channel_id: &ChannelId,
    member: &PublicKey,
) -> Result<(), String> {
    if roles_v2_held(community) {
        return member_view_overwrite(transport, community, channel_id, member, true).await;
    }
    crate::db::scoped(async move {
        let my_pk = me_pk()?;
        let ch = community.channel(channel_id).ok_or("unknown channel")?;
        if !ch.private {
            return Err("channel is public — every member already reads it".to_string());
        }
        if ch.key.is_none() {
            return Err("we hold no key for this channel, so we cannot vend it".to_string());
        }
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let chan_hex = crate::simd::hex::bytes_to_hex_32(&channel_id.0);
        let owner_hex = community.owner()?.to_hex();
        // A Grant REPLACES the member's role set, so the union it is built from must
        // be CURRENT: a stale local roster would silently strip every role this
        // client hasn't folded yet. Fetch the authority fresh rather than trusting
        // the cache, and merge the local view on top so a role we just published
        // ourselves (which the plane has but no fold has read back) survives too.
        let view = fetch_authority(transport, community).await;
        let mut roster = view.roles.clone();
        let cached = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
        for r in cached.roles {
            if !roster.roles.iter().any(|x| x.role_id == r.role_id) {
                roster.roles.push(r);
            }
        }
        for g in cached.grants {
            if !roster.grants.iter().any(|x| x.member == g.member) {
                roster.grants.push(g);
            }
        }
        let my_hex = my_pk.to_hex();
        let member_hex = member.to_hex();
        // Reader-gated by MANAGE_ROLES, like any Grant; narrowed to this channel so
        // a channel-scoped manager can run its own access list.
        if !roster.is_authorized_in(&my_hex, Some(&owner_hex), &chan_hex, crate::community::roles::Permissions::MANAGE_ROLES) {
            return Err("not authorized to manage this channel's access".to_string());
        }
        // Rank as well as the bit: the fold drops a Grant aimed at a peer or superior
        // (CORD-04 §2), so publishing one vends a key against a role set no reader
        // will honour. The owner is the exception — never a valid rank target, but a
        // legitimate recipient of a channel key an admin minted.
        if member_hex != owner_hex {
            if !roster.can_act_on_member(&my_hex, Some(&owner_hex), &member_hex, crate::community::roles::Permissions::MANAGE_ROLES) {
                return Err("you do not outrank this member".to_string());
            }
            // A Grant replaces whole — a floored-but-unserved head would publish a
            // wipe. The owner holds no Grant (their authority is implicit), so there
            // is no head to insist on and nothing a first edition could erase.
            require_grant_head(community, &view, &member_hex)?;
        }
        // The channel's roles are ordered by AUTHORITY, so `.first()` is the most
        // privileged — granting read access must never hand out a per-channel
        // moderator role that happens to share the scope. Pick the permission-less
        // one: conferring read access is exactly what carries no authority.
        let role_id = roster
            .channel_roles(&chan_hex)
            .into_iter()
            .find(|r| r.permissions == crate::community::roles::Permissions::empty())
            .map(|r| r.role_id.clone())
            .ok_or("channel has no permission-less access role to grant")?;

        let mut role_ids: Vec<String> = roster.roles_of(&member_hex).map(|r| r.role_id.clone()).collect();
        if !role_ids.contains(&role_id) {
            role_ids.push(role_id.clone());
        }
        // The access role is permission-less (never staff-making), but a KEPT role
        // can be — the fetched roster judges (CORD-04 §3).
        grant_roles_with_roster(transport, community, member, role_ids.clone(), &roster).await?;
        merge_local_roster(&cid_hex, None, Some(&crate::community::roles::MemberGrant { member: member.to_hex(), role_ids }));
        // Settle the vend against the Grant we JUST published — the fold lags it.
        let bundle = bundle_of_with_overlay(
            community,
            BundleAudience::Member(*member),
            Some(my_pk),
            None,
            None,
            std::slice::from_ref(&role_id),
            &[],
        );
        let signer = crate::signer::active_signer()?;
        let wrap = invite::build_direct_invite_signed(&signer, my_pk, member, &bundle).await.map_err(|e| e.to_string())?;
        transport.publish(&wrap, &community.relays).await?;
        Ok(())
    })
    .await
}

/// Revoke `member`'s read access to a Private channel (CORD-03 "rekeyed on
/// removal"): drop the channel's access role from their Grant, then rotate the
/// channel to its next epoch delivering the fresh key to everyone still
/// entitled (CORD-06). The revoked member keeps whatever history they already
/// read — a rekey protects the future, never the past.
pub async fn revoke_channel_access<T: Transport + ?Sized>(
    transport: &T,
    community: &CommunityV2,
    channel_id: &ChannelId,
    member: &PublicKey,
) -> Result<(), String> {
    if roles_v2_held(community) {
        return member_view_overwrite(transport, community, channel_id, member, false).await;
    }
    crate::db::scoped(async move {
        let my_pk = me_pk()?;
        let ch = community.channel(channel_id).ok_or("unknown channel")?;
        if !ch.private {
            return Err("channel is public — there is no access to revoke".to_string());
        }
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let chan_hex = crate::simd::hex::bytes_to_hex_32(&channel_id.0);
        let owner_hex = community.owner()?.to_hex();
        // Same replace-not-merge hazard as the grant: the retained set must be built
        // from a CURRENT roster or this revoke strips roles we simply hadn't folded.
        let view = fetch_authority(transport, community).await;
        let mut roster = view.roles.clone();
        let cached = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
        for r in cached.roles {
            if !roster.roles.iter().any(|x| x.role_id == r.role_id) {
                roster.roles.push(r);
            }
        }
        for g in cached.grants {
            if !roster.grants.iter().any(|x| x.member == g.member) {
                roster.grants.push(g);
            }
        }
        let my_hex = my_pk.to_hex();
        let member_hex = member.to_hex();
        if !roster.is_authorized_in(&my_hex, Some(&owner_hex), &chan_hex, crate::community::roles::Permissions::MANAGE_ROLES) {
            return Err("not authorized to manage this channel's access".to_string());
        }
        if *member == community.owner()? {
            return Err("the owner is supreme and cannot be removed".to_string());
        }
        // Rank as well as the bit, and it matters more here than on the grant side:
        // readers drop the Grant, but the channel rotation below is gated on the
        // citation alone, so an unauthorized revoke still severs its target.
        if !roster.can_act_on_member(&my_hex, Some(&owner_hex), &member_hex, crate::community::roles::Permissions::MANAGE_ROLES) {
            return Err("you do not outrank this member".to_string());
        }
        // A Grant replaces whole — a floored-but-unserved head would publish a wipe.
        require_grant_head(community, &view, &member_hex)?;
        let access_ids = roster.channel_role_ids(&chan_hex);
        // Without the access list this revoke is a no-op that still ROTATES, and the
        // rotation's recipient filter would match nobody — cutting off every
        // legitimately entitled member. Refuse rather than mass-evict.
        if access_ids.is_empty() {
            return Err("this channel's access role has not folded yet — retry once the control plane serves it".to_string());
        }
        let remaining: Vec<String> = roster
            .roles_of(&member_hex)
            .map(|r| r.role_id.clone())
            .filter(|id| !access_ids.contains(id))
            .collect();
        grant_roles_with_roster(transport, community, member, remaining.clone(), &roster).await?;
        merge_local_roster(&cid_hex, None, Some(&crate::community::roles::MemberGrant { member: member.to_hex(), role_ids: remaining }));
        // Rotate so the removal actually severs them (CORD-06 §1). The revoked
        // member is excluded from the recipient set by the overlay, since the fold
        // has not yet caught the Grant we just published.
        rekey_channel_excluding(transport, community, channel_id, &roster, &access_ids, std::slice::from_ref(member)).await
    })
    .await
}

/// Rotate one Private channel to its next epoch, delivering the fresh key to
/// everyone entitled EXCEPT `removed` (CORD-06 §1 single-channel rekey).
///
/// `roster` must be the caller's CURRENT view (fetched, not the local cache):
/// the recipient set is built from it, so a cached roster silently drops every
/// member granted since this client last folded — they keep a dead key with no
/// heal path. `access_ids` is that roster's access-role set for this channel;
/// `removed` is excluded explicitly, since the revoking Grant was published
/// moments ago and no fold has caught it. A batch ban excludes its whole wave
/// in ONE rotation — that is why this takes a slice.
async fn rekey_channel_excluding<T: Transport + ?Sized>(
    transport: &T,
    community: &CommunityV2,
    channel_id: &ChannelId,
    roster: &crate::community::roles::CommunityRoles,
    access_ids: &[String],
    removed: &[PublicKey],
) -> Result<(), String> {
    rekey_channel_at(transport, community, channel_id, roster, access_ids, removed, None).await.map(|_| ())
}

/// [`rekey_channel_excluding`] from the channel as held once the follow lock is ours. With `judged`,
/// only while it still stands at that epoch: false when it moved meanwhile, so the caller re-judges.
async fn rekey_channel_at<T: Transport + ?Sized>(
    transport: &T,
    community: &CommunityV2,
    channel_id: &ChannelId,
    roster: &crate::community::roles::CommunityRoles,
    access_ids: &[String],
    removed: &[PublicKey],
    judged: Option<Epoch>,
) -> Result<bool, String> {
    crate::db::scoped(async move {
        // Whole-row save below — serialize with the follow worker (see create_*_channel).
        let lock = super::realtime::follow_lock(community.id());
        let _guard = lock.lock().await;
        // A rotation from a copy read before the wait would mint an epoch someone already has.
        let held = crate::db::community::load_community_v2(community.id())?.ok_or("v2 community not found")?;
        let community = &held;
        if judged.is_some_and(|e| community.channel(channel_id).map(|c| c.epoch) != Some(e)) {
            return Ok(false);
        }
        let signer = crate::signer::active_signer()?;
        let my_pk = me_pk()?;
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let chan_hex = crate::simd::hex::bytes_to_hex_32(&channel_id.0);
        let ch = community.channel(channel_id).ok_or("unknown channel")?.clone();
        let old_key = ch.key.ok_or("we hold no key for this channel, so we cannot rotate it")?;
        let new_epoch = Epoch(ch.epoch.0.checked_add(1).ok_or("channel epoch overflow")?);
        let owner = community.owner()?;
        let owner_hex = owner.to_hex();

        // Everyone still entitled: the owner (always), me (the rotator must be able
        // to read what it rekeys), and every member the roster shows holding an
        // access role — minus the removals.
        let removed_hexes: std::collections::HashSet<String> = removed.iter().map(|p| p.to_hex()).collect();
        let mut recipients: Vec<PublicKey> = vec![my_pk];
        if owner != my_pk {
            recipients.push(owner);
        }
        if roster.everyone.is_some() {
            // On Roles v2, everyone the Channel resolves View Channel for.
            for pk in access_candidates(community, roster)? {
                let hex = pk.to_hex();
                if removed_hexes.contains(&hex) || hex == owner_hex || recipients.contains(&pk) {
                    continue;
                }
                if roster.is_entitled(Some(&owner_hex), &hex, &chan_hex, &[], &[]) {
                    recipients.push(pk);
                }
            }
        }
        for g in roster.grants.iter().filter(|_| roster.everyone.is_none()) {
            if removed_hexes.contains(&g.member) || g.member == owner_hex {
                continue;
            }
            if !g.role_ids.iter().any(|id| access_ids.contains(id)) {
                continue;
            }
            if let Ok(pk) = PublicKey::parse(&g.member) {
                if !recipients.contains(&pk) {
                    recipients.push(pk);
                }
            }
        }
        // Mint-or-reuse keyed by (channel, next epoch) so a retry after a partial
        // publish re-uses the same key instead of forking the epoch.
        let new_key = mint_or_reuse_rotation_key(&cid_hex, &chan_hex, new_epoch.0)?;
        let prev_commit = super::derive::epoch_key_commitment(ch.epoch, &old_key);
        let mut blobs = Vec::with_capacity(recipients.len());
        for r in &recipients {
            blobs.push(
                rekey::build_blob(&signer, &my_pk.to_bytes(), r, RekeyScope::Channel(*channel_id), new_epoch, &new_key)
                    .await
                    .map_err(|e| e.to_string())?,
            );
        }
        let group = channel_rekey_group_key(&community.community_root, channel_id, new_epoch);
        let at_secs = now_ms() / 1000;
        let chunks = rekey::build_rekey_chunks(&signer, my_pk, &group, RekeyScope::Channel(*channel_id), new_epoch, ch.epoch, &prev_commit, &blobs, at_secs, my_authority_citation(community, &my_pk).as_ref(), false)
            .await
            .map_err(|e| e.to_string())?;
        for c in &chunks {
            transport.publish_durable(c, &community.relays).await?;
        }
        if !crate::db::community::community_held(community.id())? {
            return Err("community removed during channel rekey".to_string());
        }
        // Adopt locally + archive, so our own history reads across the rotation.
        crate::db::community::advance_channel_epoch(&cid_hex, &chan_hex, new_epoch.0, &new_key)?;
        crate::db::community::store_epoch_key(&cid_hex, &chan_hex, new_epoch.0, &new_key)?;

        let mut rotated = community.clone();
        if let Some(c) = rotated.channels.iter_mut().find(|c| c.id == *channel_id) {
            c.key = Some(new_key);
            c.epoch = new_epoch;
        }
        reseal_rotated(transport, &rotated, channel_id).await;
        // The live subscription is addressed by each Channel's epoch, and a rotation this device
        // made itself folds no change a follow would notice: without this it goes deaf in the room.
        if let Some(client) = crate::state::nostr_client() {
            crate::db::spawn_bound(async move { super::realtime::refresh_subscription(&client).await });
        }
        super::realtime::reread_tails(*community.id(), vec![(*channel_id, ch.epoch)]);
        Ok(true)
    })
    .await
}

/// The rotator's duty after minting a Private Channel's epoch (CORD-03 §2, CORD-04 §7): seal its
/// Pin List and metadata again under the new key, which members who join at it hold alone.
/// Best-effort: a failure never fails the rotation, and a manager's duty backs it up.
async fn reseal_rotated<T: Transport + ?Sized>(transport: &T, rotated: &CommunityV2, channel_id: &ChannelId) {
    match read_channel_pins(rotated, channel_id) {
        Ok(read) if !read.sealed && !read.pins.is_empty() => {
            let entries: Vec<super::pins::PinEntry> = read.pins.iter().map(|p| p.entry.clone()).collect();
            if let Some(ch) = rotated.channel(channel_id).cloned() {
                match publish_pin_list(transport, rotated, &ch, &entries).await {
                    Err(e) => crate::log_warn!("[pins] rotation reseal failed (a curator's next edit heals): {e}"),
                    Ok(_) => crate::log_info!("[pins] resealed {} pin(s) under epoch {}", entries.len(), ch.epoch.0),
                }
            }
        }
        Ok(read) if read.sealed => crate::log_warn!("[pins] rotating a channel whose pin list we cannot read; reseal skipped"),
        _ => {}
    }
    if let Err(e) = reseal_channel(transport, rotated, channel_id).await {
        crate::log_warn!("v2: rotation reseal of channel metadata failed (the access duty retries): {e}");
    }
}

/// Rotate every private channel a just-banned member could read (CORD-06 §1 applied
/// per channel). A Public-community Ban skips the Refounding (CORD-05 §5), but the
/// banlist and grant strip alone leave the member holding each private channel's
/// CURRENT epoch key — rotation is the only read severance.
///
/// Takes the whole banned wave: a channel several targets could read rotates ONCE,
/// excluding them all. Per-target rotation would mint N epochs for one ban wave and
/// churn every legitimate reader N times.
///
/// Each target carries its role set as captured before the strip: the fold may or
/// may not have caught the strip yet, and the `with` overlay makes the entitlement
/// judgment independent of that timing.
///
/// Offer-side mirror of the reader's `channel_rotator_ok`: a channel rotation is
/// honored only from `MANAGE_CHANNELS` holders, so a BAN-only moderator must not
/// publish one — locally adopting an epoch every reader rejects forks the channel.
///
/// Best-effort per channel (one failure must not leave the others unrotated);
/// returns how many channels rotated, or the joined failures.
pub async fn sever_banned_private_reads<T: Transport + ?Sized>(
    transport: &T,
    community: &CommunityV2,
    targets: &[(PublicKey, Vec<String>)],
    // The roster as it stood before the ban: on Roles v2 a ban drops its target's own
    // overwrites, so who could read is only answerable from before it.
    before_ban: Option<&crate::community::roles::CommunityRoles>,
) -> Result<usize, String> {
    crate::db::scoped(async move {
        let my_pk = me_pk()?;
        // Readers take a Channel rotation from MANAGE_CHANNELS or BAN (CORD-06 §3).
        ensure_folded_permission(community, &my_pk, crate::community::roles::Permissions::MANAGE_CHANNELS, "severing a banned member's channel reads")
            .or_else(|_| ensure_folded_permission(community, &my_pk, crate::community::roles::Permissions::BAN, "severing a banned member's channel reads"))?;
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let owner_hex = community.owner().ok().map(|o| o.to_hex());
        // On Roles v2 who could read is judged from before the ban, a local read: recorded
        // first, so a rotation the network refuses now is retried until it lands.
        if let Some(before) = before_ban.filter(|b| b.everyone.is_some()) {
            let mut cuts: ReadCuts = Default::default();
            for ch in community.channels.iter().filter(|c| c.private && c.key.is_some()) {
                let chan_hex = crate::simd::hex::bytes_to_hex_32(&ch.id.0);
                let out: std::collections::BTreeSet<String> = targets
                    .iter()
                    .filter(|(pk, stripped)| before.is_entitled(owner_hex.as_deref(), &pk.to_hex(), &chan_hex, stripped, &[]))
                    .map(|(pk, _)| pk.to_hex())
                    .collect();
                if !out.is_empty() {
                    cuts.insert(chan_hex, out);
                }
            }
            add_read_cuts(&cid_hex, cuts);
            return run_read_cuts(transport, community).await;
        }
        // Recipients need the CURRENT entitlement view — fetched, then merged over the
        // cache so entitlements we published ourselves survive a lagging fold (the same
        // two-strand merge as `revoke_channel_access`).
        let fresh = fetch_authority(transport, community).await;
        let v2 = before_ban.is_some_and(|b| b.everyone.is_some()) || fresh.activated;
        // On Roles v2 recipients are whoever the channel resolves View for: a partial read
        // would leave out the very members a rotation must keep.
        if v2 && !fresh.everyone_served {
            return Err("the roster couldn't be read whole, so no channel was rotated yet".to_string());
        }
        let roster = rotation_roster(fresh.roles, &cid_hex);
        let mut rotated = 0usize;
        let mut failures: Vec<String> = Vec::new();
        for ch in &community.channels {
            if !ch.private || ch.key.is_none() {
                continue;
            }
            let chan_hex = crate::simd::hex::bytes_to_hex_32(&ch.id.0);
            // Everyone in the wave who could read this channel, cut in ONE rotation.
            let judge = before_ban.filter(|_| v2).unwrap_or(&roster);
            let excluded: Vec<PublicKey> = targets
                .iter()
                .filter(|(pk, stripped)| judge.is_entitled(owner_hex.as_deref(), &pk.to_hex(), &chan_hex, stripped, &[]))
                .map(|(pk, _)| *pk)
                .collect();
            if excluded.is_empty() {
                continue;
            }
            let access_ids = roster.channel_role_ids(&chan_hex);
            // On the legacy roster entitlement without an access-role set can't happen for
            // a non-owner, and an empty set would make the rotation's recipient filter
            // mass-evict. On Roles v2 recipients are whoever the channel resolves View for.
            if access_ids.is_empty() && !v2 {
                continue;
            }
            // Reload per iteration: each rotation advances the held document, and a
            // stale struct would mint a colliding channel epoch on the next pass.
            let held = match crate::db::community::load_community_v2(community.id()) {
                Ok(Some(c)) => c,
                _ => return Err("community gone during ban severance".to_string()),
            };
            match rekey_channel_excluding(transport, &held, &ch.id, &roster, &access_ids, &excluded).await {
                Ok(()) => rotated += 1,
                Err(e) => failures.push(format!("{}: {e}", &chan_hex[..12])),
            }
        }
        if failures.is_empty() {
            Ok(rotated)
        } else {
            Err(format!("{rotated} rotated; failed: {}", failures.join("; ")))
        }
    })
    .await
}

/// The fetched Roster with what this device holds and the fetch didn't serve merged under it,
/// so entitlements we published ourselves survive a lagging fold.
fn rotation_roster(mut roster: crate::community::roles::CommunityRoles, cid_hex: &str) -> crate::community::roles::CommunityRoles {
    let cached = crate::db::community::get_community_roles(cid_hex).unwrap_or_default();
    for r in cached.roles {
        if !roster.roles.iter().any(|x| x.role_id == r.role_id) {
            roster.roles.push(r);
        }
    }
    for g in cached.grants {
        if !roster.grants.iter().any(|x| x.member == g.member) {
            roster.grants.push(g);
        }
    }
    for o in cached.overwrites {
        if !roster.overwrites.iter().any(|x| x.scope == o.scope && x.target == o.target) {
            roster.overwrites.push(o);
        }
    }
    for (channel, category) in cached.syncs {
        roster.syncs.entry(channel).or_insert(category);
    }
    roster
}

/// Private channels a ban still has to rotate, each with the members to leave out (hex).
type ReadCuts = std::collections::BTreeMap<String, std::collections::BTreeSet<String>>;

fn read_cuts(cid_hex: &str) -> ReadCuts {
    crate::db::settings::get_sql_setting(format!("v2_cut:{cid_hex}"))
        .ok()
        .flatten()
        .and_then(|v| serde_json::from_str(&v).ok())
        .unwrap_or_default()
}

fn store_read_cuts(cid_hex: &str, cuts: &ReadCuts) {
    if let Ok(v) = serde_json::to_string(cuts) {
        let _ = crate::db::settings::set_sql_setting(format!("v2_cut:{cid_hex}"), v);
    }
}

fn add_read_cuts(cid_hex: &str, add: ReadCuts) {
    if add.is_empty() {
        return;
    }
    let mut cuts = read_cuts(cid_hex);
    for (chan, members) in add {
        cuts.entry(chan).or_default().extend(members);
    }
    store_read_cuts(cid_hex, &cuts);
}

pub(crate) fn has_read_cuts(cid_hex: &str) -> bool {
    !read_cuts(cid_hex).is_empty()
}

/// Rotate each pending cut's channel without its members. A cut is dropped once its
/// rotation lands, or once there is nothing left this device could rotate.
async fn run_read_cuts<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> Result<usize, String> {
    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
    let cuts = read_cuts(&cid_hex);
    if cuts.is_empty() {
        return Ok(0);
    }
    let my_pk = me_pk()?;
    if let Err(e) = ensure_folded_permission(community, &my_pk, crate::community::roles::Permissions::MANAGE_CHANNELS, "severing a banned member's channel reads")
        .or_else(|_| ensure_folded_permission(community, &my_pk, crate::community::roles::Permissions::BAN, "severing a banned member's channel reads"))
    {
        store_read_cuts(&cid_hex, &ReadCuts::new());
        return Err(e);
    }
    // Recipients are whoever the channel resolves View for: a partial read would leave out
    // the very members the rotation must keep.
    let fresh = fetch_authority(transport, community).await;
    if !fresh.everyone_served {
        return Err("the roster couldn't be read whole, so no channel was rotated yet; retrying on the next follow".to_string());
    }
    let roster = rotation_roster(fresh.roles, &cid_hex);
    let (mut rotated, mut done, mut failures) = (0usize, Vec::new(), Vec::new());
    for (chan, members) in &cuts {
        let readable = community.channels.iter().any(|c| crate::simd::hex::bytes_to_hex_32(&c.id.0) == *chan && c.private && c.key.is_some());
        let Some(channel) = crate::simd::hex::hex_to_bytes_32_checked(chan).filter(|_| readable) else {
            done.push(chan.clone());
            continue;
        };
        let excluded: Vec<PublicKey> = members.iter().filter_map(|m| PublicKey::from_hex(m).ok()).collect();
        // Reload per iteration: each rotation advances the held document.
        let held = crate::db::community::load_community_v2(community.id())?.ok_or("community gone during ban severance")?;
        match rekey_channel_excluding(transport, &held, &ChannelId(channel), &roster, &roster.channel_role_ids(chan), &excluded).await {
            Ok(()) => {
                rotated += 1;
                done.push(chan.clone());
            }
            Err(e) => failures.push(format!("{}: {e}", &chan[..12])),
        }
    }
    let mut left = read_cuts(&cid_hex);
    for chan in done {
        left.remove(&chan);
    }
    store_read_cuts(&cid_hex, &left);
    if failures.is_empty() {
        Ok(rotated)
    } else {
        Err(format!("{rotated} rotated; failed: {}", failures.join("; ")))
    }
}

/// Retry the rotations this device still owes a community: a ban's cuts and a Role move's
/// settle. Runs outside the follow lock, which every rotation takes.
pub(crate) async fn retry_owed_rotations(id: &crate::community::CommunityId) {
    let Ok(Some(community)) = crate::db::community::load_community_v2(id) else { return };
    let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
    match run_read_cuts(&transport, &community).await {
        Ok(0) => {}
        Ok(n) => crate::log_info!("[Ban] rotated {n} private channel(s) a ban still owed"),
        Err(e) => crate::log_warn!("[Ban] owed private-channel rotation still pending: {e}"),
    }
    let Ok(Some(community)) = crate::db::community::load_community_v2(id) else { return };
    if let Err(e) = run_owed_settle(&transport, &community).await {
        crate::log_warn!("[Roles] owed access settle still pending: {e}");
    }
}

/// Tombstone a channel (CORD-03 §2, `deleted: true`) + drop it locally. Reader-gated by
/// `MANAGE_CHANNELS`; the coordinate stays folded as a grave so peers hide it.
pub async fn delete_channel<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, channel_id: &ChannelId, name: &str) -> Result<(), String> {
    crate::db::scoped(async move {
        // Whole-row save below — serialize with the follow worker (see create_*_channel).
        let lock = super::realtime::follow_lock(community.id());
        let _guard = lock.lock().await;
        let my_pk = me_pk()?;
        ensure_channel_manager(community, &my_pk)?;
        // The tombstone carries the FULL held document (deleted flag set): a strict
        // reader treats an edition as the entity, so even a deletion must not strip
        // fields it didn't touch (CORD-02 §6).
        let mut meta = community.channel(channel_id).map(|c| c.metadata()).unwrap_or_else(|| control::ChannelMetadata {
            name: name.to_string(), private: false, voice: None, deleted: None, custom: None, extra: Default::default(),
        });
        meta.deleted = Some(true);
        // A sealed channel goes with its seal carried verbatim: deleting takes only the bit.
        let content = match community.channel(channel_id).and_then(|c| c.sealed.as_ref()) {
            Some(s) => control::sealed_tombstone(&s.raw).ok_or("this channel's sealed details are malformed")?,
            None => serde_json::to_string(&meta).map_err(|e| e.to_string())?,
        };
        publish_control_edition(transport, community, vsk::CHANNEL_METADATA, &channel_id.0, &content).await?;
        let mut updated = community.clone();
        updated.channels.retain(|c| c.id.0 != channel_id.0);
        crate::db::community::save_community_v2(&updated)?;
        purge::purge_deleted_channel(community, channel_id, Some(my_pk)).await;
        Ok(())
    })
    .await
}

// ── Live control-follow (CORD-02 §6 / CORD-03 §2) ────────────────────────────

/// Re-fold this community's Control Plane and apply the current metadata +
/// **public** channel set to the held community, persisting any change. Called
/// when a control-plane wrap arrives in realtime (a rename, a new channel, an
/// edited description) so a long-running bot tracks the community mid-session
/// instead of freezing at its join-time view.
///
/// **Authority (CORD-04 §5):** the roster (roles/grants/banlist) folds first into
/// the owner-seeded authorized set (`fold_authority`), then each metadata/channel
/// edition is eligible only if its signer CURRENTLY holds the entity's management
/// bit (`MANAGE_METADATA`/`MANAGE_CHANNELS`) — so an authorized admin's edits fold,
/// a demoted one's drop. The owner is supreme, proven by the self-certifying
/// community_id (no network trust).
///
/// **Private channels are skipped here:** a Private channel's Chat-Plane key is
/// delivered over the rekey plane (or an invite bundle), never derivable from a
/// control edition alone. A new Private channel therefore surfaces only once
/// [`follow_rekeys`] delivers its key. Public channels derive from the
/// community_root, so they fold in directly.
///
/// Returns the updated community iff something changed (so the caller can skip a
/// redundant re-subscribe + refresh notification).
/// What a control fold moved. `updated` is the community DOCUMENT (metadata,
/// channels, adopted control root); `authority_changed` is the roster/banlist/
/// registry — which live in their own columns and so are invisible in `updated`.
///
/// The distinction is load-bearing: the rekey walk's authority gates read exactly
/// the state `authority_changed` covers, so a caller that keys its retry off
/// `updated` alone will refuse a rotation on pass 1, silently fix the roster on
/// pass 2, and never look again. That is a permanent strand — and a strand is a
/// fork to everyone else.
#[derive(Debug, Default)]
pub struct ControlFollow {
    pub updated: Option<CommunityV2>,
    pub authority_changed: bool,
}

impl ControlFollow {
    /// Did anything at all move? Either half warrants another rekey walk.
    pub fn moved(&self) -> bool {
        self.updated.is_some() || self.authority_changed
    }
}

/// What a follow of the Control Plane reads and folds before it persists anything.
struct ControlRead {
    floors: Floors,
    editions: Vec<ParsedEdition>,
    authority: AuthoritySet,
    fold: ControlFold,
    /// The read stopped with editions this device tracks still unread.
    truncated: bool,
    pages_read: usize,
    /// Floors a build before marked editions wrote, now on the edition's real hash.
    healed: Vec<HealedFloor>,
    /// Why the last fold refused each role and grant it refused.
    refusals: std::collections::BTreeMap<String, &'static str>,
}

/// A floor that held a marked edition under its unsigned hash, and the edition it names.
struct HealedFloor {
    entity_hex: String,
    version: u64,
    unsigned: [u8; 32],
    self_hash: [u8; 32],
    inner_id: [u8; 32],
    author: [u8; 32],
}

/// A floor written before marked editions (CORD-04 §1) holds the edition's unsigned hash, which
/// no served edition carries any more: its chain reads as a rival at the same version, and every
/// edition resting on its authority stops folding. Only the same edition takes the floor over: its
/// inner id, or its unsigned hash under the signer the floor recorded. A copy re-signed under
/// another key shares that hash, so a floor that recorded no signer heals only to the owner's.
fn heal_unsigned_floors(floors: &mut Floors, owner: Option<[u8; 32]>, editions: &[ParsedEdition], healed: &mut Vec<HealedFloor>) {
    let mut at: crate::fasthash::FastMap<([u8; 32], u64), Vec<&ParsedEdition>> = Default::default();
    for e in editions {
        at.entry((e.entity_id, e.version)).or_default().push(e);
    }
    for (eid, f) in floors.iter_mut() {
        let Some(entity) = crate::simd::hex::hex_to_bytes_32_checked(eid) else { continue };
        let Some(served) = at.get(&(entity, f.0)) else { continue };
        if served.iter().any(|e| held_is(f, e)) {
            continue;
        }
        let same: Vec<&ParsedEdition> = match served.iter().find(|e| f.2 == Some(e.inner_id)) {
            Some(e) => vec![*e],
            None => {
                let Some(signer) = f.3.or(owner) else { continue };
                served
                    .iter()
                    .copied()
                    .filter(|e| e.binding.is_some() && e.author.to_bytes() == signer)
                    .filter(|e| f.4.is_none_or(|fam| fam == crate::db::community::FloorFamily::of(floor_family(&e.vsk))))
                    .filter(|e| crate::community::version::edition_hash(&e.entity_id, e.version, e.prev_hash.as_ref(), e.content.as_bytes()) == f.1)
                    .collect()
            }
        };
        let Some(e) = same.iter().min_by_key(|e| e.inner_id) else { continue };
        if same.iter().any(|o| o.self_hash != e.self_hash) {
            continue;
        }
        let unsigned = f.1;
        f.1 = e.self_hash;
        f.2 = Some(e.inner_id);
        f.3 = Some(e.author.to_bytes());
        if !healed.iter().any(|h| h.entity_hex == *eid) {
            healed.push(HealedFloor { entity_hex: eid.clone(), version: f.0, unsigned, self_hash: e.self_hash, inner_id: e.inner_id, author: e.author.to_bytes() });
        }
    }
}

/// Per-entity refuse-downgrade floors for the CURRENT epoch only. A head recorded under a prior
/// epoch is excluded, so that entity auto-bootstraps after a Refounding (Armada accepts a compacted
/// head across a dangling prev — matched). A read error FAILS CLOSED: an empty map would silently
/// re-open the rollback window the floor exists to shut.
fn held_floors(community: &CommunityV2) -> Result<Floors, String> {
    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
    Ok(crate::db::community::get_all_edition_heads_full(&cid_hex)?
        .into_iter()
        .filter(|(_, f)| f.0 == community.root_epoch.0)
        .map(|(entity, f)| (entity, (f.1, f.2, f.3, f.4, f.5)))
        .collect())
}

impl ControlRead {
    /// A fold with one answer over a whole window: what a live edition may later fold against.
    fn settled(&self) -> bool {
        self.authority.converged && !self.truncated && !self.fold.gapped && !self.authority.gapped
    }
}

/// The fold a follow runs, over editions already in hand. No network, and not truncated: the
/// window it extends was read whole.
fn fold_control_held(community: &CommunityV2, editions: Vec<ParsedEdition>) -> Result<ControlRead, String> {
    let mut floors = held_floors(community)?;
    let mut healed = Vec::new();
    heal_unsigned_floors(&mut floors, community.owner().ok().map(|o| o.to_bytes()), &editions, &mut healed);
    let authority = fold_authority(community, &editions, &floors);
    let refusals = AUTHORITY_REFUSALS.with(|c| c.borrow().clone());
    let fold = apply_control_fold(community, &editions, &floors, &authority);
    Ok(ControlRead { floors, editions, authority, fold, truncated: false, pages_read: 0, healed, refusals })
}

/// A Control Plane window a settled follow read this session, which a live edition folds
/// against instead of re-reading the plane.
#[derive(Clone)]
struct Held {
    epoch: u64,
    /// [`super::realtime::link_generation`] when the read began.
    link: u64,
    editions: Vec<ParsedEdition>,
    /// The owner and everyone the window's Roster grants a Role: nobody else's edition can fold
    /// here, since it would need a grant this window doesn't hold.
    staff: crate::fasthash::FastSet<[u8; 32]>,
    /// Channels the window already deletes.
    deleted: Vec<ChannelId>,
}

struct HeldControl;
type HeldControlMap = std::sync::Mutex<std::collections::HashMap<[u8; 32], Held>>;

fn held_control() -> std::sync::Arc<HeldControlMap> {
    crate::db::current_session().scoped::<HeldControl, HeldControlMap>()
}

/// The most editions a held window keeps: past it, live editions wait for a follow's re-read.
const LIVE_WINDOW_MAX: usize = FOLLOW_PAGE * 2;

/// What a window needs beside its editions to be held: one answer over all of it, with every
/// floored role and grant served.
fn holdable(community: &CommunityV2, read: &ControlRead) -> Option<(crate::fasthash::FastSet<[u8; 32]>, Vec<ChannelId>)> {
    if !read.settled() || !read.authority.complete {
        return None;
    }
    let mut staff: crate::fasthash::FastSet<[u8; 32]> =
        read.authority.roles.grants.iter().filter_map(|g| crate::simd::hex::hex_to_bytes_32_checked(&g.member)).collect();
    staff.extend(community.owner().ok().map(|o| o.to_bytes()));
    Some((staff, read.fold.deleted_channels.clone()))
}

/// Keep a window, or forget one a follow could not settle.
fn hold_control(community: &CommunityV2, window: Option<Held>) {
    let held = held_control();
    let mut held = held.lock().unwrap_or_else(|e| e.into_inner());
    match window.filter(|w| w.editions.len() <= LIVE_WINDOW_MAX) {
        Some(w) => held.insert(community.id().0, w),
        None => held.remove(&community.id().0),
    };
}

/// Our own published edition joins the held window, which its floor has already passed.
fn hold_own(community: &CommunityV2, edition: ParsedEdition) {
    let held = held_control();
    let mut held = held.lock().unwrap_or_else(|e| e.into_inner());
    let Some(w) = held.get_mut(&community.id().0).filter(|w| w.epoch == community.root_epoch.0) else {
        return;
    };
    if edition.vsk == vsk::GRANT {
        let member = super::roles::parse_grant_content(&edition.content).and_then(|g| crate::simd::hex::hex_to_bytes_32_checked(&g.member));
        w.staff.extend(member);
    }
    if !w.editions.iter().any(|e| e.inner_id == edition.inner_id) {
        w.editions.push(edition);
    }
    if w.editions.len() > LIVE_WINDOW_MAX {
        held.remove(&community.id().0);
    }
}

/// Follows reading a community's plane right now, whoever called them: a live fold waits them
/// out, since one that persists after it would write a row from before it.
struct ControlReads;
type ControlReadCounts = std::sync::Mutex<std::collections::HashMap<[u8; 32], usize>>;

struct Reading(std::sync::Arc<ControlReadCounts>, [u8; 32]);

impl Drop for Reading {
    fn drop(&mut self) {
        let mut counts = self.0.lock().unwrap_or_else(|e| e.into_inner());
        if let Some(n) = counts.get_mut(&self.1) {
            *n -= 1;
            if *n == 0 {
                counts.remove(&self.1);
            }
        }
    }
}

fn reading(id: &crate::community::CommunityId) -> Reading {
    let counts = crate::db::current_session().scoped::<ControlReads, ControlReadCounts>();
    *counts.lock().unwrap_or_else(|e| e.into_inner()).entry(id.0).or_default() += 1;
    Reading(counts, id.0)
}

fn being_read(id: &crate::community::CommunityId) -> bool {
    crate::db::current_session().scoped::<ControlReads, ControlReadCounts>().lock().unwrap_or_else(|e| e.into_inner()).contains_key(&id.0)
}

/// A live control wrap, folded in place: the window the last settled follow read plus this
/// edition, through the fold and persist a follow runs. `None` whenever the window may not
/// decide it as a full read would (none held, a read since that may have missed something, an
/// author or a refusal only a read can settle, a new deletion): a full follow then reads the plane.
pub(crate) async fn follow_control_live(community: &CommunityV2, wrap: &Event) -> Option<ControlFollow> {
    crate::db::scoped(async move {
        hold_wrap(community, wrap);
        if being_read(community.id()) {
            return None;
        }
        let held = held_control().lock().unwrap_or_else(|e| e.into_inner()).get(&community.id().0).cloned()?;
        if held.epoch != community.root_epoch.0 || held.link != super::realtime::link_generation() {
            return None;
        }
        let edition = control::ControlPlane::of(community).open_edition(wrap).ok()?;
        if held.editions.iter().any(|e| e.inner_id == edition.inner_id) {
            return Some(ControlFollow::default());
        }
        // A Grant of mine that carries the staff key takes a remote signer to open: not on this
        // path. One that carries none folds here like anyone's, so a Role handed out is known at once.
        let mine = me_pk().is_ok_and(|me| edition.entity_id == super::derive::grant_locator(community.id(), &me.to_bytes()));
        let keyed = mine && super::roles::parse_grant_control_wrap(&edition.content).is_some();
        if keyed || !held.staff.contains(&edition.author.to_bytes()) {
            return None;
        }
        let id = edition.inner_id;
        let Held { epoch, link, mut editions, deleted, .. } = held;
        editions.push(edition);
        let read = fold_control_held(community, editions).ok()?;
        let admitted = read.fold.admitted.contains(&id) || read.authority.admitted.contains(&id) || read.authority.heads.iter().any(|h| h.inner_id == id);
        // A deletion purges history for good: only a full read may decide one.
        if !admitted || read.fold.deleted_channels.iter().any(|c| !deleted.contains(c)) {
            return None;
        }
        let (staff, deleted) = holdable(community, &read)?;
        let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
        let Ok((follow, Some(editions))) = persist_control(&transport, community, read).await else {
            hold_control(community, None);
            return None;
        };
        hold_control(community, Some(Held { epoch, link, editions, staff, deleted }));
        Some(follow)
    })
    .await
}

/// Keep a Control wrap that reached this device outside a read (live, or one it just published),
/// so no relay is asked for it again.
fn hold_wrap(community: &CommunityV2, wrap: &Event) {
    if control_store::mode() == control_store::Mode::Off {
        return;
    }
    if let Err(e) = control_store::View::of(community).absorb(std::slice::from_ref(wrap)) {
        crate::log_warn!("[v2:control {}] a wrap was not kept: {e}", &community.id().to_hex()[..8]);
    }
}

/// What a read decided, each part by name, for telling two reads of one plane apart.
fn read_outcome(read: &ControlRead) -> Vec<(&'static str, String)> {
    let heads = |heads: &[FoldedHead]| {
        let mut all: Vec<String> = heads.iter().map(|h| format!("{}@{}:{}", h.entity_hex, h.version, crate::simd::hex::bytes_to_hex_32(&h.inner_id))).collect();
        all.sort();
        all.join(",")
    };
    let mut deleted: Vec<String> = read.fold.deleted_channels.iter().map(|c| crate::simd::hex::bytes_to_hex_32(&c.0)).collect();
    deleted.sort();
    vec![
        ("control heads", heads(&read.fold.heads)),
        ("roster heads", heads(&read.authority.heads)),
        ("roster", format!("{:?}", read.authority.roles)),
        ("banned", format!("{:?}", read.authority.banned)),
        ("banlist", format!("{:?}", read.authority.banlist_persist)),
        ("gapped", format!("{}/{}", read.fold.gapped, read.authority.gapped)),
        ("settled", format!("{}/{}", read.authority.converged, read.authority.complete)),
        ("community", format!("{:?}", read.fold.updated)),
        ("pins", format!("{:?}", read.fold.pins_persist)),
        ("writers", format!("{:?}", read.fold.writers_persist)),
        ("deleted", deleted.join(",")),
    ]
}

/// Read through the wraps held beside the read by pages a follow just made, and say where the
/// two part. Decides nothing.
async fn shadow_control<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, paged: &ControlRead) {
    let cid = community.id().to_hex();
    let held = match read_control_held(transport, community).await {
        Ok(held) => held,
        Err(Unheld::Paged(why)) => {
            crate::log_warn!("[v2:control {}] shadow: no read through the store ({why})", &cid[..8]);
            return;
        }
        Err(Unheld::NoRelay(_)) => return,
    };
    let has: crate::fasthash::FastSet<[u8; 32]> = held.editions.iter().map(|e| e.inner_id).collect();
    let lost = paged.editions.iter().filter(|e| !has.contains(&e.inner_id)).count();
    let more = has.len().saturating_sub(paged.editions.len() - lost);
    // Two reads owe each other one answer only over the same editions, each having reached one.
    // The store holding more is the point of it: what a relay stops serving is still held.
    let parted: Vec<&'static str> = if lost > 0 || more > 0 || paged.truncated || held.truncated {
        Vec::new()
    } else {
        read_outcome(paged).into_iter().zip(read_outcome(&held)).filter(|(a, b)| a.1 != b.1).map(|(a, _)| a.0).collect()
    };
    if lost > 0 || !parted.is_empty() {
        // The suite run under `VECTOR_CONTROL_SHADOW_STRICT` takes every fixture as an oracle.
        #[cfg(test)]
        if std::env::var_os("VECTOR_CONTROL_SHADOW_STRICT").is_some() {
            let apart: Vec<_> = read_outcome(paged).into_iter().zip(read_outcome(&held)).filter(|(a, b)| a.1 != b.1).collect();
            panic!("the store read differs from the paged read: {lost} edition(s) lost, apart {apart:#?}");
        }
        crate::log_warn!(
            "[v2:control {}] shadow: the store read DIFFERS: {lost} edition(s) only the paged read holds, parts apart {parted:?} (paged {} editions truncated={}, held {} truncated={})",
            &cid[..8], paged.editions.len(), paged.truncated, held.editions.len(), held.truncated
        );
    } else {
        crate::log_warn!(
            "[v2:control {}] shadow: the store read agrees ({} editions held, {more} more than paged, {} paged)",
            &cid[..8], held.editions.len(), paged.editions.len()
        );
    }
}

/// A control read in progress: the editions read so far and the folds over them.
struct Window<'a> {
    community: &'a CommunityV2,
    control: control::ControlPlane,
    cid_hex: String,
    everyone_hex: String,
    owner: Option<[u8; 32]>,
    floors: Floors,
    healed: Vec<HealedFloor>,
    refusals: std::collections::BTreeMap<String, &'static str>,
    editions: Vec<ParsedEdition>,
    seen: crate::fasthash::FastSet<[u8; 32]>,
    seen_wraps: crate::fasthash::FastSet<nostr_sdk::prelude::EventId>,
    fold: ControlFold,
    authority: AuthoritySet,
    /// Every entity some edition in hand speaks for: a page that can't account for everything
    /// tracked folds nothing, since a head needs an edition of its own entity.
    entities: crate::fasthash::FastSet<[u8; 32]>,
    /// How many editions the folds last saw.
    folded: Option<usize>,
}

/// What one page added to a [`Window`].
struct Taken {
    /// Wraps not seen before.
    fresh: usize,
    /// The oldest second among them.
    oldest: Option<u64>,
    /// Fresh wraps that did not open.
    unopened: Vec<nostr_sdk::prelude::EventId>,
}

impl<'a> Window<'a> {
    fn new(community: &'a CommunityV2) -> Result<Window<'a>, String> {
        Ok(Window {
            community,
            control: control::ControlPlane::of(community),
            cid_hex: crate::simd::hex::bytes_to_hex_32(&community.id().0),
            everyone_hex: crate::simd::hex::bytes_to_hex_32(&super::derive::everyone_locator(community.id())),
            owner: community.owner().ok().map(|o| o.to_bytes()),
            floors: held_floors(community)?,
            healed: Vec::new(),
            refusals: Default::default(),
            editions: Vec::new(),
            seen: Default::default(),
            seen_wraps: Default::default(),
            fold: ControlFold::default(),
            authority: AuthoritySet::owner_only(),
            entities: Default::default(),
            folded: None,
        })
    }

    /// Open a page into the window. A wrap seen before is passed over, so a re-served boundary
    /// costs nothing.
    fn take(&mut self, wraps: &[Event]) -> Taken {
        let mut taken = Taken { fresh: 0, oldest: None, unopened: Vec::new() };
        let batch = self.control.check_page(&wraps.iter().filter(|w| !self.seen_wraps.contains(&w.id)).collect::<Vec<_>>());
        for w in wraps {
            if !self.seen_wraps.insert(w.id) {
                continue;
            }
            taken.fresh += 1;
            let at = w.created_at.as_secs();
            if taken.oldest.is_none_or(|o| at < o) {
                taken.oldest = Some(at);
            }
            // Open + seal-verify every edition; authority is resolved by the roster
            // fold (CORD-04 §5), not by a signer filter here — an admin's edits fold.
            match self.control.open_edition(w) {
                Ok(ed) => {
                    if self.seen.insert(ed.inner_id) {
                        self.entities.insert(ed.entity_id);
                        self.editions.push(ed);
                    }
                }
                Err(_) => taken.unopened.push(w.id),
            }
        }
        drop(batch);
        taken
    }

    /// Roster first (roles/grants/banlist → authorized set), then the authority-gated
    /// metadata/channel fold over the same edition set.
    fn fold(&mut self) {
        heal_unsigned_floors(&mut self.floors, self.owner, &self.editions, &mut self.healed);
        if self.folded != Some(self.editions.len()) {
            self.authority = fold_authority(self.community, &self.editions, &self.floors);
            // Taken before any await: the thread-local is this thread's, and the task can move.
            self.refusals = AUTHORITY_REFUSALS.with(|c| c.borrow().clone());
            self.fold = apply_control_fold(self.community, &self.editions, &self.floors, &self.authority);
            self.folded = Some(self.editions.len());
        }
    }

    /// Whether what is in hand is coherent AND complete for everything this device tracks, so
    /// the read may stop. Folds when every tracked entity has an edition here to fold.
    fn enough(&mut self) -> bool {
        let known = crate::db::community::get_community_roles(&self.cid_hex);
        let everyone = super::derive::everyone_locator(self.community.id());
        let reachable = known.as_ref().is_ok_and(|known| {
            (!known.roles.is_empty() || !known.grants.is_empty())
                && (!self.floors.contains_key(&self.everyone_hex) || self.entities.contains(&everyone))
                && known.roles.iter().all(|r| crate::simd::hex::hex_to_bytes_32_checked(&r.role_id).is_some_and(|id| self.entities.contains(&id)))
                && known.grants.iter().all(|g| crate::simd::hex::hex_to_bytes_32_checked(&g.member).is_none_or(|m| self.entities.contains(&super::derive::grant_locator(self.community.id(), &m))))
        });
        if !reachable {
            if let Err(e) = &known {
                crate::log_warn!("[v2:control {}] roster read failed mid-page ({e}) — paging on rather than assuming nothing is tracked", &self.cid_hex[..8.min(self.cid_hex.len())]);
            }
            return false;
        }
        self.fold();
        // "Nothing is gapped" is NOT "I have read enough".
        //
        // An entity we track whose editions are entirely absent from the window
        // folds away silently — absence dangles no link, so it raises no gap. The
        // loop therefore declared the very first page coherent and stopped, and a
        // community whose grants sit older than one page could never re-derive its
        // own roster: every fold offered zero grants, and only the completeness
        // guard retaining the cache kept the admin list alive at all. That made the
        // cache the sole surviving copy of the roster rather than a cache.
        //
        // So keep paging while anything we already know about is still unaccounted
        // for. This only ever reads MORE; it cannot lose data, and it terminates on
        // the page cap or an exhausted plane exactly as before.
        let heads_now = self.authority.settled();
        // A FAILED read must not read as "I track nothing" — that makes
        // "everything is accounted for" trivially true and stops the walk at the
        // first page, which is the exact failure this loop exists to prevent.
        // Fail toward reading MORE.
        let all_accounted = match crate::db::community::get_community_roles(&self.cid_hex) {
            Ok(known) => {
                // A roster we have not built yet accounts for nothing, so
                // "everything I track is present" is vacuously TRUE and stops a
                // COLD device at the first page — caching whatever the newest
                // window happened to hold as its whole baseline, and losing every
                // grant older than one page. The early break is an optimisation
                // for a client that already knows what it is looking for.
                (!known.roles.is_empty() || !known.grants.is_empty())
                    && (!self.floors.contains_key(&self.everyone_hex) || heads_now.contains(self.everyone_hex.as_str()))
                    && known.roles.iter().all(|r| heads_now.contains(r.role_id.as_str()))
                    && known.grants.iter().all(|g| {
                        crate::simd::hex::hex_to_bytes_32_checked(&g.member).is_none_or(|m| {
                            let eid = crate::simd::hex::bytes_to_hex_32(&super::derive::grant_locator(self.community.id(), &m));
                            heads_now.contains(eid.as_str())
                        })
                    })
            }
            Err(e) => {
                crate::log_warn!("[v2:control {}] roster read failed mid-page ({e}) — paging on rather than assuming nothing is tracked", &self.cid_hex[..8.min(self.cid_hex.len())]);
                false
            }
        };
        !(self.fold.gapped || self.authority.gapped) && all_accounted
    }

    /// Whether every stored, floored role and grant has a head in the fold as it stands.
    fn accounted(&self) -> bool {
        let stored = crate::db::community::get_community_roles(&self.cid_hex).unwrap_or_default();
        let heads = self.authority.settled();
        stored.roles.iter().all(|r| !self.floors.contains_key(&r.role_id) || heads.contains(r.role_id.as_str()))
            && stored.grants.iter().all(|g| {
                crate::simd::hex::hex_to_bytes_32_checked(&g.member).is_none_or(|m| {
                    let eid = crate::simd::hex::bytes_to_hex_32(&super::derive::grant_locator(self.community.id(), &m));
                    !self.floors.contains_key(&eid) || heads.contains(eid.as_str())
                })
            })
    }

    fn finish(self, truncated: bool, pages_read: usize) -> ControlRead {
        ControlRead { floors: self.floors, editions: self.editions, authority: self.authority, fold: self.fold, truncated, pages_read, healed: self.healed, refusals: self.refusals }
    }
}

/// Read the Control Plane as deep as a follow does and fold it without persisting: through the
/// wraps held of it once the store is on, else page by page off the relays.
async fn read_control<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> Result<ControlRead, String> {
    if control_store::mode() == control_store::Mode::On {
        match read_control_held(transport, community).await {
            Ok(read) => return Ok(read),
            Err(Unheld::NoRelay(e)) => return Err(e),
            // The store is a saving, never a reason a follow fails.
            Err(Unheld::Paged(why)) => {
                crate::log_warn!("[v2:control {}] read by pages: {why}", &community.id().to_hex()[..8]);
            }
        }
    }
    read_control_paged(transport, community).await
}

/// [`read_control`] page by page off the relays, escalating to Full while anything this device
/// tracks is unaccounted for.
async fn read_control_paged<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> Result<ControlRead, String> {
    let began = crate::rt::time::Instant::now();
    let mut window = Window::new(community)?;
    let address = window.control.pk_hex();
    // Whether this round gave up with editions still unread. The follow is
    // procedural by design — process what arrives, converge with everyone else —
    // so a short read never blocks reading, writing or epoch adoption. It only
    // withholds the ROSTER cache below: caching a partial authority as this
    // device's baseline is the one step that outlives the round.
    let mut truncated = true;
    let mut pages_read = 0usize;
    // Newest window first; page OLDER only while a tracking entity is gapped (its
    // floor link evicted from the window — H1/M8 refetch), bounded like the join
    // verifier. A withholding relay still converges to fail-closed after the cap.
    //
    // Quorum answers as soon as a majority does, so a fast subset that happens not
    // to hold an older edition is indistinguishable from that edition not existing —
    // and the same subset answers every boot, so the retain never lifts and the
    // roster cache freezes with no way back. This fold draws an ABSENCE verdict
    // (`stored_complete`, `truncated`), and CORD-04 §5 makes a gap fail closed FOR
    // THAT ENTITY and refetch. So escalate: read at Quorum, and if anything we
    // already hold is still unaccounted for, read again at Full before concluding.
    // Healthy folds never pay for the second tier.
    for tier in [
        crate::community::transport::Evidence::Quorum,
        crate::community::transport::Evidence::Full,
    ] {
        let mut until: Option<u64> = None;
        let mut oldest: Option<u64> = None;
        truncated = true;
        for _ in 0..FOLLOW_MAX_PAGES {
            pages_read += 1;
            let query = Query { evidence: tier, ..plane_page(address.clone(), FOLLOW_PAGE, until) };
            let wraps = transport.fetch(&query, &community.relays).await?;
            // The `until` cursor is INCLUSIVE (a `-1` step can skip same-second siblings
            // at a page boundary); the wrap-id dedup makes re-served boundary events
            // free, and a page with nothing new means the relay is exhausted.
            let taken = window.take(&wraps);
            oldest = oldest.into_iter().chain(taken.oldest).min();
            if window.enough() {
                truncated = false; // coherent AND complete for everything we track
                break;
            }
            if taken.fresh == 0 {
                // A FULL page with nothing new is a same-second wall no `until` steps
                // past, so older editions stay unreachable; a short page is the end
                // of the plane, and a gap in THAT is the relay withholding, not us
                // giving up early.
                truncated = wraps.len() >= FOLLOW_PAGE;
                break;
            }
            until = oldest;
        }

        window.fold();
        if tier == crate::community::transport::Evidence::Full || window.accounted() {
            break;
        }
        crate::log_debug!(
            "[v2:control {}] stored entit(ies) unaccounted after a Quorum read — re-reading at Full before drawing an absence verdict",
            &window.cid_hex[..8.min(window.cid_hex.len())]
        );
    }

    let read = window.finish(truncated, pages_read);
    crate::log_debug!("[v2:control {}] read by pages: {} edition(s), {pages_read} page(s), truncated={truncated} in {:?}", &community.id().to_hex()[..8], read.editions.len(), began.elapsed());
    Ok(read)
}

/// Why a read did not come through the wraps held.
enum Unheld {
    /// No relay answered: the read fails, as one by pages would.
    NoRelay(String),
    /// Read it by pages instead: the plane is flooded, or the store could not be used.
    Paged(String),
}

/// From a staff device: give each relay the Control wraps it lacks that another relay still
/// holds. Re-publishing a signed wrap needs no key, so any device could; staff are few, so the
/// traffic stays bounded.
async fn heal_control<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, view: &control_store::View, sync: &control_sync::PlaneSync) {
    use control_sync::Held;
    if sync.lacks.values().all(|lack| lack.is_empty()) {
        return;
    }
    let Ok(me) = me_pk() else { return };
    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
    let owner_hex = community.owner().ok().map(|o| o.to_hex());
    let roster = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
    if !roster.is_staff(&me.to_hex(), owner_hex.as_deref()) {
        return;
    }
    let plan = control_sync::plan_heal(community, view, sync).await;
    let id = view.id();
    let work: Vec<(String, Vec<Event>)> = plan
        .into_iter()
        .filter_map(|(relay, ids)| {
            let ids: Vec<[u8; 32]> = ids.iter().map(|id| id.to_bytes()).collect();
            let bodies = crate::db::community::control_wrap_bodies(&cid_hex, &id, &ids).ok()?;
            let wraps: Vec<Event> = bodies.iter().filter_map(|body| std::str::from_utf8(body).ok().and_then(|json| crate::event_json::event(json).ok())).collect();
            (!wraps.is_empty()).then_some((relay, wraps))
        })
        .collect();
    if work.is_empty() {
        return;
    }
    let cid8 = cid_hex[..8].to_string();
    match transport.detached() {
        Some(owned) => {
            crate::db::spawn_bound(async move {
                // Staff devices spread out, so one of them usually gives a relay what it lacks.
                crate::rt::time::sleep(std::time::Duration::from_millis(rand::random::<u64>() % 20_000)).await;
                give_relays(&*owned, &cid8, work).await;
            });
        }
        None => give_relays(transport, &cid8, work).await,
    }
}

async fn give_relays<T: Transport + ?Sized>(transport: &T, cid8: &str, work: Vec<(String, Vec<Event>)>) {
    for (relay, wraps) in work {
        let relays = [relay.clone()];
        let mut kept = 0usize;
        for wrap in &wraps {
            if transport.publish(wrap, &relays).await.is_ok() {
                kept += 1;
            }
        }
        crate::log_info!("[v2:control {cid8}] healed {relay}: {kept} of {} wrap(s) it lacked", wraps.len());
    }
}

/// A fold of the wraps held, and how far down them it read.
struct HeldFold {
    read: ControlRead,
    /// Every stored, floored role and grant has its head.
    accounted: bool,
    /// It read to the end of what is held.
    ended: bool,
    oldest: Option<u64>,
}

/// Fold the wraps held of `view`, newest first, as deep as a follow reads.
fn fold_held(community: &CommunityV2, view: &control_store::View) -> Result<HeldFold, String> {
    let mut window = Window::new(community)?;
    let mut truncated = true;
    let mut pages_read = 0usize;
    let mut below: Option<(u64, nostr_sdk::prelude::EventId)> = None;
    let (mut oldest, mut ended): (Option<u64>, bool) = (None, false);
    for _ in 0..FOLLOW_MAX_PAGES {
        pages_read += 1;
        let wraps = view.page(below, FOLLOW_PAGE)?;
        let taken = window.take(&wraps);
        oldest = oldest.into_iter().chain(taken.oldest).min();
        // Held as an edition that opens: one that no longer does is asked for again.
        for id in &taken.unopened {
            view.forget(id);
        }
        if window.enough() {
            truncated = false;
            break;
        }
        let Some(last) = wraps.last() else {
            (truncated, ended) = (false, true);
            break;
        };
        below = Some((last.created_at.as_secs(), last.id));
    }
    window.fold();
    let accounted = window.accounted();
    Ok(HeldFold { read: window.finish(truncated, pages_read), accounted, ended, oldest })
}

/// [`read_control`] through the wraps held: bring them up to what the relays hold, then fold them.
/// What the relays are asked for grows only while the fold says something is missing.
async fn read_control_held<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> Result<ControlRead, Unheld> {
    use control_sync::{read_whole, sync_plane, Relayed, Wait};
    // Bound before the first await: the floors and the wraps folded after it are this account's.
    crate::db::scoped(async move {
        let view = control_store::View::of(community);
        // Wraps are kept for a community this device holds, and go with it when it is left.
        let kept = || match crate::db::community::community_held(community.id()) {
            Ok(true) => Ok(()),
            _ => Err(Unheld::Paged("the community is not held".into())),
        };
        kept()?;
        if control_sync::flooded(community, &view) {
            return Err(Unheld::Paged("more wraps than a pass reads".into()));
        }
        let synced = |sync: Result<control_sync::PlaneSync, control_sync::Unsynced>| match sync {
            Ok(sync) if sync.flooded => Err(Unheld::Paged("more wraps than a pass reads".into())),
            Ok(sync) => Ok(sync),
            Err(control_sync::Unsynced::NoRelay(e)) => Err(Unheld::NoRelay(e)),
            Err(control_sync::Unsynced::Store(e)) => Err(Unheld::Paged(e)),
        };
        let began = crate::rt::time::Instant::now();
        let mut sync = synced(sync_plane(transport, community, &view, Wait::Quorum).await)?;
        let mut held = fold_held(community, &view).map_err(Unheld::Paged)?;
        let missing = |held: &HeldFold| !held.accounted || held.read.fold.gapped || held.read.authority.gapped;
        if !held.accounted {
            // An absence verdict is next: hear every relay before drawing it.
            let all = synced(sync_plane(transport, community, &view, Wait::All).await)?;
            // What a relay left unread stays unread when it is not there to be asked again.
            let lost = sync.unread && sync.relays.iter().any(|(relay, ended)| *ended == Relayed::Partial && all.relays.get(relay) == Some(&Relayed::Unreached));
            sync = all;
            sync.unread |= lost;
            held = fold_held(community, &view).map_err(Unheld::Paged)?;
        }
        if missing(&held) {
            // A relay's "in sync" is its word, and the fold says something is missing: read them.
            if let Ok(whole) = read_whole(transport, community, &view).await {
                sync.unread |= whole.unread;
                if whole.opened > 0 {
                    held = fold_held(community, &view).map_err(Unheld::Paged)?;
                }
            }
        }
        kept()?;
        heal_control(transport, community, &view, &sync).await;
        let HeldFold { mut read, ended, oldest, .. } = held;
        // A fold that read to the end, or past a second no read can get whole, stands on a partial plane.
        let walled = control_sync::wall(community, &view, Some(&sync)).is_some_and(|wall| ended || oldest.is_some_and(|o| o < wall));
        read.truncated |= sync.unread || walled;
        crate::log_debug!(
            "[v2:control {}] read through {} wrap(s) held, {} new, {} of {} relay(s) answered, truncated={} in {:?}",
            &community.id().to_hex()[..8],
            read.editions.len(),
            sync.opened,
            sync.answered(),
            sync.relays.len(),
            read.truncated,
            began.elapsed()
        );
        Ok(read)
    })
    .await
}

pub async fn follow_control<T: Transport + ?Sized>(
    transport: &T,
    community: &CommunityV2,
) -> Result<ControlFollow, String> {
    crate::db::scoped(async move {
        community.owner()?; // fail fast if the community is somehow unproven.
        let _reading = reading(community.id());
        let link = super::realtime::link_generation();
        let read = match read_control(transport, community).await {
            Ok(read) => read,
            Err(e) => {
                hold_control(community, None);
                return Err(e);
            }
        };
        if control_store::mode() == control_store::Mode::Shadow {
            shadow_control(transport, community, &read).await;
        }
        let keep = holdable(community, &read);
        match persist_control(transport, community, read).await {
            Ok((follow, editions)) => {
                let window = keep.zip(editions).map(|((staff, deleted), editions)| Held { epoch: community.root_epoch.0, link, editions, staff, deleted });
                hold_control(community, window);
                Ok(follow)
            }
            Err(e) => {
                hold_control(community, None);
                Err(e)
            }
        }
    })
    .await
}

/// Persist what a control fold decided: floors, Roster, banlist, registry, pins, writers and
/// the community row. Shared by the follow and the live fold, so both decide alike. Hands the
/// window back when it persisted.
async fn persist_control<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, read: ControlRead) -> Result<(ControlFollow, Option<Vec<ParsedEdition>>), String> {
    {
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let ControlRead { floors, editions, authority, fold, truncated, pages_read, healed, .. } = read;
        // The change feed waits for this fold's own look, after the community row lands.
        let _persisting = super::changes::persist_guard(community.id());

        // The fetches straddled awaits; a swap since the guard was captured must not
        // write account A's control state into B.
        // A leave/delete raced this follow: writing now would resurrect the community
        // row and orphan floor rows past delete_community's wipe.
        if !crate::db::community::community_held(community.id())? {
            return Ok((ControlFollow::default(), None));
        }
        // A floor moved since this read loaded them: its fold is behind the row, so fold again.
        let now = held_floors(community)?;
        if now.iter().any(|(entity, f)| floors.get(entity).is_none_or(|r| f.0 > r.0)) {
            crate::log_info!("[v2:control {}] floors moved during the read; following again", &cid_hex[..8.min(cid_hex.len())]);
            super::realtime::enqueue_follow(community.id());
            return Ok((ControlFollow::default(), None));
        }
        // A healed floor is the same edition under its real hash, whatever this fold makes of it:
        // everything reading the row (sends, citations, the Audit Log) needs that hash too.
        for h in &healed {
            crate::db::community::heal_edition_head(&cid_hex, &h.entity_hex, community.root_epoch.0, h.version, &h.unsigned, &h.self_hash, &h.inner_id, &h.author)?;
        }
        if !healed.is_empty() {
            crate::log_info!("[v2:control {}] {} floor(s) written before marked editions moved to their real hash", &cid_hex[..8.min(cid_hex.len())], healed.len());
        }
        // A Roster fold that ran out its bound has no single answer (CORD-04 §1): every verdict
        // below rests on its last round's guess, so none of it is kept, and the next follow folds again.
        if !authority.converged {
            return Ok((ControlFollow::default(), None));
        }
        // Persist advanced floors BEFORE the state save (a failed floor write must not
        // let saved state outrun its floor), stamping the epoch this fold ran under —
        // not the row's write-time value, which a concurrent re-founding can bump. Both
        // the metadata/channel heads and the roster/banlist heads advance their floors;
        // run the advance (v+1) and same-version convergence (fork tiebreak) paths.
        let families = fold.heads.iter().map(|h| (h, crate::db::community::FLOOR_CONTROL)).chain(authority.heads.iter().map(|h| (h, crate::db::community::FLOOR_AUTHORITY)));
        crate::db::community::write_folded_heads(&cid_hex, |w| {
            for (h, family) in families {
                if h.rebased {
                    w.rebase(&h.entity_hex, h.version, &h.self_hash, &h.inner_id, &h.author, community.root_epoch.0, family)?;
                    continue;
                }
                w.set(&h.entity_hex, h.version, &h.self_hash, &h.inner_id, &h.author, community.root_epoch.0, family)?;
                // The same edition content can arrive under another author's signature (the hash
                // covers content, not signer): it must not re-key a floor that records its author,
                // or a weaker copy lowers the bar a later rival has to beat.
                let rekey = floors.get(&h.entity_hex).is_some_and(|f| f.0 == h.version && f.1 == h.self_hash && f.3.is_some());
                if !rekey {
                    w.converge(&h.entity_hex, h.version, &h.self_hash, &h.inner_id, &h.author, community.root_epoch.0, family)?;
                }
            }
            Ok(())
        })?;
        if super::changes::wanted() {
            let admitted = |id: &[u8; 32]| fold.admitted.contains(id) || authority.admitted.contains(id);
            note_folded_chains(community, &floors, fold.heads.iter().chain(authority.heads.iter()), &editions, admitted);
        }
        // Adopt the staff write key a promotion delivered inside MY OWN Grant
        // (CORD-04 §3): decrypt the control_wrap under the granter↔me pairwise key
        // and record the secret. Verified fail-closed inside — the epoch must be
        // the one I'm on and the secret must derive to exactly the control_pk I
        // hold — so a stale wrap (compaction re-wraps a Grant head verbatim across
        // Refoundings) or a forged one is dropped, never adopted.
        let adopted_control_root = adopt_my_control_wrap(community, &editions).await;
        // The adopt can await a remote signer (bunker NIP-44 round-trip) — re-validate
        // before the per-account writes below.
        // Persist the authorized banlist content (retained/withholding folds carry None,
        // so the stored banlist is left intact — an anti-roster never silently un-bans).
        let mut authority_changed = false;
        // Ban marks MERGE (never replace): they must outlive both the ban and this window,
        // so a later un-ban can't resurrect a pre-ban Join. Persisted even when the banlist
        // itself was retained — the history is what the suppression reads.
        let _ = crate::db::community::merge_community_ban_marks(&cid_hex, &authority.banned_at);
        if let Some((banned, version)) = &authority.banlist_persist {
            let mut before = crate::db::community::get_community_banlist(&cid_hex).unwrap_or_default();
            if crate::db::community::set_community_banlist(&cid_hex, banned, *version as i64)? {
                announce_banlist(&cid_hex);
            }
            let mut after = banned.clone();
            before.sort();
            after.sort();
            authority_changed |= before != after;
        }
        // Persist the authorized roster so capabilities/roles stay sync LOCAL reads
        // (the passive follow folds, reads never fetch). Guarded: only an aggregate
        // built from roster editions at least as new as
        // the stored one may replace it — a withholding relay serving NO roster
        // editions folds an empty-but-ungapped aggregate (absence raises no gap flag),
        // and that must RETAIN the stored roster, never wipe standing.
        let newest_roster_at = roster_stamp(&editions, &authority.heads);
        // Completeness gate: the `gapped` flag only covers entities present in the window.
        // A role/grant floored on this device but with ZERO editions fetched (aged out of
        // the paging reach) folds absent yet raises no gap — persisting would silently drop
        // it. So if any CURRENTLY-STORED entity is floored but folded no head this round,
        // RETAIN. A real revoke still folds a head (see select_authorized), so it persists.
        let stored = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
        let head_ents = authority.settled();
        let stored_complete = stored.roles.iter().all(|r| !floors.contains_key(&r.role_id) || head_ents.contains(r.role_id.as_str()))
            && stored.grants.iter().all(|g| {
                crate::simd::hex::hex_to_bytes_32_checked(&g.member).is_none_or(|m| {
                    let eid = crate::simd::hex::bytes_to_hex_32(&super::derive::grant_locator(community.id(), &m));
                    !floors.contains_key(&eid) || head_ents.contains(eid.as_str())
                })
            });
        // `truncated` covers the case the other three can't: a COLD device (no floors,
        // no stored roster) folding under a plane a member has inflated past the pager.
        // `stored_complete` is trivially true with nothing stored, so without this the
        // first sync would cache a partial authority as its own baseline.
        let stored_at = crate::db::community::get_community_roles_at(&cid_hex)?;
        // `stored_at == 0` is a roster with NO plane provenance: the optimistic local
        // merge every creator writes (`merge_local_roster`) so a just-made role works
        // before its edition folds. It is a guess about the plane, not evidence about
        // it, so it must never out-vote a coherent fold — and it was: the seed names
        // entities the plane no longer heads, `stored_complete` goes false forever, and
        // the roster can never be replaced. A community's OWNER is the likeliest holder
        // of such a seed, so the wedge lands on exactly the account whose rotations
        // everyone else is waiting to adopt.
        let seed_only = stored_at == 0;
        // `stored_complete` retains the cache when a stored entity is floored but folded no
        // head, because a withholding relay looks exactly like that. An entity can also stop
        // producing a head for good (its author demoted, or compacted away), and then the veto
        // holds: a frozen roster refuses rotations from admins promoted since. That is a known
        // fork risk, accepted over the alternative below.
        // NO FLOOR PRUNING. An attempt at it evicted thirteen real admins from a live
        // community: their grant editions were merely outside the fetched window, and
        // "the plane is serving newer editions than mine" is not evidence that a
        // specific entity is gone. A frozen roster is a fork risk; a WRONG roster is a
        // fork plus silent loss of everyone's standing, which is strictly worse. Until
        // there is per-entity proof of absence, absence stays unproven.
        // NOT gated on `authority.gapped`. That flag is a global OR across every
        // entity — its own declaration calls it the per-entity flag that "drives
        // older-paging" — so one unresolvable entity anywhere vetoed the whole roster
        // cache, permanently once the plane is exhausted and more paging cannot help.
        // CORD-04 §5 says a gap fails closed FOR THAT ENTITY, suspending and refetching
        // it, and that already happens: a gapped entity produces no head and so is
        // simply absent from the fold. Freezing every other entity behind it is the
        // over-reach, and it is what left live communities unable to re-derive rosters
        // they could otherwise read perfectly.
        //
        // The downgrade defence is `stored_complete`, which is untouched: nothing we
        // already know can silently vanish. An entity we have never held cannot be
        // stripped from us by its absence.
        // A fold that ran out its bound has no settled answer to cache.
        // A stamp past any clock is an older build's, taken from an unauthorized edition.
        let stamp_ok = newest_roster_at >= stored_at || stored_at > roster_stamp_ceiling();
        if !truncated && authority.converged && (stored_complete || seed_only) && stamp_ok {
            authority_changed |= stored != authority.roles;
            crate::db::community::set_community_roles(&cid_hex, &authority.roles, newest_roster_at)?;
        } else {
            // Loud, because the failure mode is silent and total: the roster is what
            // authorizes every rotation, so a client that can never re-cache it is
            // permanently deaf to that admin's re-foundings — and the only symptom is
            // an epoch that never advances.
            // Name the BLOCKERS and what the fold actually found. Without these the
            // warning says a decision was made but not on what evidence, which is how
            // a wrong roster stays indistinguishable from a cautious one.
            let mut blockers: Vec<String> = Vec::new();
            for r in &stored.roles {
                if floors.contains_key(&r.role_id) && !head_ents.contains(r.role_id.as_str()) {
                    blockers.push(format!("role:{}", &r.role_id[..8.min(r.role_id.len())]));
                }
            }
            for g in &stored.grants {
                if let Some(m) = crate::simd::hex::hex_to_bytes_32_checked(&g.member) {
                    let eid = crate::simd::hex::bytes_to_hex_32(&super::derive::grant_locator(community.id(), &m));
                    if floors.contains_key(&eid) && !head_ents.contains(eid.as_str()) {
                        blockers.push(format!("grant:{}", &g.member[..8.min(g.member.len())]));
                    }
                }
            }
            // Per-entity fate of every roster edition in the window. "Blocked" only
            // says which stored entity produced no head; this says WHY — whether its
            // editions were absent, or present and dropped, and by whom they were
            // authored. Guessing between those three cost a day.
            {
                use std::collections::BTreeMap;
                let mut fate: BTreeMap<String, (u64, u64, String, &str)> = BTreeMap::new();
                for e in &editions {
                    if e.vsk != vsk::ROLE && e.vsk != vsk::GRANT {
                        continue;
                    }
                    let kind = if e.vsk == vsk::ROLE { "role" } else { "grant" };
                    let eid = crate::simd::hex::bytes_to_hex_32(&e.entity_id);
                    let slot = fate.entry(eid).or_insert((0, 0, String::new(), kind));
                    slot.0 += 1;
                    if e.version > slot.1 {
                        slot.1 = e.version;
                        slot.2 = e.author.to_hex()[..8].to_string();
                        slot.3 = kind;
                    }
                }
                let head_now: std::collections::HashSet<&str> =
                    authority.heads.iter().map(|h| h.entity_hex.as_str()).collect();
                let rows: Vec<String> = fate
                    .iter()
                    .map(|(eid, (n, v, author, kind))| {
                        format!(
                            "{}[{kind}]:{}ed/v{}/by{}{}{}",
                            &eid[..8], n, v, author,
                            if authority.carried.contains(eid.as_str()) {
                                "/HEAD(kept: refused, nothing to fall back to)".to_string()
                            } else if head_now.contains(eid.as_str()) {
                                "/HEAD".to_string()
                            } else {
                                AUTHORITY_REFUSALS
                                    .with(|c| c.borrow().get(eid.as_str()).copied())
                                    .map(|r| format!("/DROPPED({r})"))
                                    .unwrap_or_else(|| "/dropped(no candidate survived the fold)".into())
                            },
                            floors.get(eid).map(|f| format!("/floor@v{}", f.0)).unwrap_or_default(),
                        )
                    })
                    .collect();
                // The OWNER is the root of all authority: every other author needs a
                // grant that traces back to them. If no edition here is owner-authored
                // the chain cannot bootstrap at all, and that is a different bug from
                // any individual entity being rejected.
                crate::log_warn!(
                    "[v2:control {}] fold accepted roles: [{}]",
                    &cid_hex[..8.min(cid_hex.len())],
                    authority.roles.roles.iter().map(|r| format!("{}@pos{}", &r.role_id[..8.min(r.role_id.len())], r.position)).collect::<Vec<_>>().join(" ")
                );
                crate::log_warn!(
                    "[v2:control {}] owner={} — roster editions in window: [{}]",
                    &cid_hex[..8.min(cid_hex.len())],
                    community.owner().map(|o| o.to_hex()[..8].to_string()).unwrap_or_else(|_| "UNPROVEN".into()),
                    rows.join(" ")
                );
            }
            crate::log_warn!(
                "[v2:control {}] roster NOT cached (truncated={} authority_gapped={} doc_gapped={} stored_complete={} newest_roster_at={} stored_at={}) — stored {}r/{}g, fold offers {}r/{}g from {} edition(s) over {} page(s), blocked by [{}]",
                &cid_hex[..8.min(cid_hex.len())], truncated, authority.gapped, fold.gapped, stored_complete, newest_roster_at, stored_at,
                stored.roles.len(), stored.grants.len(), authority.roles.roles.len(), authority.roles.grants.len(),
                editions.len(), pages_read,
                blockers.join(", ")
            );
        }
        // Cache the folded invite Registry so Public/Private stays a sync LOCAL read
        // (`invite_registry` is the column every caller reads). Gated like
        // the roster: a truncated or gapped window folds an empty registry out of mere
        // absence, and persisting that under-states Public — the unsafe direction, since
        // it leaves a live link open behind a ban.
        if !truncated && !authority.gapped && !fold.gapped {
            if let Ok(owner) = community.owner() {
                let sets = live_invite_link_sets(community.id(), &owner.to_hex(), &editions, &authority, &floors);
                let live = flatten_link_sets(&sets);
                let mut before = crate::db::community::get_community_invite_registry(&cid_hex).unwrap_or_default();
                before.sort();
                if before != live {
                    crate::db::community::set_community_invite_registry(&cid_hex, &live)?;
                    authority_changed = true;
                }
                // The per-creator split drives "X has N active invite links" and the
                // first-link-flips-Public confirm; it lives in its own table.
                crate::db::community::replace_invite_link_sets(&cid_hex, &sets)?;
            }
        }
        // Folded Pin List heads (CORD-04 §7): raw content per channel. The write
        // itself is monotonic on version (atomic in the statement), so a stale
        // window racing a publish echo can never regress a newer held head.
        for (channel_hex, content, version, rebased) in &fold.writers_persist {
            persist_writers(&cid_hex, channel_hex, content, *version, *rebased);
        }
        for (channel_hex, content, version, author_npub, created_at) in &fold.pins_persist {
            match crate::db::community::set_community_pins(&cid_hex, channel_hex, content, *version as i64) {
                Ok(true) => {
                    crate::log_info!("[pins] fold adopted v{} for channel {}", version, &channel_hex[..12]);
                    crate::emit_event(
                        "community_pins_updated",
                        &serde_json::json!({ "community_id": cid_hex, "channel_id": channel_hex }),
                    );
                    note_pins_modified(channel_hex, *version, author_npub, *created_at).await;
                }
                Ok(false) => {}
                Err(e) => crate::log_warn!("[pins] fold persist failed: {e}"),
            }
        }
        // Roster/banlist moves are invisible in the returned community (they live in
        // their own columns), so callers that key a refresh off `updated` would never
        // repaint a promote/demote/ban. Announce from the single fold point — it covers
        // realtime, boot catch-up and manual sync alike.
        if authority_changed {
            crate::emit_event("community_refreshed", &serde_json::json!({ "community_id": cid_hex }));
        }
        // Owner-side silent Admin widening (PIN_MESSAGES): after the roster has
        // folded, so the check reads the settled roles. Once per community per
        // session — the fold runs constantly and the upgrade is a one-shot.
        if first_admin_pin_upgrade(community.id()) {
            let _ = upgrade_admin_role_pin_bit(transport, community).await;
        }
        // The pins/upgrade tail awaited network I/O — re-validate before the vault save.
        // An adopted staff key rides whatever gets saved (the fold's update, or the
        // otherwise-unchanged community) — the vault write that makes it durable.
        // Kicks and snapshots are judged on the Roster, citations and minter this fold may have moved.
        crate::db::community::bump_membership_generation();
        let mut updated = fold.updated;
        if let Some(cr) = adopted_control_root {
            let mut u = updated.take().unwrap_or_else(|| community.clone());
            u.control_root = Some(cr);
            updated = Some(u);
        }
        resume_relay_copy(community);
        crate::community::message_delete::resume_scrubs();
        let follow = match updated {
            Some(u) => {
                crate::db::community::save_community_v2(&u)?;
                if u.relays != community.relays {
                    relays_moved(community, &u);
                }
                ControlFollow { updated: Some(u), authority_changed }
            }
            None => ControlFollow { updated: None, authority_changed },
        };
        for channel_id in &fold.deleted_channels {
            purge::purge_deleted_channel(community, channel_id, None).await;
        }
        Ok((follow, Some(editions)))
    }
}

/// Tell the change feed which editions each advanced head moved through, walking its chain back
/// to the floor this fold started from, so a change several people made credits each of them.
fn note_folded_chains<'a>(community: &CommunityV2, floors: &Floors, heads: impl Iterator<Item = &'a FoldedHead>, editions: &[ParsedEdition], admitted: impl Fn(&[u8; 32]) -> bool) {
    // Only what the fold authorized: the same content can arrive re-signed by someone else.
    let by_hash: std::collections::HashMap<[u8; 32], &ParsedEdition> = editions.iter().filter(|e| admitted(&e.inner_id)).map(|e| (e.self_hash, e)).collect();
    let by_id: std::collections::HashMap<[u8; 32], &ParsedEdition> = editions.iter().map(|e| (e.inner_id, e)).collect();
    for h in heads.filter(|h| !h.rebased) {
        let floor = floors.get(&h.entity_hex).map_or(0, |f| f.0);
        if h.version <= floor {
            continue;
        }
        let mut chain = Vec::new();
        // The head is the edition the fold chose, by its own id; what it cites is walked by hash.
        let mut next = by_id.get(&h.inner_id).copied();
        while let Some(ed) = next {
            if ed.version <= floor || chain.len() > 64 {
                break;
            }
            chain.push((ed.version, ed.author, ed.created_at));
            next = ed.prev_hash.and_then(|hash| by_hash.get(&hash).copied());
        }
        chain.reverse();
        super::changes::note_folded(community.id(), &h.entity_hex, chain);
    }
}

/// Adopt the `control_root` a staff-making Grant delivered to ME (CORD-04 §3).
///
/// Nothing to adopt on a legacy epoch (no write key exists) or when the secret
/// is already held. Candidate editions are MY grant coordinate's, newest
/// version first; authority-gating them is unnecessary for adoption — the
/// derive check IS the gate (only the true secret derives to the held
/// `control_pk`, so the worst a forged edition can do is fail it). The epoch
/// rides inside the ciphertext because staleness is structural: compaction
/// re-wraps a Grant head verbatim across Refoundings, and staff crossing a
/// rotation get the new secret in their 136-byte base blob instead.
async fn adopt_my_control_wrap(community: &CommunityV2, editions: &[ParsedEdition]) -> Option<[u8; 32]> {
    use nostr_sdk::prelude::AsyncNip44;
    let held_pk = community.control_pk?;
    if community.control_root.is_some() {
        return None;
    }
    let my_pk = me_pk().ok()?;
    let signer = crate::signer::active_signer().ok()?;
    let my_eid = super::derive::grant_locator(community.id(), &my_pk.to_bytes());
    let mut candidates: Vec<&ParsedEdition> = editions
        .iter()
        .filter(|e| e.vsk == vsk::GRANT && e.entity_id == my_eid)
        .collect();
    candidates.sort_by_key(|e| std::cmp::Reverse(e.version));
    for ed in candidates {
        let Some(wrap_b64) = super::roles::parse_grant_control_wrap(&ed.content) else { continue };
        // The granter is the edition's sealed author — the pairwise key's other
        // half (one ECDH either side can compute; bunker accounts included).
        let Ok(plain_b64) = signer.nip44_decrypt_async(&ed.author, &wrap_b64).await else { continue };
        let Ok(plain) = crate::simd::base64::STANDARD.decode_to_vec(plain_b64.as_bytes()) else { continue };
        let Ok((epoch, root)) = super::rekey::parse_control_wrap(&plain) else { continue };
        if epoch != community.root_epoch {
            continue;
        }
        if super::derive::control_signer_group_key(&root, community.id(), epoch).pk() != held_pk {
            continue;
        }
        crate::log_info!("[v2] adopted the staff write key from my Grant (epoch {})", epoch.0);
        return Some(root);
    }
    None
}

/// Control-follow paging bounds: enough depth to re-anchor a long-offline floor
/// (H1/M8 refetch) without letting a flooding relay stall the follow queue.
///
/// Nearly free to raise: both follow loops exit the moment the fold stops being
/// gapped, so the cap only binds when something is genuinely missing — exactly
/// when paging further is what's wanted. The old ceiling of 4 (~2k editions) sat
/// under a plane that 100 roles + 400 grants already outgrows before counting
/// superseded versions, which accumulate until a compaction retires them.
/// One walk's hop bound. A backlog deeper than this converges across passes,
/// because every adopted hop is checkpointed before the next is attempted.
const MAX_WALK_STEPS: usize = 128;
const FOLLOW_MAX_PAGES: usize = 32;
const FOLLOW_PAGE: usize = 500;

/// One page of a plane walked from its newest wrap down, `until` inclusive. Every such walk asks
/// through here: a page read from several relays is only whole down to where the shallowest of
/// them stopped, and `paged` has the transport cut it there.
fn plane_page(address: String, limit: usize, until: Option<u64>) -> Query {
    Query { kinds: vec![stream::KIND_WRAP], authors: vec![address], until, limit: Some(limit), paged: true, ..Default::default() }
}

/// Page ceiling for a COMPACTION read (CORD-06 §3: a Refounder that cannot fold
/// every Control Event must abort). Far above any real plane, but plane depth is
/// attacker-controlled — any member holds the key that mints wraps — so the read
/// is bounded and reports coming up short rather than compacting a partial view.
const COMPACT_MAX_PAGES: usize = 512;

/// A folded control head to persist as the per-entity refuse-downgrade floor.
#[derive(Clone)]
struct FoldedHead {
    entity_hex: String,
    version: u64,
    self_hash: [u8; 32],
    inner_id: [u8; 32],
    author: [u8; 32],
    /// The held floor's head is served and the Roster now refuses it: this is the newest
    /// edition it does admit, below the floor, and the floor moves down to it.
    rebased: bool,
}

/// The outcome of a floor-aware control fold: the updated community (if content
/// changed), the heads to persist as the new floor (returned even when content is
/// unchanged, so the floor still seeds/advances), and whether any TRACKING entity
/// hit an unresolvable gap — the caller's signal to page older history and re-fold
/// (CORD-04 H1/M8's refetch).
#[derive(Default)]
struct ControlFold {
    updated: Option<CommunityV2>,
    heads: Vec<FoldedHead>,
    gapped: bool,
    /// Folded Pin List heads to persist:
    /// `(channel_hex, raw content, version, author_npub, created_at)`.
    /// Raw carried bytes on purpose — republishing must not re-serialize.
    pins_persist: Vec<(String, String, u64, String, u64)>,
    /// Folded Writers ledger heads to persist: `(channel_hex, raw content, version, rebased)`.
    writers_persist: Vec<(String, String, u64, bool)>,
    /// Channels a standing deletion took out, whose history every device drops.
    deleted_channels: Vec<ChannelId>,
    /// Entities whose held edition the Roster now refuses with no authorized edition to step
    /// down to: this device keeps it as its head, but nobody new would fold it.
    kept: std::collections::HashSet<String>,
    /// Every edition this fold found authorized, by inner id.
    admitted: crate::fasthash::FastSet<[u8; 32]>,
}

/// Per-entity floor: `(version, self_hash, inner_id, author, family)` of the committed head. The id
/// and author are its fork tiebreak key; either is `None` on a row written before it was recorded,
/// as the family is on a row that records none.
type Floor = (u64, [u8; 32], Option<[u8; 32]>, Option<[u8; 32]>, Option<crate::db::community::FloorFamily>);

/// An author's authority in an equal-version fork (CORD-04 §1), lower outranking: the owner, then
/// the lowest role position, then the roleless.
fn fork_rank(roles: &crate::community::roles::CommunityRoles, owner_hex: Option<&str>, author_hex: &str) -> u32 {
    if owner_hex == Some(author_hex) {
        return 0;
    }
    roles.highest_position(author_hex).unwrap_or(u32::MAX)
}

/// [`fork_rank`] over an index of the roster.
fn fork_rank_in(roles: &crate::community::roles::RoleIndex<'_>, owner_hex: Option<&str>, author_hex: &str) -> u32 {
    if owner_hex == Some(author_hex) {
        return 0;
    }
    roles.highest_position(author_hex).unwrap_or(u32::MAX)
}

/// The held floor's fork key, ranked against the roster the caller folds with.
enum HeldKey {
    /// No tiebreak was recorded for the held head: any same-version rival may replace it.
    Replaceable,
    /// Recorded before authors were: rivals compare by id alone.
    Id([u8; 32]),
    Ranked(u32, [u8; 32]),
}

impl HeldKey {
    fn of(floor: &Floor, rank_of: &dyn Fn(&[u8; 32]) -> u32) -> Self {
        match (floor.2, floor.3) {
            (None, _) => HeldKey::Replaceable,
            (Some(id), None) => HeldKey::Id(id),
            (Some(id), Some(author)) => HeldKey::Ranked(rank_of(&author), id),
        }
    }

    /// Whether a same-version rival takes the floor from the held head.
    fn beaten_by(&self, rank: u32, id: &[u8; 32]) -> bool {
        match self {
            HeldKey::Replaceable => true,
            HeldKey::Id(held) => id < held,
            HeldKey::Ranked(held_rank, held) => (rank, id) < (*held_rank, held),
        }
    }
}
type Floors = crate::fasthash::FastMap<String, Floor>;

/// Which fold an edition kind's floor belongs to.
fn floor_family(vsk_code: &str) -> &'static str {
    use crate::db::community::{FLOOR_AUTHORITY, FLOOR_CONTROL};
    match vsk_code {
        vsk::ROLE | vsk::ROLE_V2 | vsk::GRANT | vsk::BANLIST | vsk::TENURE | vsk::CHANNEL_ACL | vsk::CHANNEL_SYNC => FLOOR_AUTHORITY,
        _ => FLOOR_CONTROL,
    }
}

/// `floors` without the rows another fold recorded: a row's coordinate can be squatted by
/// an edition of another kind, whose floor means nothing to this one.
fn floors_of_family(floors: &Floors, family: &str) -> Floors {
    let family = crate::db::community::FloorFamily::of(family);
    floors.iter().filter(|(_, f)| f.4.is_none_or(|f| f == family)).map(|(k, f)| (k.clone(), *f)).collect()
}

/// Fold owner-authored control editions into an updated community using the
/// PERSISTED per-entity version floor (refuse-downgrade). Per entity, fold with
/// [`version::fold`]`(floor, floor_hash)`:
///   - ANCHORED: adopt the chain-verified head. A `gap` ABOVE it (withheld middles)
///     doesn't block the verified prefix — refuse-downgrade holds for everything
///     applied — but flags `gapped` so the caller pages for the rest.
///   - UNANCHORED under a held floor: one legitimate cause is a same-version owner
///     fork AT the floor whose deterministic winner (lower inner id; a NULL held id
///     is always replaceable) isn't our held edition —
///     the floor CONVERGES to the winner and the chain re-anchors on it, so every
///     client lands on the same head where a hash-strict floor would wedge forever.
///     Anything else is withholding → fail closed + `gapped`.
///   - BOOTSTRAPPING (`floor == 0` — a fresh joiner, or a fresh epoch after a
///     Refounding, since the caller epoch-filters the floor) takes the highest
///     signed head (author already owner-filtered).
///
/// This matches CORD-04 §1. Epoch-filtering makes a
/// compaction at a new epoch auto-bootstrap, converging with Armada's acceptance of
/// a compacted head across a dangling `prev` (Armada doesn't persist a floor, so a
/// Vector floor only makes Vector STRICTER locally — no wire change, honest-case
/// convergence preserved).
fn apply_control_fold(community: &CommunityV2, editions: &[ParsedEdition], floors: &Floors, authority: &AuthoritySet) -> ControlFold {
    use crate::community::roles::Permissions;
    use std::collections::BTreeMap;
    let floors = &floors_of_family(floors, crate::db::community::FLOOR_CONTROL);

    let owner_hex = community.owner().ok().map(|o| o.to_hex());
    let standing = crate::community::roles::RoleIndex::of(&authority.roles);
    let head_index = HeadIndex::of(&authority.heads);

    let mut groups: BTreeMap<(String, [u8; 32]), Vec<&ParsedEdition>> = BTreeMap::new();
    for e in editions {
        groups.entry((e.vsk.clone(), e.entity_id)).or_default().push(e);
    }

    let mut out = community.clone();
    let mut changed = false;
    let mut heads = Vec::new();
    let mut gapped = false;
    let mut pins_persist = Vec::new();
    let mut deleted_channels = Vec::new();
    let mut writers_persist = Vec::new();
    let (mut kept, mut admitted) = (std::collections::HashSet::new(), crate::fasthash::FastSet::default());
    // Pin List eids are one-way HKDF locators, so attribution runs the other
    // direction: precompute every known channel's locator. An eid matching no
    // channel folds nothing this round — once the channel's metadata lands, the
    // next fold attributes it (editions re-fold from the window each sync).
    let pins_by_eid: std::collections::HashMap<[u8; 32], String> = community
        .channels
        .iter()
        .map(|ch| (super::derive::pins_locator(community.id(), &ch.id), crate::simd::hex::bytes_to_hex_32(&ch.id.0)))
        .collect();
    let writers_by_eid: std::collections::HashMap<[u8; 32], String> = community
        .channels
        .iter()
        .map(|ch| (super::derive::writers_locator(community.id(), &ch.id), crate::simd::hex::bytes_to_hex_32(&ch.id.0)))
        .collect();
    // A channel id is minted at random, so one shared with another entity's coordinate is aimed
    // at that entity: floor rows key on the coordinate alone. Only an edition its kind's bit
    // backs claims a coordinate, so nobody without that bit can hide a Channel behind one.
    let banlist_eid = super::derive::banlist_locator(community.id());
    let claims = |kind: &str, author: &PublicKey| {
        let bit = match kind {
            vsk::COMMUNITY_METADATA => Permissions::MANAGE_METADATA,
            vsk::CHANNEL_METADATA | vsk::CATEGORY | vsk::WRITERS => Permissions::MANAGE_CHANNELS,
            vsk::ROLE | vsk::GRANT | vsk::ROLE_V2 | vsk::CHANNEL_ACL | vsk::TENURE | vsk::CHANNEL_SYNC => Permissions::MANAGE_ROLES,
            vsk::BANLIST => Permissions::BAN,
            vsk::INVITE_LINKS => Permissions::CREATE_INVITE,
            vsk::PINS => Permissions::PIN_MESSAGES,
            _ => return false,
        };
        standing.is_authorized(&author.to_hex(), owner_hex.as_deref(), bit)
    };
    let taken_by = |kind: &str| -> std::collections::HashSet<[u8; 32]> {
        groups
            .iter()
            .filter(|((v, _), g)| v != kind && g.iter().any(|e| claims(v, &e.author)))
            .map(|((_, e), _)| *e)
            .chain([banlist_eid, super::derive::everyone_locator(community.id())])
            .collect()
    };
    let (taken, taken_cat) = (taken_by(vsk::CHANNEL_METADATA), taken_by(vsk::CATEGORY));
    for ((vsk_code, eid), group) in &groups {
        // This fold applies three entities: community metadata (eid ==
        // community_id), channel metadata, and per-channel Pin Lists. A vsk-2
        // whose eid equals the community id is excluded — the floor row keys on
        // the entity alone, so it would share (and corrupt) the metadata
        // chain's floor.
        let is_meta = vsk_code == vsk::COMMUNITY_METADATA && *eid == community.id().0;
        let is_channel = vsk_code == vsk::CHANNEL_METADATA && *eid != community.id().0 && !taken.contains(eid);
        let pins_channel = (vsk_code == vsk::PINS).then(|| pins_by_eid.get(eid)).flatten();
        let is_category = vsk_code == vsk::CATEGORY && *eid != community.id().0 && !taken_cat.contains(eid);
        let writers_channel = (vsk_code == vsk::WRITERS).then(|| writers_by_eid.get(eid)).flatten();
        // One aimed at another entity folds as none, so a reader holding it agrees with a fresh one.
        if vsk_code == vsk::CHANNEL_METADATA && !is_channel && *eid != community.id().0 {
            let before = out.channels.len();
            out.channels.retain(|c| c.id.0 != *eid);
            changed |= out.channels.len() != before;
        }
        if vsk_code == vsk::CATEGORY && !is_category && *eid != community.id().0 {
            let before = out.categories.len();
            out.categories.retain(|c| c.id != *eid);
            changed |= out.categories.len() != before;
        }
        if !is_meta && !is_channel && !is_category && pins_channel.is_none() && writers_channel.is_none() {
            continue;
        }
        // A new kind is read marked only (CORD-04 §1): nothing older ever wrote one.
        let group: Vec<&ParsedEdition> = group.iter().copied().filter(|e| !(is_category || writers_channel.is_some()) || e.binding.is_some()).collect();
        if group.is_empty() {
            continue;
        }
        let group = &group;
        // Authority gate (CORD-04 §5): only editions whose author CURRENTLY holds the
        // entity's management bit are eligible. Pre-filtering before the fold means a
        // demoted admin's (possibly higher-version) edition can't be the head; the
        // highest AUTHORIZED head wins. The owner is supreme.
        let required = if is_meta {
            Permissions::MANAGE_METADATA
        } else if is_channel || is_category || writers_channel.is_some() {
            Permissions::MANAGE_CHANNELS
        } else {
            Permissions::PIN_MESSAGES
        };
        let authorized: Vec<bool> = group
            .iter()
            .map(|e| {
                let author = e.author.to_hex();
                // A banned npub's edits are dropped (CORD-04 §4), even if they still
                // held a bit via a not-yet-stripped grant, unless a Tenure sealed them.
                let sealed = seal_of(&authority.sealed, &author, &e.self_hash, u32::MAX) & required == required;
                (sealed || !authority.banned.contains(&author))
                    && (sealed || standing.is_authorized(&author, owner_hex.as_deref(), required))
                    // …and the CORD-04 §5 sync floor. Resolved against the Grant heads
                    // this same fold settled, so it works on a bootstrap where no
                    // persisted head exists yet.
                    && (sealed || citation_ok_in_fold(community.id(), &head_index, owner_hex.as_deref(), &e.author, e.authority.as_ref()))
            })
            .collect();
        // A Writers ledger settles a tie on what never changes: a later change of rank can't move it.
        let rank = |author_hex: &str| if writers_channel.is_some() { 0 } else { fork_rank_in(&standing, owner_hex.as_deref(), author_hex) };
        let ledger_ok = writers_channel
            .map(|ch| {
                // What this reader already holds anchors what builds on it.
                let anchor = floors.get(&crate::simd::hex::bytes_to_hex_32(eid)).and_then(|f| {
                    let (content, v) = crate::db::community::get_community_writers(&crate::simd::hex::bytes_to_hex_32(&community.id().0), ch).ok().flatten()?;
                    (v as u64 == f.0).then(|| super::writers::Ledger::parse(&content)).flatten().map(|l| (f.1, l))
                });
                ledger_chain_ok(group, &authorized, ch, &|e| (rank(&e.author.to_hex()), e.inner_id), anchor.as_ref())
            })
            .unwrap_or_default();
        // An unmarked Channel edition describes only a Channel that stood before the switch.
        let unlisted = is_channel && authority.roles.legacy_channels.as_ref().is_some_and(|l| !l.contains(&crate::simd::hex::bytes_to_hex_32(eid)));
        let ok: Vec<bool> = group
            .iter()
            .zip(&authorized)
            .map(|(e, &authorized)| authorized && writers_channel.is_none_or(|_| ledger_ok.get(&e.self_hash).copied().unwrap_or(false)) && !(unlisted && e.binding.is_none()))
            .collect();
        let entity_hex = crate::simd::hex::bytes_to_hex_32(eid);
        admitted.extend(group.iter().zip(&ok).filter(|(_, &a)| a).map(|(e, _)| e.inner_id));
        // Refuse-downgrade holds for the newest AUTHORIZED edition: when the edition this
        // device holds (that very one, not a re-signed copy) is served yet no copy of it is
        // authorized, the floor steps down to the predecessor it names, if an authorized
        // copy of that is served. Only on a complete authority fold, so withholding can't
        // manufacture the refusal.
        let floor = floors.get(&entity_hex);
        let held = floor.and_then(|f| group.iter().find(|e| held_is(f, e)));
        // A floor recorded without the signer's id can't tell its edition from a copy.
        let refused = authority.complete
            && floor.is_some_and(|f| f.2.is_some())
            && held.is_some_and(|h| !group.iter().zip(&ok).any(|(e, &a)| a && e.self_hash == h.self_hash));
        if !ok.contains(&true) {
            if refused && writers_channel.is_none() {
                // Only an older build lists a Channel made after the switch by unmarked editions alone.
                if unlisted && group.iter().all(|e| e.binding.is_none()) {
                    let before = out.channels.len();
                    out.channels.retain(|c| c.id.0 != *eid);
                    changed |= out.channels.len() != before;
                }
                kept.insert(entity_hex);
            }
            continue;
        }
        // Every served edition links the chain; only an authorized one can be the head.
        let fold_eds: Vec<version::Edition> = group.iter().map(|p| p.to_fold_edition_ranked(rank(&p.author.to_hex()))).collect();
        // An authorized edition built on the held one moves the entity on, refused or not.
        let (linked, entity_gapped) = fold_head_among(&fold_eds, floor, &|a| rank(&crate::simd::hex::bytes_to_hex_32(a)), &|i| ok[i]);
        gapped |= entity_gapped;
        // A Channel's or Category's deletion is terminal over every authorized edition, not the head alone.
        let deletion = (0..group.len())
            .filter(|&i| (is_category || is_channel) && ok[i])
            .filter(|&i| deletes_entity(is_category, &group[i].content))
            .max_by_key(|&i| (group[i].version, std::cmp::Reverse(group[i].inner_id)));
        if is_channel && deletion.is_some() {
            deleted_channels.push(ChannelId(*eid));
        }
        let (hi, rebased) = match deletion.or(linked) {
            Some(hi) => (hi, false),
            // A ledger records what already happened: a head its Roster now refuses is kept, not
            // stepped back from, or the posts its entry admitted would vanish.
            None if refused && writers_channel.is_none() => {
                let prev = held.and_then(|h| h.prev_hash);
                // A build before marked editions names its predecessor by the unsigned hash.
                let names = |e: &ParsedEdition| {
                    prev == Some(e.self_hash) || (e.binding.is_some() && prev == Some(crate::community::version::edition_hash(&e.entity_id, e.version, e.prev_hash.as_ref(), e.content.as_bytes())))
                };
                let target = (0..group.len()).filter(|&i| ok[i] && names(group[i])).min_by_key(|&i| (rank(&group[i].author.to_hex()), group[i].inner_id));
                let Some(hi) = target else {
                    kept.insert(entity_hex);
                    continue;
                };
                (hi, true)
            }
            None => continue,
        };

        let head = group[hi];
        heads.push(FoldedHead { entity_hex, version: head.version, self_hash: head.self_hash, inner_id: head.inner_id, author: head.author.to_bytes(), rebased });
        if is_meta {
            if let Ok(meta) = serde_json::from_str::<control::CommunityMetadata>(&head.content) {
                changed |= apply_community_metadata(&mut out, meta);
            }
        } else if is_channel {
            if let Some(sealed) = control::parse_sealed_channel_meta(&head.content) {
                changed |= apply_sealed_channel_metadata(&mut out, ChannelId(*eid), &sealed, &head.content, head.prev_hash);
            } else if let Ok(meta) = serde_json::from_str::<control::ChannelMetadata>(&head.content) {
                // vsk-2 carries no community binding; a same-owner
                // cross-community replay can inject a phantom PUBLIC channel (bounded:
                // root-scoped key, eids don't collide). Binding is a deferred wire change.
                changed |= apply_channel_metadata(&mut out, ChannelId(*eid), control::sanitize_channel_metadata(meta));
            }
        } else if is_category {
            if let Ok(meta) = serde_json::from_str::<control::CategoryMetadata>(&head.content) {
                changed |= apply_category_metadata(&mut out, *eid, meta);
            }
        } else if let Some(channel_hex) = pins_channel {
            // The RAW carried content, cap-violations included: readers judge
            // those (read as empty), and a re-serialization here would break the
            // byte cap's meaning and every republish's fidelity.
            use nostr_sdk::prelude::ToBech32;
            let author_npub = head
                .author
                .to_bech32()
                .unwrap_or_else(|_| head.author.to_hex());
            pins_persist.push((channel_hex.clone(), head.content.clone(), head.version, author_npub, head.created_at));
        } else if let Some(channel_hex) = writers_channel {
            let ledger = super::writers::Ledger::parse(&head.content).filter(|l| crate::simd::hex::bytes_to_hex_32(&l.channel) == *channel_hex);
            if let Some(ch) = out.channels.iter_mut().find(|c| crate::simd::hex::bytes_to_hex_32(&c.id.0) == *channel_hex) {
                if ch.writers != ledger {
                    ch.writers = ledger;
                    changed = true;
                }
            }
            writers_persist.push((channel_hex.clone(), head.content.clone(), head.version, rebased));
        }
    }
    changed |= unseal_held(&mut out);
    ControlFold { updated: changed.then_some(out), heads, gapped, pins_persist, writers_persist, deleted_channels, kept, admitted }
}

/// Whether a Channel (or, with `category`, a Category) edition's content deletes it.
fn deletes_entity(category: bool, content: &str) -> bool {
    if category {
        serde_json::from_str::<control::CategoryMetadata>(content).is_ok_and(|m| m.deleted == Some(true))
    } else {
        control::parse_sealed_channel_meta(content)
            .map(|s| s.deleted)
            .or_else(|| serde_json::from_str::<control::ChannelMetadata>(content).ok().map(|m| m.deleted == Some(true)))
            .unwrap_or(false)
    }
}

/// Where a folded `@everyone` Role keeps the Channels that stood before the switch.
const EVERYONE_LEGACY: &str = "legacy";

/// Store a folded Writers ledger head. A rebased head, the fold stepping down from one it
/// refused, replaces whatever was held; when the live writer moves, writers look for its key.
fn persist_writers(cid_hex: &str, channel_hex: &str, content: &str, version: u64, rebased: bool) {
    let held = crate::db::community::get_community_writers(cid_hex, channel_hex).ok().flatten();
    if held.as_ref().is_some_and(|(c, v)| c == content && *v as u64 == version) {
        return;
    }
    let live = |raw: &str| super::writers::Ledger::parse(raw).and_then(|l| l.current_writer());
    let moved = held.as_ref().map(|(c, _)| live(c)) != Some(live(content));
    match crate::db::community::set_community_writers(cid_hex, channel_hex, content, version as i64, rebased) {
        Ok(true) if moved => {
            if let Some(id) = crate::community::id32_from_hex(cid_hex) {
                let id = crate::community::CommunityId(id);
                access_collect_now(&id);
                // A writer still on the epoch just left posts there a moment longer: read it again.
                let read_at = crate::db::community::load_community_v2(&id).ok().flatten().and_then(|c| {
                    let ch = c.channels.iter().find(|ch| crate::simd::hex::bytes_to_hex_32(&ch.id.0) == channel_hex)?;
                    (!(ch.private && ch.key.is_none())).then(|| (ch.id, c.channel_secret(ch).1))
                });
                if let Some((channel, epoch)) = read_at {
                    super::realtime::reread_tails(id, vec![(channel, epoch)]);
                }
            }
            // The live subscription is addressed by the live writer: a move this device made itself
            // folds no change a follow would notice.
            if let Some(client) = crate::state::nostr_client() {
                crate::db::spawn_bound(async move { super::realtime::refresh_subscription(&client).await });
            }
        }
        Ok(_) => {}
        Err(e) => crate::log_warn!("[writers] fold persist failed: {e}"),
    }
}

/// Which of a Writers ledger's editions stand on their content (CORD-03 §1), judged along the
/// whole chain: each well formed for its Channel, its one new entry its signer's own, dated with
/// the edition and not past this reader's horizon, and extending a predecessor that itself
/// stands. Chains grow from the head this reader holds (`anchor`) and from one root: of those an
/// `authorized` edition builds on (a first edition, version 1 with one entry, or the head a
/// Refounding carried, whose predecessor isn't served), the one with the longest history.
fn ledger_chain_ok<'a>(
    group: &[&'a ParsedEdition],
    authorized: &[bool],
    channel_hex: &str,
    key: &dyn Fn(&ParsedEdition) -> (u32, [u8; 32]),
    anchor: Option<&([u8; 32], super::writers::Ledger)>,
) -> std::collections::HashMap<[u8; 32], bool> {
    use std::collections::HashMap;
    let mut keys = super::writers::KeyCheck::default();
    let parsed: HashMap<[u8; 32], super::writers::Ledger> = group
        .iter()
        .filter_map(|e| super::writers::Ledger::parse_with(&e.content, &mut keys).filter(|l| crate::simd::hex::bytes_to_hex_32(&l.channel) == channel_hex).map(|l| (e.self_hash, l)))
        .collect();
    let by_hash: HashMap<[u8; 32], &ParsedEdition> = group.iter().map(|e| (e.self_hash, *e)).collect();
    let now = now_ms();
    let own = |e: &ParsedEdition| parsed.get(&e.self_hash).is_some_and(|l| l.tail_fits(e.created_at, &e.author.to_bytes()) && l.not_ahead(now));
    // Built on the held head, which isn't served: judged against what this reader holds.
    let anchored = |e: &ParsedEdition| anchor.is_some_and(|(h, _)| e.prev_hash == Some(*h) && !by_hash.contains_key(h));
    let root = |e: &ParsedEdition| match e.prev_hash {
        None => own(e) && e.version == 1 && parsed.get(&e.self_hash).is_some_and(|l| l.is_first()),
        Some(p) => !by_hash.contains_key(&p) && !anchored(e) && own(e),
    };
    // Each edition's children, in the group's order, so a walk down visits each edition once.
    let mut children: HashMap<[u8; 32], Vec<&ParsedEdition>> = HashMap::new();
    for e in group {
        if let Some(p) = e.prev_hash {
            children.entry(p).or_default().push(*e);
        }
    }
    // Down each chain from what is judged so far: an edition stands on its predecessor's verdict.
    let grow = |mut ok: HashMap<[u8; 32], bool>| {
        let mut down: Vec<[u8; 32]> = ok.keys().copied().collect();
        while let Some(p) = down.pop() {
            let before = ok[&p];
            for e in children.get(&p).into_iter().flatten() {
                if ok.contains_key(&e.self_hash) {
                    continue;
                }
                let extends = parsed.get(&e.self_hash).zip(parsed.get(&p)).is_some_and(|(l, b)| l.extends(b));
                ok.insert(e.self_hash, before && own(e) && extends);
                down.push(e.self_hash);
            }
        }
        ok
    };
    // Where an edition's chain starts in the group. An edition with no predecessor here is its
    // own start; above it, each predecessor's start is found once.
    let mut top_of: HashMap<[u8; 32], &ParsedEdition> = HashMap::new();
    let mut top = |e: &'a ParsedEdition| -> &'a ParsedEdition {
        let Some(mut at) = e.prev_hash.and_then(|p| by_hash.get(&p)).copied() else { return e };
        let mut path = Vec::new();
        let found = loop {
            if let Some(t) = top_of.get(&at.self_hash) {
                break *t;
            }
            path.push(at.self_hash);
            match at.prev_hash.and_then(|p| by_hash.get(&p)) {
                // A chain of distinct hashes is no longer than the group.
                Some(up) if path.len() < group.len() => at = up,
                _ => break at,
            }
        };
        for h in path {
            top_of.insert(h, found);
        }
        found
    };
    // The roots an authorized edition builds on.
    let mut endorsed: Vec<&ParsedEdition> = Vec::new();
    for (e, _) in group.iter().zip(authorized).filter(|(_, &a)| a) {
        let at = top(e);
        if root(at) && !endorsed.iter().any(|r| r.self_hash == at.self_hash) {
            endorsed.push(at);
        }
    }
    // The longest history wins, as for every Control entity: the highest version an authorized
    // edition that stands reaches from each root. The fork key settles a tie.
    let chosen = endorsed
        .iter()
        .map(|r| {
            let ok = grow(HashMap::from([(r.self_hash, true)]));
            let tip = group.iter().zip(authorized).filter(|(e, &a)| a && ok.get(&e.self_hash) == Some(&true)).map(|(e, _)| e.version).max().unwrap_or(0);
            (tip, *r)
        })
        .min_by_key(|(tip, r)| (std::cmp::Reverse(*tip), key(r)))
        .map(|(_, r)| r.self_hash);
    let mut ok: HashMap<[u8; 32], bool> = HashMap::new();
    if let Some((h, _)) = anchor.filter(|(h, _)| by_hash.contains_key(h)) {
        ok.insert(*h, true);
    }
    for e in group {
        if ok.contains_key(&e.self_hash) {
            continue;
        }
        if let Some((_, held)) = anchor.filter(|_| anchored(e)) {
            ok.insert(e.self_hash, own(e) && parsed.get(&e.self_hash).is_some_and(|l| l.extends(held)));
        } else if e.prev_hash.is_none_or(|p| !by_hash.contains_key(&p)) {
            ok.insert(e.self_hash, Some(e.self_hash) == chosen);
        }
    }
    grow(ok)
}

/// [`ledger_chain_ok`] as it was first written, kept to check the faster one against.
#[cfg(test)]
fn ledger_chain_ok_reference(
    group: &[&ParsedEdition],
    authorized: &[bool],
    channel_hex: &str,
    key: &dyn Fn(&ParsedEdition) -> (u32, [u8; 32]),
    anchor: Option<&([u8; 32], super::writers::Ledger)>,
) -> std::collections::HashMap<[u8; 32], bool> {
    use std::collections::HashMap;
    let parsed: HashMap<[u8; 32], super::writers::Ledger> = group
        .iter()
        .filter_map(|e| super::writers::Ledger::parse(&e.content).filter(|l| crate::simd::hex::bytes_to_hex_32(&l.channel) == channel_hex).map(|l| (e.self_hash, l)))
        .collect();
    let by_hash: HashMap<[u8; 32], &ParsedEdition> = group.iter().map(|e| (e.self_hash, *e)).collect();
    let now = now_ms();
    let own = |e: &ParsedEdition| parsed.get(&e.self_hash).is_some_and(|l| l.tail_fits(e.created_at, &e.author.to_bytes()) && l.not_ahead(now));
    // Built on the held head, which isn't served: judged against what this reader holds.
    let anchored = |e: &ParsedEdition| anchor.is_some_and(|(h, _)| e.prev_hash == Some(*h) && !by_hash.contains_key(h));
    let root = |e: &ParsedEdition| match e.prev_hash {
        None => own(e) && e.version == 1 && parsed.get(&e.self_hash).is_some_and(|l| l.is_first()),
        Some(p) => !by_hash.contains_key(&p) && !anchored(e) && own(e),
    };
    // Down each chain from what is judged so far; one is at most as long as the group.
    let grow = |mut ok: HashMap<[u8; 32], bool>| {
        for _ in 0..group.len() {
            let mut moved = false;
            for e in group {
                if ok.contains_key(&e.self_hash) {
                    continue;
                }
                let Some(p) = e.prev_hash else { continue };
                if let Some(&before) = ok.get(&p) {
                    let extends = parsed.get(&e.self_hash).zip(parsed.get(&p)).is_some_and(|(l, b)| l.extends(b));
                    ok.insert(e.self_hash, before && own(e) && extends);
                    moved = true;
                }
            }
            if !moved {
                break;
            }
        }
        ok
    };
    // The roots an authorized edition builds on.
    let mut endorsed: Vec<&ParsedEdition> = Vec::new();
    for (e, _) in group.iter().zip(authorized).filter(|(_, &a)| a) {
        let mut at = *e;
        for _ in 0..group.len() {
            match at.prev_hash.and_then(|p| by_hash.get(&p)) {
                Some(up) => at = up,
                None => break,
            }
        }
        if root(at) && !endorsed.iter().any(|r| r.self_hash == at.self_hash) {
            endorsed.push(at);
        }
    }
    // The longest history wins, as for every Control entity: the highest version an authorized
    // edition that stands reaches from each root. The fork key settles a tie.
    let chosen = endorsed
        .iter()
        .map(|r| {
            let ok = grow(HashMap::from([(r.self_hash, true)]));
            let tip = group.iter().zip(authorized).filter(|(e, &a)| a && ok.get(&e.self_hash) == Some(&true)).map(|(e, _)| e.version).max().unwrap_or(0);
            (tip, *r)
        })
        .min_by_key(|(tip, r)| (std::cmp::Reverse(*tip), key(r)))
        .map(|(_, r)| r.self_hash);
    let mut ok: HashMap<[u8; 32], bool> = HashMap::new();
    if let Some((h, _)) = anchor.filter(|(h, _)| by_hash.contains_key(h)) {
        ok.insert(*h, true);
    }
    for e in group {
        if ok.contains_key(&e.self_hash) {
            continue;
        }
        if let Some((_, held)) = anchor.filter(|_| anchored(e)) {
            ok.insert(e.self_hash, own(e) && parsed.get(&e.self_hash).is_some_and(|l| l.extends(held)));
        } else if e.prev_hash.is_none_or(|p| !by_hash.contains_key(&p)) {
            ok.insert(e.self_hash, Some(e.self_hash) == chosen);
        }
    }
    grow(ok)
}


/// Fold one entity's editions against its persisted floor into a head index (into the
/// input slice) plus whether a TRACKING gap was hit (the caller pages older history).
/// Encapsulates the W2 refuse-downgrade policy: bootstrap at floor 0 (highest signed
/// head, what Armada shows across a compaction's dangling prev); adopt the chain-
/// anchored head, paging on an upper gap; converge a same-version fork at the floor to
/// the lower-inner-id winner; and fail closed otherwise.
fn fold_head(fold_eds: &[version::Edition], floor: Option<&Floor>, rank_of: &dyn Fn(&[u8; 32]) -> u32) -> (Option<usize>, bool) {
    fold_head_among(fold_eds, floor, rank_of, &|_| true)
}

/// [`fold_head`] with the head taken only among the editions `eligible` admits, while
/// every served edition carries the chain.
fn fold_head_among(fold_eds: &[version::Edition], floor: Option<&Floor>, rank_of: &dyn Fn(&[u8; 32]) -> u32, eligible: &dyn Fn(usize) -> bool) -> (Option<usize>, bool) {
    let Some(floor) = floor.filter(|f| f.0 > 0) else {
        let ok: Vec<usize> = (0..fold_eds.len()).filter(|&i| eligible(i)).collect();
        let sub: Vec<version::Edition> = ok.iter().map(|&i| fold_eds[i].clone()).collect();
        return (version::bootstrap_head(&sub, 0).map(|k| ok[k]), false);
    };
    // A same-version rival of a withheld held head may stand in for it only by beating
    // the key the floor recorded; while the held edition is served, the tiebreak decides.
    let held = HeldKey::of(floor, rank_of);
    let result = version::fold_linked(fold_eds, floor.0, Some(&floor.1), &|e| held.beaten_by(e.rank, &e.tiebreak_id), eligible);
    if result.anchored {
        return (result.head, result.gap); // verified prefix; page any upper gap.
    }
    // Nothing at or above the floor is a stale relay (no paging); anything else that
    // fails to link is withholding, so fail closed.
    (None, result.gap)
}

/// The folded, delegation-AUTHORIZED control-plane authority (CORD-04): the roster
/// (roles + grants, owner-seeded fixpoint), the enforced banlist, and the
/// role/grant/banlist heads to persist as refuse-downgrade floors. The owner is
/// recomputed from the self-certifying community_id at each use.
struct AuthoritySet {
    roles: crate::community::roles::CommunityRoles,
    banned: std::collections::BTreeSet<String>,
    heads: Vec<FoldedHead>,
    gapped: bool,
    /// The authorized banlist `(content, version)` to persist when an authorized head
    /// advanced the floor. `None` when the banlist was retained (no new authorized
    /// head) or is empty — the caller then leaves the stored banlist untouched.
    banlist_persist: Option<(Vec<String>, u64)>,
    /// Ban HISTORY: npub hex → `created_at` (secs) of the newest authorized edition that
    /// named them, across every edition in the window rather than just the head. Outlives
    /// the ban itself so an un-ban can't resurrect a phantom (see [`fold_members`]).
    banned_at: std::collections::BTreeMap<String, u64>,
    /// Every floored role and grant served its held head this fold: data enough that a
    /// held head the Roster refuses is refused on the evidence, not on a withholding.
    complete: bool,
    /// Role and grant entities refused whole on that evidence: settled absent, so no
    /// completeness check waits on them.
    refused: std::collections::BTreeSet<String>,
    /// Role and grant entities whose held head is refused with nothing to fall back to.
    carried: std::collections::BTreeSet<String>,
    /// Every role and grant edition the fold admitted.
    admitted: crate::fasthash::FastSet<[u8; 32]>,
    /// Roles v2 is active (CORD-04 §2).
    activated: bool,
    /// Each member's sealed standings (CORD-04 §9).
    sealed: SealedBy,
    /// The authority fixpoint converged.
    converged: bool,
}

impl AuthoritySet {
    /// Every role/grant/banlist entity this fold settled: a head, or refused on evidence.
    fn settled(&self) -> std::collections::HashSet<&str> {
        self.heads.iter().map(|h| h.entity_hex.as_str()).chain(self.refused.iter().map(String::as_str)).collect()
    }
}

impl AuthoritySet {
    /// Bootstrap authority for a community with no roster editions folded yet: only
    /// the owner is authorized (supreme), nobody banned.
    fn owner_only() -> Self {
        AuthoritySet {
            roles: Default::default(),
            banned: Default::default(),
            heads: vec![],
            gapped: false,
            banlist_persist: None,
            banned_at: Default::default(),
            complete: false,
            refused: Default::default(),
            carried: Default::default(),
            admitted: Default::default(),
            activated: false,
            sealed: Default::default(),
            converged: true,
        }
    }
}

/// The stamp a roster cache carries: the newest of its authorized heads' times, clamped,
/// since a signer picks its own `created_at` and a future one would freeze every later
/// fold behind it.
fn roster_stamp(editions: &[ParsedEdition], heads: &[FoldedHead]) -> i64 {
    let ids: std::collections::HashSet<[u8; 32]> = heads.iter().map(|h| h.inner_id).collect();
    let ceiling = roster_stamp_ceiling();
    editions
        .iter()
        .filter(|e| [vsk::ROLE, vsk::ROLE_V2, vsk::GRANT, vsk::BANLIST, vsk::TENURE, vsk::CHANNEL_ACL, vsk::CHANNEL_SYNC].contains(&e.vsk.as_str()) && ids.contains(&e.inner_id))
        .map(|e| (e.created_at as i64).min(ceiling))
        .max()
        .unwrap_or(0)
}

fn roster_stamp_ceiling() -> i64 {
    (now_ms() / 1000) as i64 + 600
}

/// Whether `e` is the very edition `floor` records (see [`AuthorityCand::is_held`]).
fn held_is(floor: &Floor, e: &ParsedEdition) -> bool {
    e.version == floor.0 && e.self_hash == floor.1 && floor.2.is_none_or(|id| id == e.inner_id)
}

/// Fold the roster/banlist entities (vsk 1/3/4) from the control editions into the
/// delegation-AUTHORIZED roster + enforced banlist (CORD-04 §2-§5). Each entity binds
/// to its coordinate (role at role_id, grant at grant_locator(cid, member), banlist at
/// banlist_locator(cid)); a content whose coordinate doesn't match is dropped. Roles
/// cap at the 100 lowest role_ids, a member at 64 roles, the banlist at 500. The
/// banlist is enforced only if its head's signer held BAN in the authorized roster.
fn fold_authority(community: &CommunityV2, editions: &[ParsedEdition], floors: &Floors) -> AuthoritySet {
    use crate::community::roles::{Permissions, Role};
    use std::collections::BTreeMap;

    let cid = community.id();
    let cid_hex = crate::simd::hex::bytes_to_hex_32(&cid.0);
    let floors = &floors_of_family(floors, crate::db::community::FLOOR_AUTHORITY);
    let owner = community.owner().ok();
    let owner_hex = owner.map(|o| o.to_hex());
    let banlist_eid = super::derive::banlist_locator(cid);
    let banlist_hex = crate::simd::hex::bytes_to_hex_32(&banlist_eid);

    let mut groups: BTreeMap<[u8; 32], Vec<&ParsedEdition>> = BTreeMap::new();
    for e in editions {
        if e.vsk == vsk::ROLE || e.vsk == vsk::ROLE_V2 || e.vsk == vsk::GRANT || e.vsk == vsk::BANLIST || e.vsk == vsk::TENURE {
            groups.entry(e.entity_id).or_default().push(e);
        }
    }

    // Per-entity CANDIDATE lists — every ≥floor edition of a role/grant, highest
    // version first (lowest inner-id as the deterministic tiebreak). CORD-04 §1: an
    // edition whose signer isn't authorized is SIMPLY DROPPED and the fold continues
    // to the next candidate, so a forged higher-version edition can't suppress the
    // authorized head beneath it (the author-blind collapse-to-one-head it replaces
    // let any member vanish a role or a member's grant). `gapped` (drives older-
    // paging) stays fold_head's per-entity flag.
    // Roles v2 (CORD-04 §2): Roles fold from vsk 13 alone once @everyone stands there, judged
    // in a vsk-13 fold, which traces to the owner because a vsk-1 Role confers nothing in it.
    // So an admin's later edit of @everyone keeps the Community on Roles v2 across a
    // Refounding, and once floored it stays. A vsk-1 edition then links the chain a migrated
    // Role continues, and stands for nothing. Rank keys map to dense positions.
    let everyone_eid = super::derive::everyone_locator(cid);
    let everyone_hex = crate::simd::hex::bytes_to_hex_32(&everyone_eid);
    let build = |activated: bool| {
        let mut role_cands: BTreeMap<String, Vec<AuthorityCand>> = BTreeMap::new();
        let mut grant_cands: BTreeMap<String, Vec<AuthorityCand>> = BTreeMap::new();
        let mut tenure_cands: BTreeMap<String, Vec<AuthorityCand>> = BTreeMap::new();
        let mut gapped = false;
        let ranks: crate::fasthash::FastMap<String, u32> = if activated {
            let mut keys: Vec<String> = editions
                .iter()
                .filter(|e| e.vsk == vsk::ROLE_V2 && e.binding.is_some())
                .filter_map(|e| match super::roles::parse_role_v2_content(&e.content) {
                    Some(super::roles::RoleV2::Live(r)) => r.rank,
                    _ => None,
                })
                .collect();
            // A Tenure's ranks sit in the same order as the Roles'.
            keys.extend(
                editions
                    .iter()
                    .filter(|e| e.vsk == vsk::TENURE && e.binding.is_some())
                    .filter_map(|e| super::roles::parse_tenure_content(&e.content))
                    .flat_map(|t| t.sealed.into_iter().map(|e| e.rank)),
            );
            crate::community::rank::dense_ranks(keys.iter().map(String::as_str)).into_iter().map(|(k, v)| (k.to_string(), v)).collect()
        } else {
            Default::default()
        };
        for (eid, group) in &groups {
            // The banlist is folded author-aware AFTER the roster is known (below).
            if *eid == banlist_eid {
                continue;
            }
            let entity_hex = crate::simd::hex::bytes_to_hex_32(eid);
            let floor = floors.get(&entity_hex).copied();
            let held_served = floor.is_some_and(|f| group.iter().any(|p| held_is(&f, p)));
            // Nothing above a withheld held head can be judged on the rank it acts on: page for it.
            gapped |= floor.is_some_and(|f| !held_served && group.iter().any(|p| p.version > f.0));

            for p in group {
                let head = FoldedHead { entity_hex: entity_hex.clone(), version: p.version, self_hash: p.self_hash, inner_id: p.inner_id, author: p.author.to_bytes(), rebased: false };
                let author_hex = p.author.to_hex();
                let grant_hex = crate::simd::hex::bytes_to_hex_32(&super::derive::grant_locator(cid, &p.author.to_bytes()));
                let cand = |role: Role, kind: RoleKind| AuthorityCand { role: Some(role), grant: None, tenure: None, kind, author: p.author, author_hex: author_hex.clone(), grant_hex: grant_hex.clone(), head: head.clone(), citation: p.authority.clone(), prev: p.prev_hash, floor, held_served };
                match p.vsk.as_str() {
                    // The @everyone coordinate holds @everyone alone.
                    vsk::ROLE if *eid == everyone_eid => {}
                    vsk::ROLE => {
                        // Bind: the content's role_id IS the coordinate; position 0 is the owner's.
                        if let Some(role) = super::roles::parse_role_content(&p.content) {
                            if role.role_id == entity_hex && role.position != 0 {
                                let kind = if activated { RoleKind::History } else { RoleKind::Live };
                                role_cands.entry(entity_hex.clone()).or_default().push(cand(role, kind));
                            }
                        }
                    }
                    vsk::ROLE_V2 if p.binding.is_none() => {}
                    vsk::ROLE_V2 if activated && *eid == everyone_eid => {
                        if let Some((bits, legacy)) = super::roles::parse_everyone_content(&p.content) {
                            let mut extra = serde_json::Map::new();
                            if let Some(l) = legacy {
                                extra.insert(EVERYONE_LEGACY.into(), serde_json::json!(l));
                            }
                            let role = Role { role_id: everyone_hex.clone(), name: "@everyone".into(), position: u32::MAX, permissions: Permissions(bits), scope: crate::community::roles::RoleScope::Server, color: 0, rank: None, display: false, mentionable: false, extra };
                            role_cands.entry(entity_hex.clone()).or_default().push(cand(role, RoleKind::Everyone));
                        }
                    }
                    vsk::ROLE_V2 if activated => match super::roles::parse_role_v2_content(&p.content) {
                        Some(super::roles::RoleV2::Live(mut role)) if role.role_id == entity_hex => {
                            role.position = role.rank.as_ref().and_then(|k| ranks.get(k)).copied().unwrap_or(u32::MAX);
                            role_cands.entry(entity_hex.clone()).or_default().push(cand(role, RoleKind::Live));
                        }
                        Some(super::roles::RoleV2::Deleted { role_id }) if role_id == entity_hex => {
                            let role = Role { role_id, name: String::new(), position: u32::MAX, permissions: Permissions(0), scope: crate::community::roles::RoleScope::Server, color: 0, rank: None, display: false, mentionable: false, extra: Default::default() };
                            role_cands.entry(entity_hex.clone()).or_default().push(cand(role, RoleKind::Deleted));
                        }
                        _ => {}
                    },
                    vsk::TENURE if activated && p.binding.is_some() => {
                        if let Some(t) = super::roles::parse_tenure_content(&p.content) {
                            let bound = crate::simd::hex::hex_to_bytes_32_checked(&t.member).is_some_and(|m| super::derive::tenure_locator(cid, &m, &p.author.to_bytes()) == *eid);
                            if bound {
                                let entries = t
                                    .sealed
                                    .iter()
                                    .filter_map(|e| {
                                        let position = ranks.get(&e.rank).copied()?;
                                        let heads = e.heads.iter().filter_map(|h| crate::simd::hex::hex_to_bytes_32_checked(h)).collect();
                                        Some(Sealed { position, bits: e.permissions, heads })
                                    })
                                    .collect();
                                tenure_cands.entry(entity_hex.clone()).or_default().push(AuthorityCand { role: None, grant: None, tenure: Some((t.member.clone(), entries)), kind: RoleKind::Live, author: p.author, author_hex: author_hex.clone(), grant_hex: grant_hex.clone(), head, citation: p.authority.clone(), prev: p.prev_hash, floor, held_served });
                            }
                        }
                    }
                    vsk::GRANT => {
                        if let Some(mut grant) = super::roles::parse_grant_content(&p.content) {
                            if let Some(member) = crate::simd::hex::hex_to_bytes_32_checked(&grant.member) {
                                if super::derive::grant_locator(cid, &member) == *eid {
                                    grant.role_ids.truncate(super::roles::MAX_ROLES_PER_MEMBER);
                                    grant_cands.entry(entity_hex.clone()).or_default().push(AuthorityCand { role: None, grant: Some(grant), tenure: None, kind: RoleKind::Live, author: p.author, author_hex: author_hex.clone(), grant_hex: grant_hex.clone(), head, citation: p.authority.clone(), prev: p.prev_hash, floor, held_served });
                                }
                            }
                        }
                    }
                    _ => {}
                }
            }
        }
        for cands in role_cands.values_mut().chain(grant_cands.values_mut()).chain(tenure_cands.values_mut()) {
            cands.sort_by(|a, b| b.head.version.cmp(&a.head.version).then(a.head.inner_id.cmp(&b.head.inner_id)));
        }
        (role_cands, grant_cands, tenure_cands, gapped)
    };
    // Complete: every role and grant this device floors served its held head, so a held
    // head the Roster refuses is refused on the evidence. The stored roster names the
    // floored entities a plane might have stopped serving entirely.
    let stored = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
    // A Tenure this device floors is tracked too, or withholding it would refuse what it
    // seals "on evidence". Its coordinate names member and writer, so the candidates are the
    // authors of floored heads, each against everyone who could have reduced them.
    let tenure_floors: Vec<String> = {
        let mut writers: std::collections::BTreeSet<[u8; 32]> = owner.iter().map(|o| o.to_bytes()).collect();
        let managers = stored.authorized_grantees(owner_hex.as_deref(), Permissions::MANAGE_ROLES);
        writers.extend(stored.grants.iter().filter(|g| managers.contains(g.member.as_str())).filter_map(|g| crate::simd::hex::hex_to_bytes_32_checked(&g.member)));
        let authors: std::collections::BTreeSet<[u8; 32]> = floors.values().filter_map(|f| f.3).collect();
        authors
            .iter()
            .flat_map(|a| writers.iter().map(move |w| crate::simd::hex::bytes_to_hex_32(&super::derive::tenure_locator(cid, a, w))))
            .filter(|eid| floors.contains_key(eid))
            .collect()
    };
    // What `held_is` matches on, for every edition in hand: by version and hash, and with the id.
    let served: crate::fasthash::FastSet<(u64, [u8; 32])> = editions.iter().map(|e| (e.version, e.self_hash)).collect();
    let served_as: crate::fasthash::FastSet<(u64, [u8; 32], [u8; 32])> = editions.iter().map(|e| (e.version, e.self_hash, e.inner_id)).collect();
    let held_served = |f: &Floor| match f.2 {
        None => served.contains(&(f.0, f.1)),
        Some(id) => served_as.contains(&(f.0, f.1, id)),
    };
    let complete_of = |role_cands: &BTreeMap<String, Vec<AuthorityCand>>, grant_cands: &BTreeMap<String, Vec<AuthorityCand>>, tenure_cands: &BTreeMap<String, Vec<AuthorityCand>>| {
        let mut tracked: std::collections::BTreeSet<String> = role_cands.keys().chain(grant_cands.keys()).chain(tenure_cands.keys()).cloned().collect();
        tracked.extend(tenure_floors.iter().cloned());
        tracked.extend(stored.roles.iter().map(|r| r.role_id.clone()));
        tracked.extend(stored.grants.iter().filter_map(|g| {
            crate::simd::hex::hex_to_bytes_32_checked(&g.member)
                .map(|m| crate::simd::hex::bytes_to_hex_32(&super::derive::grant_locator(cid, &m)))
        }));
        tracked.iter().all(|eid| floors.get(eid).is_none_or(&held_served))
    };
    let some_v2 = groups.get(&everyone_eid).is_some_and(|g| g.iter().any(|e| e.vsk == vsk::ROLE_V2 && e.binding.is_some()));
    let activated = floors.contains_key(&everyone_hex)
        || (some_v2 && {
            let (rc, gc, tc, _) = build(true);
            let none: std::collections::BTreeSet<String> = Default::default();
            select_authorized(cid, &rc, &gc, &tc, owner_hex.as_deref(), &none, complete_of(&rc, &gc, &tc), None).heads.iter().any(|h| h.entity_hex == everyone_hex)
        });
    let (role_cands, grant_cands, tenure_cands, withheld) = build(activated);
    let mut gapped = withheld;
    let complete = complete_of(&role_cands, &grant_cands, &tenure_cands);
    let empty: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
    // Preliminary roster (bans not yet applied) — the authority view the banlist head
    // is judged against.
    let prelim_sel = select_authorized(cid, &role_cands, &grant_cands, &tenure_cands, owner_hex.as_deref(), &empty, complete, None);
    let (prelim, prelim_heads, prelim_sealed) = (prelim_sel.roles, prelim_sel.heads, prelim_sel.sealed);
    let prelim_rank = |author_hex: &str| fork_rank(&prelim, owner_hex.as_deref(), author_hex);
    let prelim_rank_bytes = |a: &[u8; 32]| prelim_rank(&crate::simd::hex::bytes_to_hex_32(a));
    // Whether a tracking role/grant chain gapped (drives older-paging), its forks ranked by
    // the authority this pass resolved.

    // Banlist (CORD-04 §4), folded AUTHORITY-aware so its two anti-roster hazards are
    // both closed:
    //   - head selection: the head is the highest version whose author CURRENTLY holds
    //     BAN — an unauthorized higher-version edition can't erase existing bans
    //     (fail-open), and the floor never advances to one;
    //   - per-target: each entry is kept only if the author STRICTLY OUTRANKS that
    //     target (`can_act_on_member` — an admin can't ban a peer/superior, and the
    //     owner is unbannable);
    //   - withholding: when no authorized head is served, the persisted banlist is
    //     RETAINED (an anti-roster must not un-ban on a relay withholding the ban).
    let persisted_banned: Vec<String> = crate::db::community::get_community_banlist(&cid_hex).unwrap_or_default();
    // An ALREADY-banned npub can't author the banlist (a banned member vanishes, §4), or
    // a BAN-holder whose grant-strip hasn't yet folded could publish a list omitting their
    // OWN ban to un-ban themselves (removals aren't outrank-checked). Exclude them from
    // head eligibility, not just from the roster.
    let banned_authors: crate::fasthash::FastSet<&str> = persisted_banned.iter().map(String::as_str).collect();
    let prelim_index = HeadIndex::of(&prelim_heads);
    let banlist_authored: Vec<&ParsedEdition> = groups
        .get(&banlist_eid)
        .map(|g| {
            g.iter()
                .copied()
                .filter(|e| {
                    let ah = e.author.to_hex();
                    let sealed_ban = seal_of(&prelim_sealed, &ah, &e.self_hash, u32::MAX) & Permissions::BAN != 0;
                    (!banned_authors.contains(ah.as_str()) || sealed_ban)
                        // From the author's Roles: @everyone's bits author no banlist.
                        && (owner_hex.as_deref() == Some(ah.as_str()) || sealed_ban || prelim.permissions_above(&ah, u32::MAX).contains(Permissions::BAN))
                        && (sealed_ban || citation_ok_in_fold(cid, &prelim_index, owner_hex.as_deref(), &e.author, e.authority.as_ref()))
                        // A malformed list is no Banlist edition: read as empty it would unban everyone.
                        && super::roles::parse_banlist_content(&e.content).is_some()
                })
                .collect()
        })
        .unwrap_or_default();
    // Ban history for phantom suppression: the newest AUTHORIZED edition naming each npub,
    // over EVERY candidate rather than only the head — an un-ban replaces the head, so the
    // head alone forgets the ban that the suppression exists to remember. The owner is
    // skipped: they are never bannable, and a moderator listing them must not durably
    // suppress them past the un-ban.
    let mut banned_at: std::collections::BTreeMap<String, u64> = std::collections::BTreeMap::new();
    for p in &banlist_authored {
        for t in super::roles::parse_banlist_content(&p.content).unwrap_or_default() {
            if owner_hex.as_deref() == Some(t.as_str()) {
                continue;
            }
            let slot = banned_at.entry(t).or_insert(0);
            *slot = (*slot).max(p.created_at);
        }
    }
    let mut banlist_persist: Option<(Vec<String>, u64)> = None;
    let mut banlist_head: Option<FoldedHead> = None;
    let banned: std::collections::BTreeSet<String> = if banlist_authored.is_empty() {
        persisted_banned.into_iter().collect()
    } else {
        // Every served edition links the chain; only an authored one can be the head.
        let all: Vec<&ParsedEdition> = groups.get(&banlist_eid).map(|g| g.to_vec()).unwrap_or_default();
        let authored: std::collections::HashSet<[u8; 32]> = banlist_authored.iter().map(|e| e.inner_id).collect();
        let fold_eds: Vec<version::Edition> = all.iter().map(|p| p.to_fold_edition_ranked(prelim_rank(&p.author.to_hex()))).collect();
        let (hi, g) = fold_head_among(&fold_eds, floors.get(&banlist_hex), &prelim_rank_bytes, &|i| authored.contains(&all[i].inner_id));
        gapped |= g;
        match hi {
            Some(hi) => {
                let head = all[hi];
                let ah = head.author.to_hex();
                let list: Vec<String> = super::roles::parse_banlist_content(&head.content)
                    .unwrap_or_default()
                    .into_iter()
                    .filter(|t| {
                        prelim.can_act_on_member(&ah, owner_hex.as_deref(), t, Permissions::BAN)
                            || (owner_hex.as_deref() != Some(t.as_str())
                                && seal_of(&prelim_sealed, &ah, &head.self_hash, prelim.highest_position(t).unwrap_or(u32::MAX)) & Permissions::BAN != 0)
                    })
                    .take(super::roles::MAX_BANLIST)
                    .collect();
                banlist_head = Some(FoldedHead { entity_hex: banlist_hex.clone(), version: head.version, self_hash: head.self_hash, inner_id: head.inner_id, author: head.author.to_bytes(), rebased: false });
                banlist_persist = Some((list.clone(), head.version));
                list.into_iter().collect()
            }
            None => persisted_banned.into_iter().collect(),
        }
    };

    // Final roster (CORD-04 §4: a banned npub vanishes — every edition it authored is
    // dropped, and a grant TO a banned member carries no rank). Re-run selection with
    // the banned set excluded so a banned admin loses authority.
    let mut refusals: std::collections::BTreeMap<String, &'static str> = Default::default();
    let selected = select_authorized(cid, &role_cands, &grant_cands, &tenure_cands, owner_hex.as_deref(), &banned, complete, Some(&mut refusals));
    let (mut authorized, mut heads, refused, carried, admitted, sealed, converged) = (selected.roles, selected.heads, selected.refused, selected.carried, selected.admitted, selected.sealed, selected.converged);
    gapped |= selected.gapped;
    if !converged {
        crate::log_warn!("[v2:authority {}] the roster fold did not settle within its bound; the last round stands", &cid_hex[..8.min(cid_hex.len())]);
    }
    AUTHORITY_REFUSALS.with(|c| *c.borrow_mut() = refusals);
    if let Some(bh) = banlist_head {
        heads.push(bh);
    }

    // Cap the AUTHORIZED community at the 100 lowest role_ids — applied AFTER
    // authorization, so an attacker's unauthorized roles can't consume cap slots and
    // evict a legitimate one (the pre-authorize cap they replace let 100 forged low-id
    // roles empty the roster).
    if authorized.roles.len() > super::roles::MAX_ROLES_PER_COMMUNITY {
        authorized.roles.sort_by(|a, b| a.role_id.cmp(&b.role_id));
        authorized.roles.truncate(super::roles::MAX_ROLES_PER_COMMUNITY);
        let kept: std::collections::HashSet<&str> = authorized.roles.iter().map(|r| r.role_id.as_str()).collect();
        authorized.grants.iter_mut().for_each(|g| g.role_ids.retain(|rid| kept.contains(rid.as_str())));
        authorized.grants.retain(|g| !g.role_ids.is_empty());
    }

    if activated && authorized.everyone.is_none() {
        authorized.everyone = stored.everyone;
    }
    if activated {
        // The switch fixes the list (CORD-04 §2): an @everyone edition after it can't change it.
        let switched = role_cands
            .get(&everyone_hex)
            .and_then(|cands| cands.iter().filter(|c| c.kind == RoleKind::Everyone && Some(c.author) == owner && c.prev.is_none()).min_by_key(|c| (c.head.version, c.head.inner_id)))
            .and_then(|c| c.role.as_ref())
            .and_then(|r| r.extra.get(EVERYONE_LEGACY))
            .and_then(|l| serde_json::from_value(l.clone()).ok());
        authorized.legacy_channels = switched.or(stored.legacy_channels.clone()).or(authorized.legacy_channels.take());
    }
    if activated {
        authorized.overwrites = fold_overwrites(community, editions, floors, &authorized, &banned, &sealed, &mut heads, &mut gapped);
        authorized.syncs = fold_syncs(community, editions, floors, &authorized, &banned, &sealed, &mut heads, &mut gapped);
        authorized.creators = community.channels.iter().filter_map(|c| Some((crate::simd::hex::bytes_to_hex_32(&c.id.0), c.creator()?.to_string()))).collect();
    }

    AuthoritySet { roles: authorized, banned, heads, gapped, banlist_persist, banned_at, complete, refused, carried, admitted, activated, sealed, converged }
}

/// Whether `author_hex` could write every overwrite in `scopes` as it stands: what a sync
/// swaps all at once (CORD-04 §8). `sealed_over` lends a Tenure's standing to one edition.
fn may_swap_overwrites(roles: &crate::community::roles::CommunityRoles, owner_hex: Option<&str>, author_hex: &str, scopes: &[&str], sealed_over: &dyn Fn(u32) -> u64) -> bool {
    use crate::community::roles::{OverwriteTarget, Permissions};
    if owner_hex == Some(author_hex) {
        return true;
    }
    let held = |rank: u32| roles.permissions_above(author_hex, rank).0 | sealed_over(rank);
    if held(u32::MAX) & Permissions::MANAGE_ROLES == 0 {
        return false;
    }
    roles.overwrites.iter().filter(|o| scopes.contains(&o.scope.as_str())).all(|o| {
        let rank = match &o.target {
            OverwriteTarget::Everyone => u32::MAX,
            OverwriteTarget::Role(id) => roles.role(id).map_or(u32::MAX, |r| r.position),
            OverwriteTarget::Member(m) => roles.highest_position(m).unwrap_or(u32::MAX),
        };
        let support = held(rank);
        support & Permissions::MANAGE_ROLES != 0 && (o.allow.0 | o.deny.0) & !support == 0
    })
}

/// Fold each Channel's sync (vsk 17): judged against the settled overwrites, since a sync
/// swaps every rule on both sides at once, so its signer must be able to write them all.
#[allow(clippy::too_many_arguments)]
fn fold_syncs(
    community: &CommunityV2,
    editions: &[ParsedEdition],
    floors: &Floors,
    roles: &crate::community::roles::CommunityRoles,
    banned: &std::collections::BTreeSet<String>,
    sealed: &SealedBy,
    heads: &mut Vec<FoldedHead>,
    gapped: &mut bool,
) -> std::collections::BTreeMap<String, String> {
    let cid = community.id();
    let owner_hex = community.owner().ok().map(|o| o.to_hex());
    let mut groups: std::collections::BTreeMap<[u8; 32], Vec<(&ParsedEdition, String, Option<String>)>> = Default::default();
    for e in editions.iter().filter(|e| e.vsk == vsk::CHANNEL_SYNC && e.binding.is_some()) {
        let Some((channel, category)) = super::roles::parse_sync_content(&e.content) else { continue };
        let ch = ChannelId(crate::simd::hex::hex_to_bytes_32(&channel));
        if super::derive::sync_locator(cid, &ch) == e.entity_id {
            groups.entry(e.entity_id).or_default().push((e, channel, category));
        }
    }
    let mut out = std::collections::BTreeMap::new();
    let mut withheld: std::collections::BTreeSet<[u8; 32]> = Default::default();
    let served: std::collections::BTreeSet<[u8; 32]> = groups.keys().copied().collect();
    for (eid, group) in groups {
        let ok: Vec<bool> = group
            .iter()
            .map(|(e, channel, category)| {
                let ah = e.author.to_hex();
                if banned.contains(&ah) && !is_listed(sealed, &ah, &e.self_hash) && owner_hex.as_deref() != Some(ah.as_str()) {
                    return false;
                }
                // The Category it leaves is the one its predecessor named: judged too, and
                // unknowable while that predecessor isn't served.
                let left = match e.prev_hash {
                    None => None,
                    Some(p) => match group.iter().find(|(x, _, _)| x.self_hash == p) {
                        Some((_, _, k)) => k.clone(),
                        None => return false,
                    },
                };
                let mut scopes = vec![channel.as_str()];
                scopes.extend(category.as_deref());
                scopes.extend(left.as_deref());
                may_swap_overwrites(roles, owner_hex.as_deref(), &ah, &scopes, &|rank| seal_of(sealed, &ah, &e.self_hash, rank))
            })
            .collect();
        if !ok.contains(&true) {
            continue;
        }
        let entity_hex = crate::simd::hex::bytes_to_hex_32(&eid);
        let rank = |a: &str| fork_rank(roles, owner_hex.as_deref(), a);
        let fold_eds: Vec<version::Edition> = group.iter().map(|(p, _, _)| p.to_fold_edition_ranked(rank(&p.author.to_hex()))).collect();
        let floor = floors.get(&entity_hex);
        let (hi, gap) = fold_head_among(&fold_eds, floor, &|a| rank(&crate::simd::hex::bytes_to_hex_32(a)), &|i| ok[i]);
        *gapped |= gap;
        let held_served = floor.is_some_and(|f| group.iter().any(|(e, _, _)| held_is(f, e)));
        let (hi, rebased) = match hi {
            Some(hi) => (hi, false),
            None if held_served => match fold_head_among(&fold_eds, None, &|a| rank(&crate::simd::hex::bytes_to_hex_32(a)), &|i| ok[i]).0 {
                Some(hi) => (hi, true),
                None => continue,
            },
            None => {
                withheld.insert(eid);
                continue;
            }
        };
        let (head, channel, category) = &group[hi];
        heads.push(FoldedHead { entity_hex, version: head.version, self_hash: head.self_hash, inner_id: head.inner_id, author: head.author.to_bytes(), rebased });
        if let Some(k) = category {
            out.insert(channel.clone(), k.clone());
        }
    }
    let stored = crate::db::community::get_community_roles(&crate::simd::hex::bytes_to_hex_32(&cid.0)).unwrap_or_default();
    for (channel, category) in stored.syncs {
        let Some(ch) = crate::simd::hex::hex_to_bytes_32_checked(&channel) else { continue };
        let eid = super::derive::sync_locator(cid, &ChannelId(ch));
        if floors.contains_key(&crate::simd::hex::bytes_to_hex_32(&eid)) && (withheld.contains(&eid) || !served.contains(&eid)) {
            out.entry(channel).or_insert(category);
        }
    }
    out
}

/// Fold the Channel and Category overwrites (vsk 14, CORD-04 §8) against the settled
/// Roster. Each is judged on itself: its signer holds MANAGE_ROLES and every bit it allows
/// or denies through Roles ranked strictly above its target (a Role's rank, a member's,
/// beneath every Role for `@everyone`). The head is the newest admitted edition, chained
/// from the floor like any Control entity.
#[allow(clippy::too_many_arguments)]
fn fold_overwrites(
    community: &CommunityV2,
    editions: &[ParsedEdition],
    floors: &Floors,
    roles: &crate::community::roles::CommunityRoles,
    banned: &std::collections::BTreeSet<String>,
    sealed: &SealedBy,
    heads: &mut Vec<FoldedHead>,
    gapped: &mut bool,
) -> Vec<crate::community::roles::Overwrite> {
    use crate::community::roles::{OverwriteTarget, Permissions};
    let cid = community.id();
    let owner_hex = community.owner().ok().map(|o| o.to_hex());
    let mut groups: std::collections::BTreeMap<[u8; 32], Vec<(&ParsedEdition, crate::community::roles::Overwrite)>> = Default::default();
    for e in editions.iter().filter(|e| e.vsk == vsk::CHANNEL_ACL && e.binding.is_some()) {
        let Some(o) = super::roles::parse_overwrite_content(&e.content) else { continue };
        let scope = crate::simd::hex::hex_to_bytes_32_checked(&o.scope).expect("parsed");
        let Some(target) = super::roles::overwrite_target_bytes(cid, &o.target) else { continue };
        if super::derive::acl_locator(cid, &scope, &target) == e.entity_id {
            groups.entry(e.entity_id).or_default().push((e, o));
        }
    }
    let mut out = Vec::new();
    let mut withheld: std::collections::BTreeSet<[u8; 32]> = Default::default();
    // A floored overwrite with no edition served at all is withheld too.
    let served: std::collections::BTreeSet<[u8; 32]> = groups.keys().copied().collect();
    for (eid, group) in groups {
        let ok: Vec<bool> = group
            .iter()
            .map(|(e, o)| {
                let ah = e.author.to_hex();
                let rank = match &o.target {
                    OverwriteTarget::Everyone => u32::MAX,
                    // An overwrite names a Role that stands, or nothing.
                    OverwriteTarget::Role(id) => match roles.role(id) {
                        Some(r) => r.position,
                        None => return false,
                    },
                    // The owner holds everything, in every Channel: nothing to overwrite.
                    OverwriteTarget::Member(m) if owner_hex.as_deref() == Some(m.as_str()) => return false,
                    // A banned member holds nothing anywhere (CORD-04 §4).
                    OverwriteTarget::Member(m) if banned.contains(m) => return false,
                    OverwriteTarget::Member(m) => roles.highest_position(m).unwrap_or(u32::MAX),
                };
                if owner_hex.as_deref() == Some(ah.as_str()) {
                    return true;
                }
                if banned.contains(&ah) && !is_listed(sealed, &ah, &e.self_hash) {
                    return false;
                }
                let support = roles.permissions_above(&ah, rank).0 | seal_of(sealed, &ah, &e.self_hash, rank);
                support & Permissions::MANAGE_ROLES != 0 && (o.allow.0 | o.deny.0) & !support == 0
            })
            .collect();
        if !ok.contains(&true) {
            continue;
        }
        let entity_hex = crate::simd::hex::bytes_to_hex_32(&eid);
        let rank = |a: &str| fork_rank(roles, owner_hex.as_deref(), a);
        let fold_eds: Vec<version::Edition> = group.iter().map(|(p, _)| p.to_fold_edition_ranked(rank(&p.author.to_hex()))).collect();
        let floor = floors.get(&entity_hex);
        let (hi, gap) = fold_head_among(&fold_eds, floor, &|a| rank(&crate::simd::hex::bytes_to_hex_32(a)), &|i| ok[i]);
        *gapped |= gap;
        // A held edition that is served but now refused falls back as a reader holding no
        // floor would; only one that isn't served at all is kept as held.
        let held_served = floor.is_some_and(|f| group.iter().any(|(e, _)| held_is(f, e)));
        let (hi, rebased) = match hi {
            Some(hi) => (hi, false),
            None if held_served => match fold_head_among(&fold_eds, None, &|a| rank(&crate::simd::hex::bytes_to_hex_32(a)), &|i| ok[i]).0 {
                Some(hi) => (hi, true),
                None => continue,
            },
            None => {
                withheld.insert(eid);
                continue;
            }
        };
        let (head, o) = &group[hi];
        heads.push(FoldedHead { entity_hex, version: head.version, self_hash: head.self_hash, inner_id: head.inner_id, author: head.author.to_bytes(), rebased });
        if o.allow.0 != 0 || o.deny.0 != 0 {
            out.push(o.clone());
        }
    }
    // What this device held for an overwrite a relay isn't serving stays as it was: absence
    // proves nothing, and the stored roster is what the floor committed to.
    let stored = crate::db::community::get_community_roles(&crate::simd::hex::bytes_to_hex_32(&cid.0)).unwrap_or_default();
    for o in stored.overwrites {
        let (Some(scope), Some(target)) = (crate::simd::hex::hex_to_bytes_32_checked(&o.scope), super::roles::overwrite_target_bytes(cid, &o.target)) else { continue };
        let eid = super::derive::acl_locator(cid, &scope, &target);
        let floored = floors.contains_key(&crate::simd::hex::bytes_to_hex_32(&eid));
        if floored && (withheld.contains(&eid) || !served.contains(&eid)) && !out.iter().any(|x| x.scope == o.scope && x.target == o.target) {
            out.push(o);
        }
    }
    out
}

/// One candidate edition of a role/grant entity — the pool [`select_authorized`]
/// draws the highest AUTHORIZED head from (exactly one of `role`/`grant` is set).
struct AuthorityCand {
    role: Option<crate::community::roles::Role>,
    grant: Option<crate::community::roles::MemberGrant>,
    /// A Tenure (CORD-04 §9): the member it seals, and each standing at its fold position.
    tenure: Option<(String, Vec<Sealed>)>,
    /// What a role candidate stands for (grants are always `Live`).
    kind: RoleKind,
    author: PublicKey,
    /// `author` as hex, and the coordinate of their own Grant, which their citation names.
    author_hex: String,
    grant_hex: String,
    head: FoldedHead,
    /// The `vac` this edition carried (CORD-04 §5). `None` for an owner edition
    /// (supreme, cites nothing) or an uncited one — the latter is refused.
    citation: Option<crate::community::edition::AuthorityCitation>,
    /// The edition this one names as its predecessor.
    prev: Option<[u8; 32]>,
    /// Its entity's persisted floor.
    floor: Option<Floor>,
    /// The entity's held floor edition is among the served candidates.
    held_served: bool,
}

/// One sealed standing from a Tenure: editions whose hash it lists are judged as if their
/// author held `bits` through a Role at `position`.
#[derive(Clone, Debug, PartialEq, Eq)]
struct Sealed {
    position: u32,
    bits: u64,
    heads: std::collections::BTreeSet<[u8; 32]>,
}

/// Each member's sealed standings, from the Tenures the fold admits.
type SealedBy = std::collections::BTreeMap<String, Vec<Sealed>>;

/// The bits sealed for `author` over `hash` by every standing ranked above `reach`, as
/// Roles above it would lend them.
fn seal_of(sealed: &SealedBy, author_hex: &str, hash: &[u8; 32], reach: u32) -> u64 {
    sealed.get(author_hex).into_iter().flatten().filter(|e| e.position < reach && e.heads.contains(hash)).fold(0, |acc, e| acc | e.bits)
}

/// Some Tenure lists `hash` as `author`'s, at whatever standing.
fn is_listed(sealed: &SealedBy, author_hex: &str, hash: &[u8; 32]) -> bool {
    sealed.get(author_hex).is_some_and(|es| es.iter().any(|e| e.heads.contains(hash)))
}

/// What a role-entity edition is, in a Community that folds Roles v2 or doesn't.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum RoleKind {
    Live,
    /// A Role's terminal deletion: it acts on the Role at the rank it stood at.
    Deleted,
    /// `@everyone`, beneath every Role.
    Everyone,
    /// A vsk-1 edition after activation: it links what was built on it, and confers nothing.
    History,
}

impl AuthorityCand {
    /// The very edition its entity's floor records: version and hash, and the signer's
    /// rumor id where the floor has one, since the hash alone admits a re-signed copy.
    fn is_held(&self) -> bool {
        self.floor.is_some_and(|f| self.head.version == f.0 && self.head.self_hash == f.1 && f.2.is_none_or(|id| id == self.head.inner_id))
    }

    /// A same-version rival of a withheld held edition that does not beat the key its
    /// floor recorded (CORD-04 §1). Taking it would let a relay withholding the better
    /// held edition swap in a worse one; a served held edition competes on the tiebreak.
    fn loses_to_floor(&self, roles: &crate::community::roles::RoleIndex<'_>, owner_hex: Option<&str>) -> bool {
        let Some(floor) = self.floor.as_ref().filter(|_| !self.held_served) else { return false };
        if self.head.version != floor.0 || self.head.self_hash == floor.1 {
            return false;
        }
        // Without the held edition its claims are unknown, so no rival can be judged against
        // them: only the owner, who acts whatever the rank, stands in for it.
        if owner_hex != Some(self.author_hex.as_str()) {
            return true;
        }
        let rank_of = |a: &[u8; 32]| fork_rank_in(roles, owner_hex, &crate::simd::hex::bytes_to_hex_32(a));
        let mine = fork_rank_in(roles, owner_hex, &self.author_hex);
        !HeldKey::of(floor, &rank_of).beaten_by(mine, &self.head.inner_id)
    }
}

/// CORD-04 §5 sync floor, resolved against the heads THIS fold pass has accepted.
///
/// Deliberately not the persisted-head helper the kick/hide paths use: this IS the
/// pass that establishes those heads, so an external floor would refuse every
/// non-owner edition on a bootstrap and the roster could never fold. Same rule the
/// spec gives for a dangling `prev` across a Refounding — a fresh joiner takes the
/// authority-verified head as its baseline, a tracking client fails closed per
/// entity — applied to the citation instead of the chain link.
fn citation_ok_in_fold(
    cid: &crate::community::CommunityId,
    heads: &HeadIndex<'_>,
    owner_hex: Option<&str>,
    author: &PublicKey,
    citation: Option<&crate::community::edition::AuthorityCitation>,
) -> bool {
    citation_ok_against(cid, heads, owner_hex, author, citation)
}

/// A fold's heads by entity, for the citation checks it makes per candidate: the first head held
/// for each entity, as a scan of the list would find it.
struct HeadIndex<'a>(crate::fasthash::FastMap<&'a str, (u64, [u8; 32])>);

impl<'a> HeadIndex<'a> {
    fn of(heads: &'a [FoldedHead]) -> Self {
        let mut index = crate::fasthash::FastMap::with_capacity_and_hasher(heads.len(), Default::default());
        for h in heads {
            index.entry(h.entity_hex.as_str()).or_insert((h.version, h.self_hash));
        }
        HeadIndex(index)
    }
}

/// [`citation_ok_against`] for a candidate, whose author's hex and Grant coordinate it carries.
fn citation_ok_of(heads: &HeadIndex<'_>, owner_hex: Option<&str>, c: &AuthorityCand) -> bool {
    if owner_hex == Some(c.author_hex.as_str()) {
        return true;
    }
    crate::community::edition::authority_citation_satisfied_by(|e| heads.0.get(e).copied(), owner_hex, &c.author_hex, &c.grant_hex, c.citation.as_ref())
}

/// Whether `citation` holds against a fold's heads (the CORD-04 §5 sync floor).
fn citation_ok_against(
    cid: &crate::community::CommunityId,
    heads: &HeadIndex<'_>,
    owner_hex: Option<&str>,
    author: &PublicKey,
    citation: Option<&crate::community::edition::AuthorityCitation>,
) -> bool {
    let actor_hex = author.to_hex();
    if owner_hex == Some(actor_hex.as_str()) {
        return true;
    }
    let grant_hex = crate::simd::hex::bytes_to_hex_32(&super::derive::grant_locator(cid, &author.to_bytes()));
    crate::community::edition::authority_citation_satisfied_by(|e| heads.0.get(e).copied(), owner_hex, &actor_hex, &grant_hex, citation)
}

thread_local! {
    /// Refusal reasons from the most recent authority fold on this thread — read by
    /// the roster diagnostic. Diagnostic only; nothing branches on it.
    static AUTHORITY_REFUSALS: std::cell::RefCell<std::collections::BTreeMap<String, &'static str>> =
        const { std::cell::RefCell::new(std::collections::BTreeMap::new()) };
}

/// The authorized roster one fold settles on.
struct Selected {
    roles: crate::community::roles::CommunityRoles,
    heads: Vec<FoldedHead>,
    /// Entities whose whole served chain the Roster refuses, judged on a complete fold:
    /// settled as absent, not missing, so nothing waits on them.
    refused: std::collections::BTreeSet<String>,
    /// Entities whose held head is refused with nothing decided to fall back to: kept.
    carried: std::collections::BTreeSet<String>,
    /// An admitted edition sits above a head out of reach: a link withheld.
    gapped: bool,
    /// Every role and grant edition the last round admitted.
    admitted: crate::fasthash::FastSet<[u8; 32]>,
    /// Each member's sealed standings, from the Tenures admitted.
    sealed: SealedBy,
    /// The fixpoint was reached within its bound.
    converged: bool,
}

type Refusals<'w> = Option<&'w mut std::collections::BTreeMap<String, &'static str>>;

fn refuse(why: &mut Refusals<'_>, c: &AuthorityCand, reason: &'static str) -> Option<Option<u32>> {
    if let Some(m) = why.as_mut() {
        m.insert(c.head.entity_hex.clone(), reason);
    }
    None
}

/// The owner-seeded delegation fixpoint (CORD-04 §1-§3). Per entity it takes the highest
/// edition its author is authorized to write under the roster resolved so far, dropping
/// an unauthorized higher version rather than vanishing the entity. Every edition is
/// judged only on roles ranked strictly above everything it touches (downward support),
/// so each decision rests on decisions above it, the fold has exactly one answer, and
/// this Jacobi iteration reaches it within one round per level. The heads it returns are
/// the floors to advance: an unauthorized forgery never poisons one.
#[allow(clippy::too_many_arguments)]
fn select_authorized(
    cid: &crate::community::CommunityId,
    role_cands: &std::collections::BTreeMap<String, Vec<AuthorityCand>>,
    grant_cands: &std::collections::BTreeMap<String, Vec<AuthorityCand>>,
    tenure_cands: &std::collections::BTreeMap<String, Vec<AuthorityCand>>,
    owner_hex: Option<&str>,
    excluded: &std::collections::BTreeSet<String>,
    // The authority fold is complete (see `fold_authority`): a served held head the Roster
    // refuses may then fall back below its floor, or settle as refused.
    complete: bool,
    // Why each entity was refused, for diagnosis: every gate is otherwise silent.
    mut why: Refusals<'_>,
) -> Selected {
    use crate::community::roles::{CommunityRoles, Permissions};
    let mut accepted = CommunityRoles::default();
    let mut heads: Vec<FoldedHead> = Vec::new();
    let mut refused: std::collections::BTreeSet<String> = Default::default();
    let mut carried: std::collections::BTreeSet<String> = Default::default();
    let mut gapped = false;
    let mut admitted: crate::fasthash::FastSet<[u8; 32]> = Default::default();
    let mut sealed: SealedBy = Default::default();
    let mut converged = false;
    let everyone_hex = crate::simd::hex::bytes_to_hex_32(&super::derive::everyone_locator(cid));
    let bound = 2 * (role_cands.len() + grant_cands.len() + tenure_cands.len()) + 8;
    #[cfg(test)]
    let bound = tests::FOLD_BOUND.with(|b| b.get()).unwrap_or(bound);
    let mut scratch = ReplayScratch::default();
    for _ in 0..bound {
        let mut next = CommunityRoles::default();
        let mut next_heads: Vec<FoldedHead> = Vec::new();
        let mut next_refused: std::collections::BTreeSet<String> = Default::default();
        let mut next_carried: std::collections::BTreeSet<String> = Default::default();
        let mut next_gapped = false;
        let mut next_admitted: crate::fasthash::FastSet<[u8; 32]> = crate::fasthash::FastSet::with_capacity_and_hasher(admitted.len(), Default::default());
        let mut next_sealed: SealedBy = Default::default();
        let cite_heads = HeadIndex::of(&heads);
        let standing = crate::community::roles::RoleIndex::of(&accepted);
        // A ban takes what its target wrote, but not what a Tenure sealed (CORD-04 §9).
        let voided = |cands: &[AuthorityCand]| {
            held_banned(cands, excluded) && !cands.first().and_then(|c| c.floor).is_some_and(|f| f.3.is_some_and(|a| is_listed(&sealed, &crate::simd::hex::bytes_to_hex_32(&a), &f.1)))
        };
        // What an author holds above `reach` for this edition: their Roles, and the standing a
        // Tenure sealed it at.
        let support_for = |ah: &str, c: &AuthorityCand, reach: u32| -> Permissions {
            Permissions(standing.permissions_above(ah, reach).0 | seal_of(&sealed, ah, &c.head.self_hash, reach))
        };

        for (entity, cands) in tenure_cands {
            let claims = |c: &AuthorityCand| c.tenure.iter().flat_map(|(_, es)| es.iter().map(|e| e.position)).min();
            let mut judge = |c: &AuthorityCand, _reach: u32| -> Option<Option<u32>> {
                let (member, entries) = c.tenure.as_ref()?;
                let ah = c.author_hex.as_str();
                let is_sealed = is_listed(&sealed, ah, &c.head.self_hash);
                if excluded.contains(ah) && !is_sealed {
                    return refuse(&mut why, c, "tenure: author banned");
                }
                // Written by whoever reduces the member: never by the member, and the owner
                // needs none.
                if member == ah || owner_hex == Some(member.as_str()) {
                    return refuse(&mut why, c, "tenure: written by its own member, or for the owner");
                }
                if owner_hex != Some(ah) {
                    // Each standing is one the writer could grant: beneath them, with bits
                    // they hold above it.
                    let can = entries.iter().all(|e| {
                        let support = support_for(ah, c, e.position);
                        support.contains(Permissions::MANAGE_ROLES) && e.bits & !support.0 == 0
                    });
                    if !can {
                        return refuse(&mut why, c, "tenure: seals a standing its writer couldn't grant");
                    }
                }
                // A sealed edition stands on its Tenure, not on the Grant it cited.
                if !is_sealed && !citation_ok_of(&cite_heads, owner_hex, c) && c.citation.is_some() {
                    return refuse(&mut why, c, "tenure: cited a grant we cannot resolve");
                }
                Some(None)
            };
            let (picked, gap) = replay(cands, &standing, owner_hex, complete, voided(cands), &claims, &mut judge, &mut next_admitted, &mut scratch);
            next_gapped |= gap;
            let j = match picked {
                Picked::Head(j, rebased) => {
                    next_heads.push(FoldedHead { rebased, ..cands[j].head.clone() });
                    j
                }
                Picked::Carried(j) => {
                    next_heads.push(cands[j].head.clone());
                    next_carried.insert(entity.clone());
                    j
                }
                Picked::Refused => {
                    next_refused.insert(entity.clone());
                    continue;
                }
                Picked::Nothing => continue,
            };
            if let Some((member, entries)) = cands[j].tenure.clone() {
                next_sealed.entry(member).or_default().extend(entries);
            }
        }

        for (entity, cands) in role_cands {
            // A deletion and a legacy edition claim no rank: they act at the one the Role stood at.
            let claims = |c: &AuthorityCand| match c.kind {
                RoleKind::Deleted | RoleKind::History => None,
                _ => c.role.iter().map(|r| r.position).min(),
            };
            let mut judge = |c: &AuthorityCand, reach: u32| -> Option<Option<u32>> {
                let role = c.role.as_ref()?;
                let ah = c.author_hex.as_str();
                if c.kind == RoleKind::History {
                    return refuse(&mut why, c, "role: a vsk-1 edition after Roles v2 activated");
                }
                let is_sealed = is_listed(&sealed, ah, &c.head.self_hash);
                if (excluded.contains(ah) && !is_sealed) || role.position == 0 {
                    return refuse(&mut why, c, "role: author banned or position 0");
                }
                if owner_hex != Some(ah) {
                    // MANAGE_ROLES and every carried bit from roles above the reach: both
                    // rank gates at once (the rank claimed and the rank replaced).
                    let support = support_for(ah, c, reach);
                    if !support.contains(Permissions::MANAGE_ROLES) {
                        return refuse(&mut why, c, "role: author holds no MANAGE_ROLES above what it touches");
                    }
                    // Judged on this edition alone, so a compacted head folds the same for
                    // every reader.
                    if role.permissions.0 & !support.0 != 0 {
                        return refuse(&mut why, c, "role: carries a permission its author lacks");
                    }
                }
                // A `vac` is a sync floor, not the verdict (CORD-04 §5): a citation we
                // can't resolve parks, while an uncited edition declared no floor to wait
                // for. The rank gates above already passed either way.
                if !is_sealed && !citation_ok_of(&cite_heads, owner_hex, c) && c.citation.is_some() {
                    return refuse(&mut why, c, "role: cited a grant we cannot resolve");
                }
                Some((c.kind != RoleKind::Deleted).then_some(role.position))
            };
            let (picked, gap) = replay(cands, &standing, owner_hex, complete, voided(cands), &claims, &mut judge, &mut next_admitted, &mut scratch);
            next_gapped |= gap;
            // Deletion is terminal over the authorized chain, not the head alone (CORD-04 §2):
            // once one stands, the Role is gone whatever was written after it.
            // A deletion acts on the Role at every rank it holds from the deletion on, so one
            // backdated beneath a Role's later life can't reach above its signer.
            let deletion = cands
                .iter()
                .enumerate()
                .filter(|(_, c)| c.kind == RoleKind::Deleted && next_admitted.contains(&c.head.inner_id))
                .filter(|(_, d)| {
                    let later = cands
                        .iter()
                        .filter(|c| c.kind == RoleKind::Live && c.head.version >= d.head.version && next_admitted.contains(&c.head.inner_id))
                        .filter_map(|c| c.role.as_ref().map(|r| r.position))
                        .min();
                    later.is_none_or(|reach| judge(d, reach).is_some())
                })
                .max_by_key(|(_, c)| (c.head.version, std::cmp::Reverse(c.head.inner_id)))
                .map(|(j, _)| j);
            if let Some(j) = deletion {
                let below = cands[j].floor.is_some_and(|f| cands[j].head.version < f.0 || (cands[j].head.version == f.0 && !cands[j].is_held()));
                next_heads.push(FoldedHead { rebased: below, ..cands[j].head.clone() });
                continue;
            }
            let keep = |j: usize, next: &mut CommunityRoles| {
                let role = cands[j].role.clone().expect("a role candidate");
                match cands[j].kind {
                    RoleKind::Everyone => {
                        next.everyone = Some(role.permissions);
                        next.legacy_channels = role.extra.get(EVERYONE_LEGACY).and_then(|l| serde_json::from_value(l.clone()).ok());
                    }
                    RoleKind::Live => next.roles.push(role),
                    // Kept as the head, standing for nothing.
                    RoleKind::Deleted | RoleKind::History => {}
                }
            };
            match picked {
                Picked::Head(j, rebased) => {
                    keep(j, &mut next);
                    next_heads.push(FoldedHead { rebased, ..cands[j].head.clone() });
                }
                Picked::Carried(j) => {
                    keep(j, &mut next);
                    next_heads.push(cands[j].head.clone());
                    next_carried.insert(entity.clone());
                }
                Picked::Refused => {
                    next_refused.insert(entity.clone());
                }
                Picked::Nothing => {}
            }
        }

        for (entity, cands) in grant_cands {
            // A grant confers the roles it names that resolve. It is judged on what it
            // names, never on whether those resolve, so no role can hinge on its absence.
            let claims = |c: &AuthorityCand| {
                c.grant.iter().flat_map(|g| g.role_ids.iter()).filter(|rid| **rid != everyone_hex).filter_map(|rid| standing.role(rid).map(|r| r.position)).min()
            };
            let mut judge = |c: &AuthorityCand, reach: u32| -> Option<Option<u32>> {
                let grant = c.grant.as_ref()?;
                let ah = c.author_hex.as_str();
                let is_sealed = is_listed(&sealed, ah, &c.head.self_hash);
                if (excluded.contains(ah) && !is_sealed) || excluded.contains(&grant.member) {
                    return refuse(&mut why, c, "grant: author or member banned");
                }
                // An uncited edition may add authority, fully rank-checked, but one that
                // names no Role anyone has published is a strip, and a strip must cite.
                if !is_sealed && !citation_ok_of(&cite_heads, owner_hex, c) {
                    if c.citation.is_some() {
                        return refuse(&mut why, c, "grant: cited a grant we cannot resolve");
                    }
                    if grant.role_ids.iter().all(|rid| *rid == everyone_hex || !role_cands.contains_key(rid)) {
                        return refuse(&mut why, c, "grant: UNCITED revocation — a strip must cite its authority");
                    }
                }
                // MANAGE_ROLES from roles above the reach. That also rules out a
                // self-grant: nothing of yours sits above your own standing. The owner
                // is never a target.
                let ok = owner_hex == Some(ah)
                    || (owner_hex != Some(grant.member.as_str()) && support_for(ah, c, reach).contains(Permissions::MANAGE_ROLES));
                if !ok {
                    return refuse(&mut why, c, "grant: author holds no MANAGE_ROLES above the roles or the member");
                }
                Some(claims(c))
            };
            // A banned member holds nothing, whatever their grant's history (CORD-04 §4).
            if cands.first().and_then(|c| c.grant.as_ref()).is_some_and(|g| excluded.contains(&g.member)) {
                next_refused.insert(entity.clone());
                continue;
            }
            let (picked, gap) = replay(cands, &standing, owner_hex, complete, voided(cands), &claims, &mut judge, &mut next_admitted, &mut scratch);
            next_gapped |= gap;
            let (j, rebased) = match picked {
                Picked::Head(j, rebased) => (j, rebased),
                Picked::Carried(j) => {
                    next_carried.insert(entity.clone());
                    (j, false)
                }
                Picked::Refused => {
                    next_refused.insert(entity.clone());
                    continue;
                }
                Picked::Nothing => continue,
            };
            // A revoke still records its head: it is a real chain advance.
            next_heads.push(FoldedHead { rebased, ..cands[j].head.clone() });
            if let Some(grant) = &cands[j].grant {
                let ids: Vec<String> = grant.role_ids.iter().filter(|rid| **rid != everyone_hex && standing.role(rid).is_some()).cloned().collect();
                if !ids.is_empty() {
                    next.grants.push(crate::community::roles::MemberGrant { member: grant.member.clone(), role_ids: ids });
                }
            }
        }

        // Heads count too: a citation is judged against the heads of the round before.
        let same_heads = next_heads.len() == heads.len()
            && next_heads.iter().zip(&heads).all(|(a, b)| (&a.entity_hex, a.self_hash, a.inner_id, a.rebased) == (&b.entity_hex, b.self_hash, b.inner_id, b.rebased));
        let settled = same_heads && next.roles == accepted.roles && next.grants == accepted.grants && next.everyone == accepted.everyone && next.legacy_channels == accepted.legacy_channels && next_sealed == sealed;
        accepted = next;
        sealed = next_sealed;
        heads = next_heads;
        refused = next_refused;
        carried = next_carried;
        gapped = next_gapped;
        admitted = next_admitted;
        if settled {
            converged = true;
            break;
        }
    }
    Selected { roles: accepted, heads, refused, carried, gapped, admitted, sealed, converged }
}

/// The signer the entity's floor records is banned: the held edition is gone with
/// everything else they wrote, served or not.
fn held_banned(cands: &[AuthorityCand], excluded: &std::collections::BTreeSet<String>) -> bool {
    cands.first().and_then(|c| c.floor).and_then(|f| f.3).is_some_and(|a| excluded.contains(&crate::simd::hex::bytes_to_hex_32(&a)))
}

/// An author's authority for ordering a version's siblings, read only from roles ranked
/// above `reach`: the same standing the sibling is judged on, so the order can't lean on
/// authority the decision itself creates.
fn fork_rank_above(roles: &crate::community::roles::RoleIndex<'_>, owner_hex: Option<&str>, author_hex: &str, reach: u32) -> u32 {
    if owner_hex == Some(author_hex) {
        return 0;
    }
    roles.highest_position_above(author_hex, reach).unwrap_or(u32::MAX)
}

enum Picked {
    /// The head's index, and whether it sits below the floor because the held head was refused.
    Head(usize, bool),
    /// The held head is the genesis, served, and refused on a complete fold.
    Refused,
    /// The held head, refused on what is served but with nothing decided to fall back to.
    Carried(usize),
    Nothing,
}

/// What an edition's successor stands on: the rank its nearest admitted ancestor confers,
/// and whether that is known on evidence.
#[derive(Clone, Copy)]
struct Stand {
    standing: Option<u32>,
    proven: bool,
}

/// An entity's editions by hash, each hash's in `cands` order.
#[derive(Default)]
struct HashGroups {
    at: crate::fasthash::FastMap<[u8; 32], (u32, u32)>,
    order: Vec<usize>,
}

impl HashGroups {
    fn build(&mut self, n: usize, hash: impl Fn(usize) -> [u8; 32]) {
        self.at.clear();
        self.order.clear();
        self.order.extend(0..n);
        // Stable, so a hash's indices keep their order.
        self.order.sort_by_key(|&j| hash(j));
        let mut i = 0;
        while i < self.order.len() {
            let h = hash(self.order[i]);
            let run = self.order[i..].iter().take_while(|&&j| hash(j) == h).count();
            self.at.insert(h, (i as u32, run as u32));
            i += run;
        }
    }

    fn get(&self, h: &[u8; 32]) -> Option<&[usize]> {
        self.at.get(h).map(|&(start, len)| &self.order[start as usize..(start + len) as usize])
    }
}

/// What [`replay`] works in, kept across the entities and rounds of one fold: it is filled
/// afresh on every call, so only its allocations carry over.
#[derive(Default)]
struct ReplayScratch {
    by_hash: HashGroups,
    admitted: Vec<bool>,
    sure: Vec<bool>,
    conf: Vec<Option<Option<u32>>>,
    stand: Vec<Stand>,
    key: Vec<(u32, [u8; 32])>,
    viable: Vec<bool>,
    runs: crate::fasthash::FastMap<([u8; 32], u64), (Option<u32>, bool)>,
    reachable: Vec<bool>,
}

fn refill<T: Clone>(v: &mut Vec<T>, n: usize, value: T) {
    v.clear();
    v.resize(n, value);
}

/// One entity's chain, replayed ascending (CORD-04 §1/§3), and its head. Each version acts
/// on what the newest admitted version below it left: never on what its own `prev` names,
/// which its author chooses and so could point at a branch where nothing stood. A link
/// adds to that only when it reaches evidence in hand: through editions the Roster
/// refuses (each perhaps a copy of one that stands, so the stricter rank counts) down to
/// an admitted one, or to the genesis below this device's own held edition. A link names
/// the version directly beneath. `judge` returns the rank an admitted edition confers.
/// Candidates arrive version-DESC. Also returns whether an admitted edition above the
/// head is out of reach, which is a link withheld and worth paging for.
#[allow(clippy::too_many_arguments)]
fn replay(
    cands: &[AuthorityCand],
    accepted: &crate::community::roles::RoleIndex<'_>,
    owner_hex: Option<&str>,
    complete: bool,
    // The held edition's signer is banned: everything they wrote is gone, the floor with it.
    voided: bool,
    // The strictest rank an edition claims.
    claims: &dyn Fn(&AuthorityCand) -> Option<u32>,
    judge: &mut dyn FnMut(&AuthorityCand, u32) -> Option<Option<u32>>,
    // Every edition this replay admits, collected for the caller.
    admitted_out: &mut crate::fasthash::FastSet<[u8; 32]>,
    scratch: &mut ReplayScratch,
) -> (Picked, bool) {
    #[cfg(test)]
    let mut fresh = ReplayScratch::default();
    #[cfg(test)]
    let scratch = if tests::FRESH_SCRATCH.with(|f| f.get()) { &mut fresh } else { scratch };
    let n = cands.len();
    let Some(first) = cands.first() else { return (Picked::Nothing, false) };
    let floor = first.floor;
    let is_owner = |c: &AuthorityCand| owner_hex == Some(c.author_hex.as_str());
    let ReplayScratch { by_hash, admitted, sure, conf, stand, key, viable, runs, reachable } = scratch;
    by_hash.build(n, |j| cands[j].head.self_hash);
    let by_hash = &*by_hash;
    // Copies of one hash share version, predecessor and content; any admitted one stands.
    let node = |h: &[u8; 32], at: u64| by_hash.get(h).filter(|js| cands[js[0]].head.version == at);
    refill(admitted, n, false);
    refill(sure, n, false);
    refill(conf, n, None);
    refill(stand, n, Stand { standing: None, proven: false });
    refill(key, n, (u32::MAX, [0u8; 32]));
    refill(viable, n, false);
    runs.clear();
    // What the newest admitted version left.
    let mut base: Option<u32> = None;

    let mut i = n;
    while i > 0 {
        let hi = i;
        let ver = cands[i - 1].head.version;
        while i > 0 && cands[i - 1].head.version == ver {
            i -= 1;
        }
        for j in i..hi {
            let (constraint, proven) = match cands[j].prev {
                None => (None, ver == 1),
                Some(h) => *runs.entry((h, ver)).or_insert_with(|| link_run(cands, h, ver, by_hash, sure, conf, claims)),
            };
            stand[j] = Stand { standing: stricter(base, constraint), proven };
        }
        let own = |j: usize| claims(&cands[j]).into_iter().chain(stand[j].standing).min().unwrap_or(u32::MAX);
        // A sibling that fails even on its own is out of the running: it can't make the
        // version stricter for the rest.
        for j in i..hi {
            viable[j] = !cands[j].loses_to_floor(accepted, owner_hex) && (hi - i == 1 || judge(&cands[j], own(j)).is_some());
        }
        // One reach for the version: the strictest rank any viable sibling claims or stands
        // on, so a low claim can't lean on authority its own sibling's acceptance creates.
        let reach = (i..hi).filter(|&j| viable[j]).map(own).min().unwrap_or(u32::MAX);
        for j in i..hi {
            let c = &cands[j];
            key[j] = (fork_rank_above(accepted, owner_hex, &c.author_hex, reach), c.head.inner_id);
            conf[j] = if viable[j] { judge(c, reach) } else { None };
            admitted[j] = conf[j].is_some();
            // Decided on evidence: judged with what stood beneath it in hand, signed by the owner,
            // or the version this device settled on.
            sure[j] = admitted[j] && (stand[j].proven || is_owner(c) || floor.is_some_and(|f| f.0 == ver));
            if admitted[j] {
                admitted_out.insert(c.head.inner_id);
            }
        }
        if let Some(w) = (i..hi).filter(|&j| admitted[j]).min_by_key(|&j| key[j]) {
            base = conf[w].flatten();
        }
    }
    let best = |ok: &dyn Fn(usize) -> bool| -> Option<usize> {
        let top = (0..n).filter(|&j| ok(j)).map(|j| cands[j].head.version).max()?;
        (0..n).filter(|&j| ok(j) && cands[j].head.version == top).min_by_key(|&j| key[j])
    };

    let Some(f) = floor.filter(|_| !voided) else {
        if let Some(j) = best(&|j| admitted[j]) {
            return (Picked::Head(j, voided && !cands[j].is_held()), false);
        }
        if !voided {
            return (Picked::Nothing, false);
        }
        // Nothing stands once the banned signer's editions are gone, which is what a reader
        // holding no floor folds too. Page for what stood before them unless the held chain
        // already reads down to its genesis; a chain ending at a compaction pages in vain,
        // but nothing waits on it.
        let mut at = (0..n).find(|&j| cands[j].is_held());
        for _ in 0..HELD_CHAIN_CAP {
            let Some(j) = at else { break };
            let Some(p) = cands[j].prev else { return (Picked::Refused, false) };
            at = cands[j].head.version.checked_sub(1).and_then(|v| node(&p, v)).map(|js| js[0]);
        }
        return (Picked::Refused, true);
    };
    // Reachable from the floor along served links: its version (bar a rival that doesn't
    // beat the held key), then whatever names the held hash or a reachable edition.
    refill(reachable, n, false);
    // Ascending, so a link's target one version down is decided before what names it.
    for j in (0..n).rev() {
        let c = &cands[j];
        reachable[j] = match c.head.version.cmp(&f.0) {
            std::cmp::Ordering::Less => false,
            std::cmp::Ordering::Equal => !c.loses_to_floor(accepted, owner_hex),
            std::cmp::Ordering::Greater => c.prev.is_some_and(|h| {
                (Some(c.head.version) == f.0.checked_add(1) && h == f.1) || node(&h, c.head.version - 1).is_some_and(|js| js.iter().any(|&k| reachable[k]))
            }),
        };
    }
    let gap_above = |v: u64| (0..n).any(|j| admitted[j] && !reachable[j] && cands[j].head.version > v);
    // Above the floor an edition stands on evidence: a withheld link leaves the rank it
    // acts on unknown, and only the owner acts regardless of rank.
    let advance = |j: usize| reachable[j] && admitted[j] && (cands[j].head.version == f.0 || stand[j].proven || is_owner(&cands[j]));
    if let Some(j) = best(&advance) {
        return (Picked::Head(j, false), gap_above(cands[j].head.version));
    }
    // The held edition itself is refused. On a complete fold it falls back to the
    // predecessor it names, when a served copy of that stands on evidence; a genesis has
    // none. A floor recorded without the signer's id can't tell its edition from a copy.
    if !first.held_served {
        return (Picked::Nothing, false);
    }
    let Some(held) = (0..n).find(|&j| cands[j].is_held()) else { return (Picked::Nothing, false) };
    let gap = gap_above(f.0);
    if complete && f.2.is_some() {
        let Some(p) = cands[held].prev else { return (Picked::Refused, gap) };
        let own = |j: usize| claims(&cands[j]).into_iter().chain(stand[j].standing).min().unwrap_or(u32::MAX);
        // Stepping down is judged no lower than the held edition reached, so the choice
        // between keeping it and its predecessor rests only on authority above both.
        let floor_reach = own(held);
        let target = node(&p, f.0.wrapping_sub(1)).and_then(|js| {
            js.iter()
                .copied()
                .filter(|&k| sure[k])
                .filter(|&k| judge(&cands[k], own(k).min(floor_reach)).is_some())
                .min_by_key(|&k| key[k])
        });
        if let Some(k) = target {
            return (Picked::Head(k, true), gap);
        }
    }
    // Refused on what is served, with nothing decided to fall back to: it stays as held.
    (Picked::Carried(held), gap)
}

/// How far a link walk goes before it counts as unresolved.
const LINK_RUN_CAP: usize = 64;
/// How far a voided floor's chain is read for its genesis before it counts as unresolved.
const HELD_CHAIN_CAP: usize = 4096;

/// What naming `h` at version `ver` adds to the rank an edition acts on, and whether that
/// rests on evidence in hand: the walk passes editions the Roster refuses, keeping the
/// strictest rank each could confer, and ends at an admitted copy (proving only as much as
/// that copy was itself decided on evidence), at the genesis below this device's held
/// edition, or unresolved. A walk of refused copies down to a genesis this device never
/// held proves nothing: anyone can serve one.
fn link_run(
    cands: &[AuthorityCand],
    mut h: [u8; 32],
    ver: u64,
    by_hash: &HashGroups,
    sure: &[bool],
    conf: &[Option<Option<u32>>],
    claims: &dyn Fn(&AuthorityCand) -> Option<u32>,
) -> (Option<u32>, bool) {
    let (mut acc, mut through_held, mut at) = (None, false, ver);
    for _ in 0..LINK_RUN_CAP {
        let Some(js) = by_hash.get(&h).filter(|js| cands[js[0]].head.version.checked_add(1) == Some(at)) else { return (None, false) };
        if let Some(&k) = js.iter().find(|&&k| conf[k].is_some()) {
            return (stricter(acc, conf[k].flatten()), js.iter().any(|&k| sure[k]));
        }
        through_held |= js.iter().any(|&k| cands[k].is_held());
        acc = stricter(acc, claims(&cands[js[0]]).into_iter().min());
        at = cands[js[0]].head.version;
        match cands[js[0]].prev {
            Some(p) => h = p,
            None => return if through_held { (acc, true) } else { (None, false) },
        }
    }
    (None, false)
}

/// The stricter of two ranks a successor could stand on; `None` binds nothing.
fn stricter(a: Option<u32>, b: Option<u32>) -> Option<u32> {
    match (a, b) {
        (Some(x), Some(y)) => Some(x.min(y)),
        (x, None) => x,
        (None, y) => y,
    }
}

/// Apply a folded community-metadata head. Relays only overwrite when the edition
/// carries a non-empty list (a metadata edition that omits relays must not blank
/// the working set). Returns whether anything changed.
fn apply_community_metadata(out: &mut CommunityV2, meta: control::CommunityMetadata) -> bool {
    let mut changed = false;
    if out.name != meta.name {
        out.name = meta.name;
        changed = true;
    }
    if out.description != meta.description {
        out.description = meta.description;
        changed = true;
    }
    // Icon/banner apply verbatim, None included — an edition is the full
    // document, so an absent image IS a removal (editors preserve via
    // `CommunityV2::metadata()`).
    if out.icon != meta.icon {
        out.icon = meta.icon;
        changed = true;
    }
    if out.banner != meta.banner {
        out.banner = meta.banner;
        changed = true;
    }
    // Client-extensible + unknown fields ride the fold verbatim so our own
    // editions can carry them forward (CORD-02 §6).
    if out.meta_custom != meta.custom {
        out.meta_custom = meta.custom;
        changed = true;
    }
    if out.meta_extra != meta.extra {
        out.meta_extra = meta.extra;
        changed = true;
    }
    // CAP on the way in. `cap_relays` is the truncate-on-read invariant for every
    // other construction boundary, and the fold is a boundary like any other: an
    // authorized editor is not a trusted one, and an oversize list costs every
    // member a fan-out on each publish and the slowest of N on each fetch
    // (CORD-02 §6 makes trimming explicitly a client's call). Compare against the
    // CAPPED list too — against the raw one, an oversize edition never compares
    // equal, so every fold would report a change and re-save forever.
    let relays = crate::community::cap_relays(meta.relays);
    if !relays.is_empty() && out.relays != relays {
        out.relays = relays;
        changed = true;
    }
    changed
}

/// Apply a folded channel-metadata head: delete removes the channel, a rename
/// updates an existing one, a brand-new PUBLIC channel is added, and a brand-new
/// PRIVATE one is recorded KEYLESS (unreadable until its key arrives over the
/// rekey plane or a fresh bundle). Returns whether anything changed.
fn apply_category_metadata(out: &mut CommunityV2, id: [u8; 32], meta: control::CategoryMetadata) -> bool {
    if meta.deleted == Some(true) {
        let before = out.categories.len();
        out.categories.retain(|c| c.id != id);
        return out.categories.len() != before;
    }
    let mut name = meta.name;
    control::cut_name(&mut name);
    let position = meta.position.filter(|k| crate::community::rank::is_rank_key(k));
    let next = super::community::CategoryV2 { id, name, position, extra: meta.extra };
    let changed = match out.categories.iter_mut().find(|c| c.id == id) {
        Some(c) if *c == next => false,
        Some(c) => {
            *c = next;
            true
        }
        None => {
            out.categories.push(next);
            true
        }
    };
    // Past the cap, the lowest ids stand: the same set however the heads arrived.
    if out.categories.len() > super::community::MAX_CATEGORIES {
        out.categories.sort_by(|a, b| a.id.cmp(&b.id));
        let dropped = out.categories.split_off(super::community::MAX_CATEGORIES);
        return !dropped.iter().any(|c| c.id == id);
    }
    changed
}

/// Fold a sealed head (CORD-03 §2): the Channel stands as private, and its fields come once
/// this device opens the seal ([`unseal_held`]).
fn apply_sealed_channel_metadata(out: &mut CommunityV2, id: ChannelId, s: &control::SealedChannelMeta, raw: &str, prev: Option<[u8; 32]>) -> bool {
    if s.deleted {
        let before = out.channels.len();
        out.channels.retain(|c| c.id.0 != id.0);
        return out.channels.len() != before;
    }
    let sealed = Some(super::community::SealedMeta { epoch: s.epoch, raw: raw.to_string(), open: false, junk: false, prev: prev.map(|p| crate::simd::hex::bytes_to_hex_32(&p)) });
    match out.channels.iter_mut().find(|c| c.id.0 == id.0) {
        // Public → private (CORD-03 §2): keyless until a rotation delivers its key, which the
        // rekey walk looks for from the first channel epoch, as for a Channel met fresh.
        // Public → private (CORD-03 §2): keyless until the rotation that minted its key, which the
        // rekey walk looks for at the sealed edition's own epoch.
        Some(existing) if !existing.private => {
            existing.private = true;
            existing.key = None;
            existing.epoch = Epoch(s.epoch.saturating_sub(1));
            existing.sealed = sealed;
            true
        }
        Some(existing) if existing.sealed.as_ref().is_some_and(|h| h.raw == raw) => false,
        Some(existing) => {
            existing.sealed = sealed;
            true
        }
        None => {
            out.channels.push(ChannelV2 { id, name: String::new(), private: true, key: None, epoch: Epoch(0), voice: None, meta_custom: None, meta_extra: Default::default(), writers: None, sealed });
            true
        }
    }
}

/// Open what this device can of its Private Channels' sealed metadata, with the key of the
/// epoch each is sealed under. A seal that key can't open is junk: the details last read stay.
/// Returns whether anything changed.
pub(crate) fn unseal_held(community: &mut CommunityV2) -> bool {
    let held = community.clone();
    let mut changed = false;
    for ch in community.channels.iter_mut() {
        // Junk is tried again each time: the key held for its epoch may have changed.
        let Some(s) = ch.sealed.clone().filter(|s| !s.open) else { continue };
        let Some(conv) = held.channel(&ch.id).and_then(|c| channel_conv_key_at(&held, c, s.epoch)) else { continue };
        let prev = s.prev.as_deref().and_then(crate::simd::hex::hex_to_bytes_32_checked);
        let opened = control::parse_sealed_channel_meta(&s.raw).and_then(|parsed| control::open_sealed_channel_meta(&parsed, &conv, prev.as_ref()));
        match opened.map(control::sanitize_channel_metadata) {
            Some(meta) => {
                ch.name = meta.name;
                ch.voice = meta.voice;
                ch.meta_custom = meta.custom;
                ch.meta_extra = meta.extra;
                ch.sealed = Some(super::community::SealedMeta { open: true, junk: false, ..s });
            }
            None if s.junk => continue,
            None => ch.sealed = Some(super::community::SealedMeta { junk: true, ..s }),
        }
        changed = true;
    }
    changed
}

fn apply_channel_metadata(out: &mut CommunityV2, id: ChannelId, meta: control::ChannelMetadata) -> bool {
    let deleted = meta.deleted.unwrap_or(false);
    if deleted {
        let before = out.channels.len();
        out.channels.retain(|c| c.id.0 != id.0);
        return out.channels.len() != before;
    }
    match out.channels.iter_mut().find(|c| c.id.0 == id.0) {
        Some(existing) => {
            let mut changed = false;
            if existing.name != meta.name {
                existing.name = meta.name;
                changed = true;
            }
            // vsk-2 fields Vector doesn't drive still fold + persist, so a later
            // local edit republishes them instead of wiping (CORD-02 §6).
            if existing.voice != meta.voice {
                existing.voice = meta.voice;
                changed = true;
            }
            if existing.meta_custom != meta.custom {
                existing.meta_custom = meta.custom;
                changed = true;
            }
            if existing.meta_extra != meta.extra {
                existing.meta_extra = meta.extra;
                changed = true;
            }
            if existing.sealed.take().is_some() {
                changed = true;
            }
            // The owner's edition authoritatively declares visibility. A channel the
            // owner marks PUBLIC must derive from the root (key = None) — this heals a
            // bundle-time misclassification where an attacker set a public channel's
            // grant key to their own, silently addressing it at a plane only they read.
            // A plain edition never makes a Channel private: that takes the sealed form and its
            // key rotation (CORD-03 §2).
            if !meta.private && (existing.private || existing.key.is_some()) {
                existing.private = false;
                existing.key = None;
                changed = true;
            }
            changed
        }
        None if !meta.private => {
            // A public channel derives its Chat Plane from the community_root at the
            // current root epoch (key = None); its stored epoch mirrors the root.
            out.channels.push(ChannelV2 {
                id,
                name: meta.name,
                private: false,
                key: None,
                epoch: out.root_epoch,
                voice: meta.voice,
                meta_custom: meta.custom,
                meta_extra: meta.extra,
                writers: None,
                sealed: None,
            });
            true
        }
        None => {
            // A brand-new PRIVATE channel: record it KEYLESS at epoch 0 (the root
            // generation — CORD-03 §2 numbers the first private key epoch 1). The
            // epoch then doubles as [`follow_rekeys`]' scan cursor. Until a rotation
            // delivers a key, every read/send/subscribe path skips the channel; the
            // root-fallback in `channel_secret` is never taken for it.
            out.channels.push(ChannelV2 {
                id,
                name: meta.name,
                private: true,
                key: None,
                epoch: Epoch(0),
                voice: meta.voice,
                meta_custom: meta.custom,
                meta_extra: meta.extra,
                writers: None,
                sealed: None,
            });
            true
        }
    }
}

// ── Live rekey-follow (CORD-06 §2/§3) ────────────────────────────────────────

/// The outcome of a rekey-follow pass.
pub struct RekeyFollow {
    /// The community after adopting every rotation it could catch up on, or `None`
    /// if nothing advanced.
    pub updated: Option<CommunityV2>,
    /// A base rotation removed us — the caller tears the local hold down (the
    /// updated community is not persisted in that case).
    pub self_removed: bool,
    /// When that rotation was sent, in ms: the eviction's own time.
    pub removed_at: Option<u64>,
    /// An owner tombstone sits on the dissolved plane (CORD-02 §9) — the local
    /// flag is already set; the caller surfaces the death and stops following.
    pub dissolved: bool,
    /// A complete authorized rotation carried a blob AT OUR LOCATOR that would
    /// not open (a width this build predates, a rotator bug, or a deliberately
    /// undecryptable blob planted to pass an admissibility check while severing
    /// us). Never a removal (CORD-06 §2: removal is the ABSENCE of a blob), so
    /// the walk parks — but the park is otherwise indistinguishable from "no
    /// rotation happened", which is exactly what makes it abusable. Surfaced so
    /// the user learns their key delivery is broken while the prior root still
    /// reaches everyone.
    pub wedged: bool,
}

/// The most archived base roots a channel-rekey lookup fans across per step. A
/// standalone rekey rides the minter's then-current root and a removal's rides the
/// PRIOR root (CORD-06 §3), so a follower whose base already advanced must look
/// back. A channel stranded DEEPER than this (its next-epoch crate addressed under
/// an older root than the fan reaches) only heals via a fresh invite bundle — the
/// walk is strictly sequential, so a later rotation can't be reached either.
const MAX_ADDRESSING_ROOTS: usize = 8;

/// The base roots a channel rekey may be addressed under, freshest first: the
/// current root plus the archived priors, capped at [`MAX_ADDRESSING_ROOTS`].
/// CORD-06 D2: a removal-forced channel rekey rides the PRIOR root — so the
/// follower's fetch fan ([`follow_rekeys`]) and the stream-auth registration
/// (`streamauth::register_community`) MUST cover the SAME set. A plane the
/// fetch addresses but auth never registered is invisible on an AUTH-gating
/// relay: the REQ is CLOSED, the rotation crate never arrives, and the channel
/// wedges at its old epoch while the base advances.
pub(crate) fn channel_rekey_addressing_roots(cur_root: [u8; 32], cid_hex: &str) -> Vec<[u8; 32]> {
    let mut roots: Vec<[u8; 32]> = vec![cur_root];
    let mut archived = crate::db::community::held_epoch_keys(cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX)
        .unwrap_or_default();
    archived.sort_by_key(|a| std::cmp::Reverse(a.0 .0));
    for (_, r) in archived {
        if !roots.contains(&r) {
            roots.push(r);
        }
    }
    roots.truncate(MAX_ADDRESSING_ROOTS);
    roots
}

/// Follow rekeys for a held community: advance the base (root) epoch and each
/// Private channel's epoch as far as authorized rotations allow, adopting the
/// fresh key we're still a recipient of at each step and dropping a scope we've
/// been removed from. Persists the result. Called when a rekey wrap arrives in
/// realtime so a long-running bot keeps decrypting after a rotation instead of
/// going silent.
///
/// **Authority (CORD-06 §Authority):** a BASE rotation is honored from the owner
/// or any `BAN` holder, and a CHANNEL rotation from the owner or a
/// `MANAGE_CHANNELS` holder — both under the PERSISTED roster (folded by
/// `follow_control`), minus the banlist, so an admin-created private channel
/// keys up on every member. Concluding OUR OWN removal takes more than the bit:
/// the rotator must strictly outrank us (`*_outranks_me`), so an equal-rank
/// admin can never evict a peer by minting a rotation that skips their blob.
///
/// **Addressing fans across held base roots:** each channel step queries its
/// next-epoch rekey address under the current root AND the archived prior roots,
/// so a base adopt landing before a Refounding's prior-root-addressed channel
/// rekeys (or before a creation delivery minted under an older root) can't
/// strand the channel.
///
/// **Continuity + fork resolution are spec-strict:** a rotation must extend the
/// exact `(epoch, key)` I hold, one epoch at a time; a same-epoch fork resolves
/// by the lexicographically lowest new key ([`rekey::lowest_key_winner`]), so
/// every follower converges. An incomplete rotation (a missing chunk) never
/// concludes removal — it just waits. A KEYLESS channel (announced by vsk-2, key
/// not yet delivered) holds no chain, so continuity is vacuous for it (CORD-06
/// §2: "a convergence check, not a secrecy mechanism") — authority is its
/// boundary; its epoch is the scan cursor, advancing past complete rotations
/// that exclude us so the walk converges on the channel's current epoch.
/// Explain this client's epoch state: what we hold, what the next-epoch base plane
/// offers, and — per rotation found there — exactly which `advance_scope` gate
/// decided we did or did not adopt it.
///
/// **Ships in release builds deliberately.** A strand is silent by construction: a
/// client parked on a dead epoch is subscribed at its own addresses and simply sees
/// nothing, which is indistinguishable from a quiet community. Answering "why is
/// this client stuck" without this meant reading sqlite by hand. It is also the
/// instrument for comparing two clients' views of one community — the local half
/// (`held`) is what diverges first.
///
/// Read-only, and safe to surface: every rotator/owner is a PUBLIC key, and no key
/// material, blob plaintext or roster secret is returned.
pub async fn explain_epoch_state<T: Transport + ?Sized>(
    transport: &T,
    community: &CommunityV2,
) -> Result<serde_json::Value, String> {
    let my_xonly = me_pk()?.to_bytes();
    let owner = community.owner()?;
    let owner_hex = owner.to_hex();
    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
    let roster = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
    let banned = crate::db::community::get_community_banlist(&cid_hex).unwrap_or_default();
    let held_epoch = community.root_epoch;
    let held_key = community.community_root;
    let next = Epoch(held_epoch.0.saturating_add(1));
    let group = base_rekey_group_key(&held_key, community.id(), next);
    let chunks = fetch_rekey_chunks(transport, &community, &group).await?;
    let rotations = rekey::collect_rotations(&chunks);

    let reports: Vec<serde_json::Value> = rotations
        .iter()
        .map(|r| {
            let rotator_is_owner = r.rotator == owner;
            // CORD-06 §Authority: a Refounding is authorized by BAN in the folded
            // Roster, not owner-identity — report that gate, not just owner-equality.
            let rotator_authorized = rotator_is_owner
                || (!banned.contains(&r.rotator.to_hex())
                    && roster.is_authorized(&r.rotator.to_hex(), Some(&owner_hex), crate::community::roles::Permissions::BAN));
            let scope_ok = r.scope.id32() == rekey::RekeyScope::Root.id32();
            let epoch_ok = r.new_epoch.0 == next.0;
            let complete = r.is_complete();
            let continuity = format!("{:?}", r.continuity(held_epoch, &held_key));
            let has_my_blob = rekey::find_my_blob(&r.blobs, &r.rotator.to_bytes(), &my_xonly, r.scope, r.new_epoch).is_some();
            // Is the OWNER a recipient? A non-owner Refounding that drops the owner
            // is a takeover attempt — this tells whether an "owner must be kept"
            // adopt-block would be safe here (it would falsely reject a legitimate
            // rotation that happened to exclude the owner).
            let owner_kept = r.rotator == owner
                || rekey::find_my_blob(&r.blobs, &r.rotator.to_bytes(), &owner.to_bytes(), r.scope, r.new_epoch).is_some();
            // The exact reason follow_rekeys skipped/rejected this rotation, in gate order.
            let verdict = if !rotator_authorized {
                "REJECTED: rotator holds no BAN authority in the folded roster"
            } else if !scope_ok {
                "REJECTED: scope is not Root"
            } else if !epoch_ok {
                "REJECTED: new_epoch != held+1"
            } else if !complete {
                "WAIT: rotation incomplete (missing chunk) — never concludes removal"
            } else if continuity != "Extends" {
                "REJECTED: continuity does not extend my held root (FORK/GAP)"
            } else if has_my_blob {
                "ADOPT: authorized + complete + continuous + my blob present"
            } else {
                "REMOVED: complete authorized rotation with no blob for me"
            };
            serde_json::json!({
                "rotator": r.rotator.to_hex(),
                "rotator_is_recorded_owner": rotator_is_owner,
                "rotator_authorized_ban": rotator_authorized,
                "scope_is_root": scope_ok,
                "new_epoch": r.new_epoch.0,
                "prev_epoch": r.prev_epoch.0,
                "declared_chunks": r.declared_chunks,
                "held_chunks": r.held_chunks.iter().copied().collect::<Vec<_>>(),
                "is_complete": complete,
                "continuity_vs_held_root": continuity,
                "my_blob_present": has_my_blob,
                "owner_kept": owner_kept,
                "blob_count": r.blobs.len(),
                "severing": r.severed,
                "verdict": verdict,
            })
        })
        .collect();

    // The LOCAL half. Two clients on one community diverge here first, and every
    // field is a thing that has silently frozen a client in the field: the roster
    // is what authorizes a rotator, its provenance is what the freeze-guard reads,
    // and the invite registry is what Public/Private hangs off.
    let roster_at = crate::db::community::get_community_roles_at(&cid_hex).unwrap_or(0);
    let admin_count = roster.grants.iter().filter(|g| roster.is_admin(&g.member)).count();
    let control_wraps = {
        let view = control_store::View::of(community);
        let (bodies, refusals, bytes) = view.counts().unwrap_or_default();
        serde_json::json!({ "mode": format!("{:?}", control_store::mode()), "held": bodies, "refused": refusals, "bytes": bytes, "sync": control_sync::report(community, &view) })
    };
    let held = serde_json::json!({
        "root_epoch": held_epoch.0,
        "roster_roles": roster.roles.len(),
        "roster_grants": roster.grants.len(),
        "roster_admins": admin_count,
        // 0 = a locally-seeded roster that never folded from the plane. A client
        // whose roster never gains provenance can never authorize a non-owner
        // admin, so it refuses their rotations forever.
        "roster_provenance_at": roster_at,
        "banlist_entries": banned.len(),
        "sever_marks": sever_marks(&cid_hex).keys().copied().collect::<Vec<_>>(),
        "control_plane_split": community.control_pk.is_some(),
        "private_channels": community.channels.iter().filter(|c| c.private).count(),
        "channels_awaiting_key": community.channels.iter().filter(|c| c.private && c.key.is_none()).count(),
        // What is held of the Control Plane, and how each relay's last pass against it ended.
        "control_wraps": control_wraps,
    });

    // The one-line answer. `probing_next_epoch` existing at all proves the community
    // moved without us; what we did about it is the `rotations` verdicts.
    let summary = if rotations.is_empty() {
        "UP TO DATE (or the plane is unreachable): no rotation offered at held+1"
    } else if reports.iter().any(|r| r["verdict"].as_str().is_some_and(|v| v.starts_with("ADOPT"))) {
        "BEHIND: an adoptable rotation is waiting — run a sync"
    } else {
        "WEDGED: a rotation exists at held+1 and every one was refused (see verdicts)"
    };

    Ok(serde_json::json!({
        "summary": summary,
        "recorded_owner": owner.to_hex(),
        "held": held,
        "held_root_epoch": held_epoch.0,
        "probing_next_epoch": next.0,
        "base_plane_pk": group.pk_hex(),
        "raw_chunks_parsed": chunks.len(),
        "rotations_found": rotations.len(),
        "rotations": reports,
    }))
}

/// Wide enough to collapse a large community's channel fan into one wave, narrow enough that a
/// catch-up does not present as a burst to every relay.
const CHANNEL_FAN_CONCURRENCY: usize = 8;

/// What one hop of a rekey walk reads, before any of it is judged.
struct RekeyHop {
    /// The roots a channel rekey may be addressed under: #0 the current one, then archived
    /// priors. Shared with streamauth, so the auth registration covers exactly this fan.
    roots: Vec<[u8; 32]>,
    /// Each private Channel as held: its key, its epoch, and the epoch read for.
    fan: Vec<(ChannelId, Option<[u8; 32]>, Epoch, Epoch)>,
    /// A Channel's next-epoch chunks by `(channel, root index)`, where any were found.
    channels: std::collections::HashMap<([u8; 32], usize), Vec<rekey::RekeyChunk>>,
    /// The base plane's next-epoch chunks.
    base: Vec<rekey::RekeyChunk>,
}

/// Read one hop in a single concurrent wave: every private Channel's next epoch under each
/// addressing root, and the base plane's. Serially this is `channels x roots + 1` round trips
/// before a hop can be decided, a week's absence walks dozens of hops, and every follow pays
/// one hop even when nothing rotated. Only the reads overlap: the walk still judges channels
/// first (a removal-forced channel rekey rides the PRIOR root, CORD-06 D2), then the base.
async fn read_rekey_hop<T: Transport + ?Sized>(transport: &T, cur: &CommunityV2, cid_hex: &str) -> Result<RekeyHop, String> {
    use futures_util::stream::StreamExt;
    let roots = channel_rekey_addressing_roots(cur.community_root, cid_hex);
    let fan: Vec<(ChannelId, Option<[u8; 32]>, Epoch, Epoch)> =
        cur.channels.iter().filter(|c| c.private).map(|ch| (ch.id, ch.key, ch.epoch, Epoch(ch.epoch.0.saturating_add(1)))).collect();
    // root #0 = current, #1.. = archived priors (indices only: root bytes are key material
    // and must never reach a log).
    let jobs: Vec<(ChannelId, usize, GroupKey, Epoch)> = fan
        .iter()
        .flat_map(|(cid, _, _, next)| roots.iter().enumerate().map(move |(ri, root)| (*cid, ri, channel_rekey_group_key(root, cid, *next), *next)))
        .collect();
    let channels = async {
        let mut found = std::collections::HashMap::new();
        let mut results = futures_util::stream::iter(jobs)
            .map(|(cid, ri, group, next)| async move { (cid, ri, next, fetch_rekey_chunks(transport, cur, &group).await) })
            .buffer_unordered(CHANNEL_FAN_CONCURRENCY);
        while let Some((cid, ri, next, out)) = results.next().await {
            let ch_hex = crate::simd::hex::bytes_to_hex_32(&cid.0);
            match out {
                Ok(chunks) if chunks.is_empty() => {}
                Ok(chunks) => {
                    crate::log_debug!("[v2:follow {}] ch {} next e{} root#{}/{}: {} rekey chunk(s)", &cid_hex[..8], &ch_hex[..8], next.0, ri, roots.len(), chunks.len());
                    found.insert((cid.0, ri), chunks);
                }
                Err(e) => {
                    crate::log_warn!("[v2:follow {}] ch {} next e{} root#{}/{}: rekey plane fetch failed: {}", &cid_hex[..8], &ch_hex[..8], next.0, ri, roots.len(), e);
                    return Err(e);
                }
            }
        }
        Ok(found)
    };
    let base_group = base_rekey_group_key(&cur.community_root, cur.id(), Epoch(cur.root_epoch.0.saturating_add(1)));
    let (channels, base) = futures_util::future::join(channels, fetch_rekey_chunks(transport, cur, &base_group)).await;
    let (channels, base) = (channels?, base?);
    Ok(RekeyHop { roots, fan, channels, base })
}

pub async fn follow_rekeys<T: Transport + ?Sized>(
    transport: &T,
    community: &CommunityV2,
    session: &std::sync::Arc<crate::db::Session>,
) -> Result<RekeyFollow, String> {
    crate::db::scoped(async move {
        // Death wins every race (CORD-02 §9): a dissolved community honors no epoch advance
        // past its tombstone — don't adopt a rotation into a grave.
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        if crate::db::community::get_community_dissolved(&cid_hex).unwrap_or(false) {
            return Ok(RekeyFollow { updated: None, self_removed: false, removed_at: None, dissolved: true, wedged: false });
        }
        // An offline member must also LEARN of a death: the tombstone rides its own
        // public plane, which the live sub watches but no catch-up fetch touched —
        // without this, a member who slept through a dissolution follows (and posts
        // into) a grave forever. Fail-open on transport failure: availability is
        // never death.
        //
        // The first hop's planes are read alongside: nothing is decided until both are in.
        let (dead, first_hop) = futures_util::future::join(is_dissolved(transport, community), read_rekey_hop(transport, community, &cid_hex)).await;
        if dead {
            if session.is_live() {
                let _ = crate::db::community::set_community_dissolved(&cid_hex);
            }
            return Ok(RekeyFollow { updated: None, self_removed: false, removed_at: None, dissolved: true, wedged: false });
        }
        let mut first_hop = Some(first_hop);
        let signer = crate::signer::active_signer()?;
        let my_pk = me_pk()?;
        let my_xonly = my_pk.to_bytes();
        let owner = community.owner()?;
        let owner_hex = owner.to_hex();
        let mut cur = community.clone();
        let mut changed = false;
        // A rotation delivered us a blob we could not open (see RekeyFollow::wedged).
        let mut wedged = false;

        // The rotator/admissibility gates read the PERSISTED roster (folded by a prior
        // follow_control; the worker folds control right after this rekey pass). This
        // is "one pass late" for the rotator-AUTHORIZATION direction (a newly-granted
        // admin's rotation adopts a pass late, never early — safe). It is fail-OPEN for
        // the base-admissibility protected-set: a superior whose grant this receiver
        // has not yet folded is not in `roster.grants`, so a non-owner Refounding
        // excluding them can be adopted within that propagation window. Bounded — the
        // owner is ALWAYS hard-protected below (independent of the roster) and can
        // counter-refound; and it is inherent to eventual consistency (one cannot gate
        // on a grant never seen). Tightening this (fold control before the first rekey,
        // or gate non-owner adoption on roster freshness) is a follow-on.
        let roster = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
        let banned = crate::db::community::get_community_banlist(&cid_hex).unwrap_or_default();
        let me_hex = my_pk.to_hex();
        // CORD-06 §Authority: "a rotation cites the Grant it acts under like any
        // authority action (CORD-04's `vac`), so a just-demoted admin's rotation is
        // never honored by a lagging client." Persisted heads ARE the right floor
        // here (unlike the roster fold, which must resolve in-pass): a rotation is
        // judged against a roster we already folded, and `follow_control` — v2's only
        // roster writer — persists the heads in the same pass it writes the roster.
        // A joiner who sees a rotation before folding control simply parks it and
        // heals on the next follow, which runs control first.
        let cited_ok = |rot: &rekey::Rotation| -> bool {
            citation_is_synced(&cid_hex, &owner_hex, &rot.rotator.to_hex(), rot.citation.as_ref())
        };
        let channel_rotator_ok = |rotator: &PublicKey| -> bool { rotates_channels(&roster, &owner_hex, banned.iter(), &rotator.to_hex()) };
        // Concluding MY removal takes more than the bit: the rotator must strictly
        // outrank ME (CORD-06 §Authority — "the Rotator must strictly outrank every
        // removed target"), so an equal-rank admin can never silently evict a peer
        // (or the owner) by minting a complete rotation that skips their blob.
        let channel_rotator_outranks_me = |rotator: &PublicKey| -> bool {
            if *rotator == owner {
                return true;
            }
            let rh = rotator.to_hex();
            rotates_channels(&roster, &owner_hex, banned.iter(), &rh) && roster.can_act_on_member(&rh, Some(&owner_hex), &me_hex, channel_rotation_bit(&roster, &owner_hex, &rh))
        };
        // CORD-06 §Authority: a Refounding requires the BAN permission in the folded
        // Roster (NOT owner-identity) — any admin holding BAN may perform it, checked
        // against the Roster exactly like a channel rekey checks MANAGE_CHANNELS. The
        // owner is always authorized. (Owner-only here silently wedged every member
        // whose community was refounded by a non-owner admin.)
        let base_rotator_ok = |rotator: &PublicKey| -> bool {
            if *rotator == owner {
                return true;
            }
            let rh = rotator.to_hex();
            !banned.contains(&rh) && roster.is_authorized(&rh, Some(&owner_hex), crate::community::roles::Permissions::BAN)
        };
        // Concluding MY removal via a base rotation takes more than the bit: the
        // rotator must strictly outrank ME with BAN (CORD-06 §Authority — "the
        // Rotator must strictly outrank every removed target"), so an equal-rank
        // admin can never evict a peer (or the owner) by minting a rotation that
        // skips their blob. Adoption (I hold a blob) only needs `base_rotator_ok`.
        let base_rotator_outranks_me = |rotator: &PublicKey| -> bool {
            if *rotator == owner {
                return true;
            }
            let rh = rotator.to_hex();
            !banned.contains(&rh) && roster.can_act_on_member(&rh, Some(&owner_hex), &me_hex, crate::community::roles::Permissions::BAN)
        };

                // A non-owner Refounding may only remove members the rotator strictly
        // OUTRANKS. The protected set is the owner plus every grant-holder the
        // rotator can't act on with BAN (a peer or superior) — excluding one is
        // an authority-escalation takeover, so its rotation is inadmissible.
        // Plain members hold no grant and are always outranked by a BAN-holder,
        // so removing them is legitimate and needs no memberlist.
        let base_admissible = |r: &rekey::Rotation| -> bool {
            if r.rotator == owner {
                return true; // the owner is supreme.
            }
            // Uncited (or citing a Grant we haven't synced) → skip entirely:
            // neither adopt nor conclude a removal, exactly like an
            // unauthorized rotation. It parks and heals on the next follow.
            if !cited_ok(r) {
                return false;
            }
            let rotator_hex = r.rotator.to_hex();
            let has_blob = |xonly: &[u8; 32]| {
                rekey::find_my_blob(&r.blobs, &r.rotator.to_bytes(), xonly, r.scope, r.new_epoch).is_some()
            };
            // The owner is never a valid removed target.
            if !has_blob(&owner.to_bytes()) {
                return false;
            }
            for g in &roster.grants {
                if g.member == rotator_hex || g.member == owner_hex || banned.contains(&g.member) {
                    continue; // self, owner (checked), or an already-authorized removal.
                }
                // A grant-holder the rotator can't act on is a peer/superior.
                if !roster.can_act_on_member(&rotator_hex, Some(&owner_hex), &g.member, crate::community::roles::Permissions::BAN) {
                    if let Ok(pk) = PublicKey::from_hex(&g.member) {
                        if !has_blob(&pk.to_bytes()) {
                            return false; // a peer/superior was excluded.
                        }
                    }
                }
            }
            true
        };

        // Containment hops adopted in this walk (B2: any one of them condemns —
        // a later ordinary hop in the same walk must not relaunder links open).
        let mut severed_hops: Vec<u64> = Vec::new();

        // ── Same-epoch convergence, BEFORE walking forward (CORD-06 §3) ─────────
        //
        // Two authorized rotators can mint the same epoch concurrently. The spec's
        // tiebreak is deterministic — the lexicographically lowest new base key wins
        // — but it was only ever applied among rotations seen in ONE fetch. A client
        // that saw only the higher sibling adopted it and then looked exclusively
        // for its successor, so the lower sibling became permanently unreachable:
        // two halves of a community, both at the same epoch number, different keys,
        // unable to read each other, forever. Nobody was misbehaving.
        //
        // So re-check the epoch we ALREADY hold on every follow, and step sideways
        // onto a strictly lower sibling. Down-only, exactly as the spec requires: a
        // held epoch converges only downward, so a flaky fetch that returns just the
        // higher sibling can never re-fork a settled epoch, and the walk terminates
        // because each convergence strictly decreases the held key.
        //
        // The losing branch's key is simply dropped. Messages already ingested from
        // it stay readable — they are stored decrypted under the account vault, not
        // re-derived from the epoch key — so converging costs only the fork-window
        // messages this client never fetched, which live on a branch nobody reads.
        if cur.root_epoch.0 > 0 {
            let prior = crate::db::community::held_epoch_key(
                &cid_hex,
                crate::community::SERVER_ROOT_SCOPE_HEX,
                cur.root_epoch.0 - 1,
            )
            .ok()
            .flatten();
            if let Some(prior_root) = prior {
                let group = base_rekey_group_key(&prior_root, cur.id(), cur.root_epoch);
                match fetch_rekey_chunks(transport, &cur, &group).await {
                    Ok(siblings) if !siblings.is_empty() => {
                        let held_before = cur.community_root;
                        match advance_scope(
                            &[(siblings, Some((Epoch(cur.root_epoch.0 - 1), prior_root)))],
                            RekeyScope::Root,
                            cur.id(),
                            &base_rotator_ok,
                            &base_rotator_outranks_me,
                            &base_admissible,
                            &signer,
                            &my_xonly,
                            cur.root_epoch,
                        )
                        .await
                        {
                            // Strictly lower only. Equal = the branch we already hold.
                            Advance::Adopt { new_key, control_pk, control_root, severed, rotator } if new_key < held_before => {
                                crate::log_warn!(
                                    "[v2:follow {}] same-epoch fork at epoch {} — converging DOWN onto the canonical sibling",
                                    &cid_hex[..8.min(cid_hex.len())], cur.root_epoch.0
                                );
                                cur.community_root = new_key;
                                cur.control_pk = control_pk.and_then(|pk| PublicKey::from_slice(&pk).ok());
                                cur.control_root = control_root;
                                // Everything the sibling carries, as if it had been adopted first.
                                record_epoch_minter(&cid_hex, cur.root_epoch.0, &rotator.to_hex());
                                if severed {
                                    severed_hops.push(cur.root_epoch.0);
                                    // Recorded now: a walk that fails later must not forget it.
                                    add_sever_mark(&cid_hex, cur.root_epoch.0, now_ms() / 1000);
                                }
                                if let Err(e) = crate::db::community::store_epoch_key(
                                    &cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX, cur.root_epoch.0, &new_key,
                                ) {
                                    crate::log_warn!("v2: converged epoch-key archive failed: {e}");
                                }
                                if matches!(crate::db::community::community_held(community.id()), Ok(true)) {
                                    let _ = crate::db::community::save_community_v2(&cur);
                                }
                                changed = true;
                            }
                            // A sibling we cannot open is NOT a removal: refusing to
                            // converge parks us on a branch that still works, where
                            // concluding removal here would delete the community over
                            // a fork we merely could not read.
                            _ => {}
                        }
                    }
                    Ok(_) => {}
                    Err(e) => crate::log_warn!(
                        "[v2:follow {}] same-epoch fork check failed (will retry): {}",
                        &cid_hex[..8.min(cid_hex.len())], e
                    ),
                }
            }
        }

        // Bound the catch-up: each real step consumes a valid authorized rotation, so a
        // finite chain terminates naturally; the cap defends against a relay feeding a
        // pathological set.
        const MAX_STEPS: usize = MAX_WALK_STEPS;
        for _ in 0..MAX_STEPS {
            let mut advanced = false;

            // Read against the state this hop decides on: the one read ahead stands only while
            // the convergence above left the root where it was.
            let hop = match first_hop.take().filter(|_| !changed) {
                Some(read) => read?,
                None => read_rekey_hop(transport, &cur, &cid_hex).await?,
            };
            let RekeyHop { roots: addressing_roots, fan, channels: mut prefetched, base } = hop;

            for (cid, held_key, held_epoch, next) in fan {
                let ch_hex = crate::simd::hex::bytes_to_hex_32(&cid.0);
                let mut batches: Vec<RekeyBatch> = Vec::new();
                for ri in 0..addressing_roots.len() {
                    if let Some(chunks) = prefetched.remove(&(cid.0, ri)) {
                        // A rotation committing to the root it is addressed under is a Public Channel
                        // made private (CORD-03 §2), from someone who could make it public: it extends
                        // an earlier private era's key too.
                        if held_key.is_some() {
                            let converts: Vec<rekey::RekeyChunk> = chunks
                                .iter()
                                .filter(|c| c.rotator == owner || roster.is_authorized(&c.rotator.to_hex(), Some(&owner_hex), crate::community::roles::Permissions::MANAGE_CHANNELS))
                                .cloned()
                                .collect();
                            if !converts.is_empty() {
                                batches.push((converts, Some((held_epoch, addressing_roots[ri]))));
                            }
                        }
                        batches.push((chunks, held_key.map(|k| (held_epoch, k))));
                    }
                }
                // Keyless-adopt residual (documented, deferred hardening): a malicious
                // AUTHORIZED admin can fork a keyless member onto an orphan low-key
                // rotation nothing extends (keyed members' continuity filters it out).
                // Recoverable via a fresh bundle; an insider with MANAGE_CHANNELS can
                // exclude the member outright anyway, so the marginal harm is the wedge
                // outliving their demotion.
                match advance_scope(&batches, RekeyScope::Channel(cid), cur.id(), &channel_rotator_ok, &channel_rotator_outranks_me, &cited_ok, &signer, &my_xonly, next).await {
                    Advance::Adopt { new_key, .. } => {
                        if let Some(ch) = cur.channels.iter_mut().find(|c| c.id.0 == cid.0) {
                            ch.key = Some(new_key);
                            ch.epoch = next;
                        }
                        crate::log_debug!("[v2:follow {}] ch {} ADOPTED e{}", &cid_hex[..8], &ch_hex[..8], next.0);
                        // The adopter's own multi-epoch archive (the minter archived at
                        // mint) — this channel's history stays readable across rotations.
                        // fetch_channel compensates for the CURRENT epoch, so a failed
                        // archive only bites after the NEXT rotation — surface it.
                        if let Err(e) = crate::db::community::store_epoch_key(&cid_hex, &crate::simd::hex::bytes_to_hex_32(&cid.0), next.0, &new_key) {
                            crate::log_warn!("v2: channel epoch-key archive failed (history across this rotation may not read back): {e}");
                        }
                        advanced = true;
                        changed = true;
                    }
                    // A complete rotation without me: cut, or still keyless. Either way the
                    // channel stays known at that epoch, so the walk goes on to the CURRENT one,
                    // where a later rotation that names me again (a re-grant) lets me back in.
                    Advance::Removed { .. } => {
                        if held_key.is_some() {
                            crate::log_debug!("[v2:follow {}] ch {} cut at e{}", &cid_hex[..8], &ch_hex[..8], next.0);
                        }
                        if let Some(ch) = cur.channels.iter_mut().find(|c| c.id.0 == cid.0) {
                            ch.key = None;
                            ch.epoch = next;
                        }
                        advanced = true;
                        changed = true;
                    }
                    Advance::Stay => {}
                    Advance::StayWedged => {
                        // A blob at our locator that will not open: park, never
                        // remove, and make the park legible (a silent park is
                        // indistinguishable from "no rotation happened").
                        wedged = true;
                    }
                }
            }

            // Base rotation (Refounding): advances the root + root_epoch, re-addressing
            // every public channel, the guestbook, and the control plane by derivation
            // (refresh_subscription recomputes the author-set from the new root).
            {
                let held_epoch = cur.root_epoch;
                let held_key = cur.community_root;
                let next = Epoch(held_epoch.0.saturating_add(1));
                let batches = vec![(base, Some((held_epoch, held_key)))];
                match advance_scope(&batches, RekeyScope::Root, cur.id(), &base_rotator_ok, &base_rotator_outranks_me, &base_admissible, &signer, &my_xonly, next).await {
                    Advance::Adopt { new_key, control_pk, control_root, severed, rotator } => {
                        // CORD-02 §5: this npub's snapshot — and only this npub's —
                        // seeds the new epoch's Guestbook. Recorded from the rotation
                        // this device just VERIFIED and adopted, so a snapshot can
                        // never nominate its own author.
                        record_epoch_minter(&cid_hex, next.0, &rotator.to_hex());
                        // Record the HOP that was severed, not the walk's final head:
                        // the mark drives both the link condemnation line and the
                        // rescue re-stamp, and a multi-step walk would otherwise
                        // present the containment at the wrong epoch.
                        if severed {
                            severed_hops.push(next.0);
                            add_sever_mark(&cid_hex, next.0, now_ms() / 1000);
                        }
                        cur.community_root = new_key;
                        cur.root_epoch = next;
                        // The control pair is the blob's, never inherited: the
                        // secret rolls with the root at every Refounding
                        // (CORD-02 §2), so a stale pair carried forward would sign
                        // (or subscribe) at a dead address.
                        //
                        // A legacy 72-byte blob therefore DOWNGRADES a split
                        // community back to the member-writable plane — the exact
                        // flooding surface the split closes. The width stays
                        // accepted (transition compat, CORD-06 §3), but once a
                        // community has been split this is either an outdated
                        // rotator or an attack, so it is never silent.
                        if cur.control_pk.is_some() && control_pk.is_none() {
                            crate::log_warn!(
                                "[v2:follow {}] rotation to epoch {} carried a LEGACY base blob — this community's control plane reverts to the member-writable address",
                                &cid_hex[..8.min(cid_hex.len())], next.0
                            );
                        }
                        archive_control_address(&cid_hex, held_epoch.0, cur.control_pk.as_ref());
                        cur.control_pk = control_pk.and_then(|pk| PublicKey::from_slice(&pk).ok());
                        archive_control_address(&cid_hex, next.0, cur.control_pk.as_ref());
                        cur.control_root = control_root;
                        // Archive on adopt: without this, a member who lived through TWO
                        // Refoundings loses the middle epoch's public history (only the
                        // minter archived it).
                        if let Err(e) = crate::db::community::store_epoch_key(&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX, next.0, &new_key) {
                            crate::log_warn!("v2: base epoch-key archive failed (this epoch's history may not read back after the next rotation): {e}");
                        }
                        // CHECKPOINT THE HOP. A client back from a long absence walks
                        // many epochs in one pass, and the row used to be written only
                        // after the whole loop — so a fetch failure on the last hop
                        // discarded every hop already taken. The next attempt started
                        // from scratch, cost the same again, and on a flaky link could
                        // never converge at all. Banking here makes the walk resumable:
                        // progress is monotonic, and an interrupted catch-up picks up
                        // where it stopped.
                        //
                        // The FULL row, never just root+epoch: `control_pk`/
                        // `control_root` roll with the root, so a narrow write would
                        // leave the control pair an epoch behind and fold the control
                        // plane at a dead address. Archive first, then the head — a
                        // stray archive is harmless, a missing one is permanent.
                        //
                        // A leave/delete racing the walk must not be resurrected by an
                        // upsert, so re-check the row still exists before each write.
                        match crate::db::community::community_held(community.id()) {
                            Ok(true) => {
                                if let Err(e) = crate::db::community::save_community_v2(&cur) {
                                    crate::log_warn!("v2: hop checkpoint failed at epoch {} (the walk will redo it): {e}", next.0);
                                }
                            }
                            // Gone mid-walk: stop rather than resurrect it.
                            Ok(false) => return Ok(RekeyFollow { updated: None, self_removed: false, removed_at: None, dissolved: false, wedged }),
                            Err(e) => crate::log_warn!("v2: hop checkpoint skipped at epoch {}: {e}", next.0),
                        }
                        advanced = true;
                        changed = true;
                    }
                    Advance::Removed { at_ms } => {
                        return Ok(RekeyFollow { updated: None, self_removed: true, removed_at: Some(at_ms), dissolved: false, wedged: false });
                    }
                    Advance::Stay => {}
                    Advance::StayWedged => {
                        // A blob at our locator that will not open: park, never
                        // remove, and make the park legible (a silent park is
                        // indistinguishable from "no rotation happened").
                        wedged = true;
                    }
                }
            }

            if !advanced {
                break;
            }
        }

        if wedged {
            // Legible, and actionable: the prior root still reaches every member,
            // so an owner/admin seeing this can counter-rotate before the honest
            // chain moves on.
            crate::log_warn!(
                "[v2:follow {}] a complete rotation delivered a key blob this client cannot open — parked at epoch {} (never treated as a removal)",
                &cid_hex[..8.min(cid_hex.len())], cur.root_epoch.0
            );
            crate::emit_event(
                "community_rekey_wedged",
                &serde_json::json!({ "community_id": cid_hex, "held_epoch": cur.root_epoch.0 }),
            );
        }
        if !changed {
            // A pending severance whose revoke was interrupted must heal on QUIET
            // passes too — waiting for the next rotation means a one-shot transport
            // blip leaves the community reading Public (and every future ban
            // refound-less) until someone happens to rotate again.
            retry_pending_severance(transport, &cur).await;
            return Ok(RekeyFollow { updated: None, self_removed: false, removed_at: None, dissolved: false, wedged });
        }
        // A leave/delete raced this follow: saving would resurrect the community row
        // (the save is an upsert) with no floor rows behind it.
        if !crate::db::community::community_held(community.id())? {
            return Ok(RekeyFollow { updated: None, self_removed: false, removed_at: None, dissolved: false, wedged });
        }
        unseal_held(&mut cur);
        crate::db::community::save_community_v2(&cur)?;
        // Mark every containment hop FIRST: the marks are what condemn links, and
        // both the severance below and the refresh consult them — so the order of
        // those two stops mattering (a condemned link is skipped by the refresh
        // and buried by the severance, in either order, on any pass).
        for hop in &severed_hops {
            add_sever_mark(&cid_hex, *hop, now_ms() / 1000);
        }
        if !severed_hops.is_empty() {
            // Someone ELSE ran a Severing Refounding: my links minted below the
            // severed epoch are the raid's door — bury them instead of carrying
            // them forward. A fresh link minted at-or-after it survives every
            // device's adopt, however late (the epoch is the same on all of them).
            if let Err(e) = sever_own_links(transport, &cur).await {
                crate::log_warn!("[Sever] own-link revocation on adopt failed (retries next follow): {e}");
            }
        }
        // Carry my SURVIVING links across the rotation someone ELSE performed
        // (CORD-05 §2). The refounder refreshes only the bundles they can reach —
        // their own — so without this every other creator's links keep vending the
        // superseded root and drop new joiners onto a dead epoch, which is exactly
        // the stranding the stable-URL refresh exists to prevent. Condemned links
        // are skipped inside (see the guard there). Best-effort and idempotent.
        let _ = refresh_public_links(transport, &cur).await;
        // A pending sever mark (mine or adopted) whose revoke never completed
        // keeps retrying while condemned links remain (B4).
        retry_pending_severance(transport, &cur).await;
        Ok(RekeyFollow { updated: Some(cur), self_removed: false, removed_at: None, dissolved: false, wedged })
    })
    .await
}

/// One scope's catch-up decision from the rekey chunks fetched at its next-epoch
/// address.
enum Advance {
    /// Adopt this fresh key for `next_epoch`. A BASE adoption also carries the
    /// next epoch's Control Plane pair from the blob (CORD-06 §1) — the pk in
    /// every 104/136-byte blob, the secret only in a staff recipient's 136. The
    /// pair is the BLOB's, never inherited: a legacy 72-byte blob carries
    /// neither (that epoch's Control folds at the legacy address), and channel
    /// rotations never carry any.
    Adopt { new_key: [u8; 32], control_pk: Option<[u8; 32]>, control_root: Option<[u8; 32]>, severed: bool, rotator: PublicKey },
    /// A complete owner rotation at `next_epoch` dropped my blob — I'm removed, as of `at_ms`.
    Removed { at_ms: u64 },
    /// No owner rotation extends my held epoch (yet) — keep the current key.
    Stay,
    /// A complete authorized rotation carried a blob at MY locator that would
    /// not open. Never a removal (CORD-06 §2), but never silent either — the
    /// caller surfaces it (see [`RekeyFollow::wedged`]).
    StayWedged,
}

/// Fetch + parse every seal-verified 3303 chunk at a rekey plane address.
async fn fetch_rekey_chunks<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, group: &GroupKey) -> Result<Vec<rekey::RekeyChunk>, String> {
    // A rekey plane address is community_root-derived, so ANY member can seal junk 3303s
    // there: a flood, or a large community's own multi-chunk rotation, could bury the genuine
    // rotation past one page. The seal + authority filter downstream drops the junk.
    let wraps = plane_wraps(transport, community, group).await?;
    let _batch = stream::check_page(&wraps.iter().collect::<Vec<_>>(), group);
    Ok(wraps.iter().filter_map(|w| stream::open_wrap(w, group).ok()).filter_map(|opened| rekey::parse_rekey_chunk(&opened).ok()).collect())
}

/// Every wrap on a rekey or access plane: through the wraps held once the store is on, else
/// page by page off the relays.
async fn plane_wraps<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, group: &GroupKey) -> Result<Vec<Event>, String> {
    match control_store::mode() {
        control_store::Mode::Off => plane_wraps_paged(transport, &community.relays, group).await,
        control_store::Mode::On => match plane_wraps_held(transport, community, group).await {
            Some(wraps) => Ok(wraps),
            None => plane_wraps_paged(transport, &community.relays, group).await,
        },
        control_store::Mode::Shadow => {
            let paged = plane_wraps_paged(transport, &community.relays, group).await?;
            if let Some(held) = plane_wraps_held(transport, community, group).await {
                let held: std::collections::HashSet<nostr_sdk::prelude::EventId> = held.iter().map(|w| w.id).collect();
                // A wrap that opens as nothing is held as refused, and read as nothing either way.
                let pages: std::collections::HashSet<nostr_sdk::prelude::EventId> = paged.iter().filter(|w| stream::open_wrap(w, group).is_ok()).map(|w| w.id).collect();
                let (lost, more) = (pages.difference(&held).count(), held.difference(&pages).count());
                if lost > 0 || more > 0 {
                    #[cfg(test)]
                    if std::env::var("VECTOR_CONTROL_SHADOW_STRICT").is_ok() {
                        panic!("the plane read through the store differs from the paged one: {lost} wrap(s) lost, {more} more");
                    }
                    crate::log_warn!("[v2:plane {}] shadow: the read through the store differs: {lost} lost, {more} more", &community.id().to_hex()[..8]);
                }
            }
            Ok(paged)
        }
    }
}

/// [`plane_wraps`] through the wraps held, the relays asked first: what the relays hold now, as a
/// read by pages finds it, since a delivery only this device still holds is one nobody else can
/// fetch. `None` when the store cannot serve it (no relay answered, the plane is flooded, a store
/// error, a relay that could not say what it lacks): the caller reads by pages.
async fn plane_wraps_held<T: Transport + ?Sized>(transport: &T, community: &CommunityV2, group: &GroupKey) -> Option<Vec<Event>> {
    crate::db::scoped(async move {
        if !crate::db::community::community_held(community.id()).unwrap_or(false) {
            return None;
        }
        let view = plane_store::PlaneView::of(community, group);
        if control_sync::flooded(community, &view) {
            return None;
        }
        let began = web_time::Instant::now();
        let sync = control_sync::sync_plane(transport, community, &view, control_sync::Wait::Quorum).await.ok().filter(|sync| !sync.flooded && !sync.unread)?;
        let synced = began.elapsed();
        let unserved = control_sync::unserved_by_all(transport, &view, &sync).await?;
        crate::log_debug!("[v2:plane {}] {} read in {:?} ({:?} to sync)", &community.id().to_hex()[..8], &group.pk_hex()[..8], began.elapsed(), synced);
        Some(view.all().ok()?.into_iter().filter(|w| !unserved.contains(&w.id)).collect())
    })
    .await
}

/// [`plane_wraps`] off the relays, newest first, page by page to the end of the plane.
async fn plane_wraps_paged<T: Transport + ?Sized>(transport: &T, relays: &[String], group: &GroupKey) -> Result<Vec<Event>, String> {
    // Bounded: a sustained flood past this depth degrades to "adopt one pass late", never a
    // false state.
    const PAGE: usize = 200;
    const MAX_PAGES: usize = 6;
    let mut out = Vec::new();
    let mut seen: std::collections::HashSet<nostr_sdk::prelude::EventId> = std::collections::HashSet::new();
    let (mut until, mut oldest): (Option<u64>, Option<u64>) = (None, None);
    for _ in 0..MAX_PAGES {
        let query = plane_page(group.pk_hex(), PAGE, until);
        // Authenticate AS the plane key: on AUTH-gating relays (Ditto) the shared user-authed
        // client's REQ for a plane's events is CLOSED.
        let page = transport.fetch_plane(group.keys(), &query, relays).await?;
        // A page nobody fully answered must not read as "the plane ends here".
        let complete = page.is_complete();
        let wraps = page.events;
        let mut fresh = 0usize;
        for w in wraps.iter() {
            if !seen.insert(w.id) {
                continue;
            }
            fresh += 1;
            oldest = Some(oldest.map_or(w.created_at.as_secs(), |o| o.min(w.created_at.as_secs())));
            out.push(w.clone());
        }
        if fresh == 0 || (wraps.len() < PAGE && complete) {
            break;
        }
        match oldest {
            Some(o) if o > 0 => until = Some(o),
            _ => break,
        }
    }
    Ok(out)
}

/// One addressing root's chunks, with the key held at that scope as `(epoch, key)`.
type RekeyBatch = (Vec<rekey::RekeyChunk>, Option<(Epoch, [u8; 32])>);

/// Decide how a scope advances from per-addressing-root chunk batches (pure). Each
/// batch pairs the chunks fetched under one root with the continuity to demand of
/// them: a rotation qualifies when it's rotator-authorized (`rotator_ok`),
/// complete, targets the immediate `next_epoch`, and — when I hold a chain —
/// extends my exact `(epoch, key)`. A KEYLESS batch (`held` = None) has no chain
/// to extend, so it qualifies on authority + completeness alone (CORD-06 §2:
/// continuity is "a convergence check, not a secrecy mechanism"; the rotator's
/// seal authority is the boundary). Among qualifying rotations carrying my blob
/// the lexicographically lowest new key wins (convergent). All complete
/// candidates without my blob conclude Removed for a KEYED holder only when one
/// came from a rotator who may remove ME (`rotator_may_remove_me`, the CORD-06
/// strict-outrank rule) — else Stay; for a keyless holder they merely advance the
/// scan cursor (any bit-holder's real rotation is scan progress, never a loss).
#[allow(clippy::too_many_arguments)]
async fn advance_scope<S: crate::signer::VectorSigner + ?Sized>(
    batches: &[RekeyBatch],
    scope: RekeyScope,
    community_id: &crate::community::CommunityId,
    rotator_ok: &(dyn Fn(&PublicKey) -> bool + Sync),
    rotator_may_remove_me: &(dyn Fn(&PublicKey) -> bool + Sync),
    admissible: &(dyn Fn(&rekey::Rotation) -> bool + Sync),
    signer: &S,
    my_xonly: &[u8; 32],
    next_epoch: Epoch,
) -> Advance {
    let mut winners: Vec<rekey::BaseKeyDelivery> = Vec::new();
    // Parallel to `winners`: whether each delivery's rotation is a containment
    // (Root scope only). Selected by the same lowest-key index, so a same-epoch
    // fork adopts the winner's flag and never a loser's.
    let mut winner_severed: Vec<bool> = Vec::new();
    // Parallel to `winner_severed`: whose Refounding this delivery came from. The
    // snapshot authority for the adopted epoch (CORD-02 §5) is exactly this npub.
    let mut winner_rotator: Vec<PublicKey> = Vec::new();
    let mut saw_complete_candidate = false;
    // The latest complete rotation considered: a removal dates from it.
    let mut removed_at: u64 = 0;
    // Did any qualifying rotation actually carry recipients? See the removal gate.
    let mut saw_nonempty_candidate = false;
    let mut saw_outranking_candidate = false;
    let mut my_blob_unopenable = false;
    let keyed = batches.iter().any(|(_, held)| held.is_some());
    for (chunks, held) in batches {
        let rotations = rekey::collect_rotations(chunks);
        for r in &rotations {
            if !rotator_ok(&r.rotator) || r.scope.id32() != scope.id32() || r.new_epoch.0 != next_epoch.0 {
                continue;
            }
            if let Some((held_epoch, held_key)) = held {
                if r.continuity(*held_epoch, held_key) != Continuity::Extends {
                    continue;
                }
            }
            // CORD-06 §Authority: a rotator must strictly OUTRANK every removed
            // target. An authorized-but-inadmissible rotation (one that excludes
            // the owner or a peer/superior the rotator can't act on) is a takeover
            // attempt — skip it entirely, so it neither adopts nor concludes a
            // removal (it forks; the honest chain wins).
            if !admissible(r) {
                continue;
            }
            // Completeness gates the DESTRUCTIVE direction only. Concluding removal
            // means "no blob for me anywhere in this rotation", which is only
            // knowable with every chunk in hand — so `saw_complete_candidate`, and
            // everything downstream of it, still demands the whole set.
            //
            // ADOPTION does not need it. The blob binds its own (scope, epoch)
            // inside the ciphertext, so a key that opens is this rotation's key
            // whatever else is unreachable; and admissibility is monotonic in the
            // blob set — chunks we have not seen can only ADD recipients, so a
            // rotation that looks admissible on the blobs we hold cannot become a
            // takeover once the rest arrive. Requiring the full set to adopt made a
            // large community's rotation as fragile as its least reachable chunk,
            // and the walk is sequential, so that strand blocked every epoch above
            // it too. (A rotation that fails admissibility on partial data is still
            // skipped, never adopted — the unsafe direction stays closed.)
            if r.is_complete() {
                removed_at = removed_at.max(r.at_ms);
                saw_complete_candidate = true;
                saw_nonempty_candidate |= !r.blobs.is_empty();
                saw_outranking_candidate |= rotator_may_remove_me(&r.rotator);
            }
            // EVERY blob at my locator, not just the first. A locator is a public
            // index that proves nothing, so anyone may publish a blob at mine;
            // taking only the first would let a junk one shadow the real key and
            // park a client that actually holds it. First that opens wins.
            let mut mine = rekey::find_my_blobs(&r.blobs, &r.rotator.to_bytes(), my_xonly, r.scope, r.new_epoch).peekable();
            let had_candidate = mine.peek().is_some();
            let mut opened_one = false;
            for blob in mine {
                let opened = match scope {
                    // Base blobs are width-declared forms (CORD-06 §1).
                    RekeyScope::Root => rekey::open_base_blob(signer, &r.rotator, community_id, r.new_epoch, blob).await,
                    RekeyScope::Channel(_) => rekey::open_blob(signer, &r.rotator, r.scope, r.new_epoch, blob)
                        .await
                        .map(|k| rekey::BaseKeyDelivery { new_root: k, control_pk: None, control_root: None }),
                };
                if let Ok(d) = opened {
                    winners.push(d);
                    winner_severed.push(scope.id32() == RekeyScope::Root.id32() && r.severed);
                    winner_rotator.push(r.rotator);
                    opened_one = true;
                    break;
                }
            }
            // A blob AT my locator that won't open is not an exclusion (CORD-06 §2:
            // removal = NO blob across all chunks). It must never conclude Removed
            // below — that is exactly how a pre-split client turned an unreadable
            // width into a false self-removal. Stay and keep recovering instead.
            if had_candidate && !opened_one {
                my_blob_unopenable = true;
            }
        }
    }
    if !winners.is_empty() {
        // `collect_rotations` correlates on `(rotator, scope, new_epoch, prev_commit)`,
        // so a single rotator's blobs merge into ONE rotation (and a retried Refounding
        // MINT-OR-REUSES its root, so it never emits two distinct roots to fork on).
        // The lowest-key tiebreak engages only for CONCURRENT DISTINCT rotators racing
        // the same epoch (separate rotations): every follower converges on the same
        // lowest new BASE key — the control pair rides the winner's blobs, never
        // compared (CORD-06 §3). A wrap served under two addressing roots can't
        // double-count: each rekey wrap opens under exactly one root's group key.
        let keys: Vec<[u8; 32]> = winners.iter().map(|d| d.new_root).collect();
        let idx = rekey::lowest_key_winner(&keys).expect("winners is non-empty");
        let w = &winners[idx];
        return Advance::Adopt {
            new_key: w.new_root,
            control_pk: w.control_pk,
            control_root: w.control_root,
            severed: winner_severed[idx],
            rotator: winner_rotator[idx],
        };
    }
    // A rotation that delivered NO blob to anyone removed nobody. Read literally it
    // is "complete, authorized, and contains no blob for me" — which is the removal
    // shape — but removal DELETES the community locally, so one empty rotation from
    // an authorized rotator would evict the entire membership at once, irreversibly.
    // An empty recipient set is a malformed or aborted rotation, never a verdict
    // about any individual. Nobody is removed by a rotation that removed everybody.
    if saw_complete_candidate && !saw_nonempty_candidate {
        return Advance::Stay;
    }
    if saw_complete_candidate && !my_blob_unopenable && (!keyed || saw_outranking_candidate) {
        Advance::Removed { at_ms: removed_at.min(now_ms()) }
    } else if my_blob_unopenable {
        Advance::StayWedged
    } else {
        Advance::Stay
    }
}

// ── Pins (CORD-04 §7) ────────────────────────────────────────────────────────

/// A channel's pin list, read from the locally folded head.
#[derive(Debug, serde::Serialize)]
pub struct ChannelPins {
    /// Entries that passed the full §7 verification, wire order (curator's).
    pub pins: Vec<super::pins::VerifiedPin>,
    /// The head is sealed under a key epoch this client does not hold: the
    /// pins exist but are unreadable. Render as unavailable, NEVER as empty —
    /// and a writer seeing this MUST NOT publish (it would drop every entry).
    pub sealed: bool,
    /// Folded head version (0 = no edition has ever folded).
    pub version: u64,
}

/// The channel's stream conversation key at `epoch`, if this client holds the
/// deriving secret: a private channel's held per-epoch key, a public channel's
/// held base root at that epoch.
fn channel_conv_key_at(community: &CommunityV2, ch: &ChannelV2, epoch: u64) -> Option<[u8; 32]> {
    let ikm = channel_conv_ikm(community, ch, epoch).ok()?;
    // A private plane is never derived from the root value (that would address
    // the public plane) — mirrors fetch_channel_history's invariant.
    if ch.private && ikm == community.community_root {
        return None;
    }
    let group = channel_group_key(&ikm, &ch.id, Epoch(epoch));
    group.conv_key().as_bytes().try_into().ok()
}

/// Read a channel's pins from the locally folded head: unseal (private form),
/// verify every entry, keep wire order. Local-only — the control follow is what
/// moves the head.
pub fn read_channel_pins(community: &CommunityV2, channel_id: &ChannelId) -> Result<ChannelPins, String> {
    let ch = community.channel(channel_id).ok_or("no such channel in this community")?;
    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
    let ch_hex = crate::simd::hex::bytes_to_hex_32(&channel_id.0);
    let Some((content, version)) = crate::db::community::get_community_pins(&cid_hex, &ch_hex)? else {
        return Ok(ChannelPins { pins: Vec::new(), sealed: false, version: 0 });
    };
    let read = super::pins::read_pin_list(&content, |epoch| channel_conv_key_at(community, ch, epoch));
    let pins = read
        .entries
        .iter()
        .filter_map(|e| super::pins::verify_pin_entry(e, &ch_hex))
        .collect();
    Ok(ChannelPins { pins, sealed: read.sealed, version: version.max(0) as u64 })
}

/// Publish `entries` as the channel's next Pin List edition, in the form the
/// channel's folded type mandates, and echo it locally so a follow-up edit
/// builds on this write rather than the pre-write fold.
async fn publish_pin_list<T: Transport + ?Sized>(
    transport: &T,
    community: &CommunityV2,
    ch: &ChannelV2,
    entries: &[super::pins::PinEntry],
) -> Result<(), String> {
    crate::db::scoped(async move {
        let content = if ch.private {
            let key = ch.key.ok_or("this private channel's key has not arrived yet")?;
            let group = channel_group_key(&key, &ch.id, ch.epoch);
            super::pins::serialize_sealed_pin_list(entries, group.conv_key(), ch.epoch.0)?
        } else {
            super::pins::serialize_public_pin_list(entries)?
        };
        let eid = super::derive::pins_locator(community.id(), &ch.id);
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let ch_hex = crate::simd::hex::bytes_to_hex_32(&ch.id.0);
        let entity_hex = crate::simd::hex::bytes_to_hex_32(&eid);
        // The version this publish will chain to — mirrors publish_control_edition.
        let version = match crate::db::community::get_edition_head(&cid_hex, &entity_hex)? {
            Some((v, _)) => v + 1,
            None => 1,
        };
        crate::log_info!("[pins] publishing v{} with {} entries for channel {}", version, entries.len(), &ch_hex[..12]);
        publish_control_edition(transport, community, vsk::PINS, &eid, &content).await?;
        let _ = crate::db::community::set_community_pins(&cid_hex, &ch_hex, &content, version as i64);
        crate::emit_event(
            "community_pins_updated",
            &serde_json::json!({ "community_id": cid_hex, "channel_id": ch_hex }),
        );
        if let Ok(me) = me_pk() {
            use nostr_sdk::prelude::ToBech32;
            let me_npub = me.to_bech32().unwrap_or_else(|_| me.to_hex());
            note_pins_modified(&ch_hex, version, &me_npub, now_ms() / 1000).await;
        }
        Ok(())
    })
    .await
}

/// One centered system row per adopted Pin List edition — "X modified the
/// Pins". The id is deterministic on (channel, version), so the publisher's
/// echo and every fold that adopts the same edition collapse into one row,
/// and a catch-up fold stamps the edition's own time so history sorts true.
async fn note_pins_modified(channel_hex: &str, version: u64, actor_npub: &str, at_secs: u64) {
    let event_id = format!("pins-mod-{}-v{}", &channel_hex[..16], version);
    let inserted = crate::db::events::save_system_event_at(
        &event_id,
        channel_hex,
        crate::stored_event::SystemEventType::PinsModified,
        actor_npub,
        None,
        at_secs,
        None,
        None,
    )
    .await
    .unwrap_or(false);
    if inserted {
        crate::emit_event(
            "system_event",
            &serde_json::json!({
                "conversation_id": channel_hex,
                "event_id": event_id,
                "event_type": crate::stored_event::SystemEventType::PinsModified.as_u8(),
                "member_pubkey": actor_npub,
            }),
        );
    }
}

/// The current entries this writer may build on. Replace-entire cuts sharply
/// (§7): an empty view has two innocent causes indistinguishable from an empty
/// list, so a writer MUST refuse to build from a list it could not read.
fn writable_pin_entries(community: &CommunityV2, channel_id: &ChannelId) -> Result<Vec<super::pins::PinEntry>, String> {
    let current = read_channel_pins(community, channel_id)?;
    if current.sealed {
        return Err("this channel's pins are sealed under a key you don't hold; pinning would erase them".to_string());
    }
    Ok(current.pins.into_iter().map(|p| p.entry).collect())
}

/// Pin a message: recover its wrap, rebuild its proof, append, republish.
///
/// The seal is re-fetched from the community relays by the stored wrapper id —
/// the DB retains rumors, not seals, and a proof needs the seal verbatim.
pub async fn pin_message<T: Transport + ?Sized>(
    transport: &T,
    community: &CommunityV2,
    channel_id: &ChannelId,
    rumor_id_hex: &str,
) -> Result<(), String> {
    crate::db::scoped(async move {
        let ch = community.channel(channel_id).ok_or("no such channel in this community")?.clone();
        let ch_hex = crate::simd::hex::bytes_to_hex_32(&channel_id.0);

        let mut entries = writable_pin_entries(community, channel_id)?;
        if entries.len() >= super::pins::PIN_MAX_ENTRIES {
            return Err(format!("this channel already holds {} pins; unpin one first", super::pins::PIN_MAX_ENTRIES));
        }
        // Idempotent: re-pinning an already-pinned message is a no-op, not an error.
        if entries
            .iter()
            .filter_map(|e| super::pins::verify_pin_entry(e, &ch_hex))
            .any(|v| v.rumor_id == rumor_id_hex)
        {
            return Ok(());
        }

        let (wrap_id, _tags) = crate::db::events::get_event_wrap_context(rumor_id_hex)?
            .ok_or("message not found in this device's history")?;
        let wrap_id = wrap_id.ok_or("this message's original wrap id was not recorded")?;

        // Recover the wrap verbatim — Full evidence: a pin is a permanent artifact,
        // so don't build it from the first relay to answer.
        let wraps = transport
            .fetch(
                &Query {
                    ids: vec![wrap_id.clone()],
                    kinds: vec![super::stream::KIND_WRAP],
                    limit: Some(1),
                    evidence: crate::community::transport::Evidence::Full,
                    ..Default::default()
                },
                &community.relays,
            )
            .await?;
        let wrap = wraps
            .iter()
            .find(|w| w.id.to_hex() == wrap_id)
            .ok_or("the message's wrap is no longer served by this community's relays")?;

        // The stored row does not retain the rumor's epoch binding, so re-derive it
        // the way history reads do: try the channel's every held plane coordinate,
        // current epoch first, until the wrap opens AND carries this rumor. The
        // open itself verifies the channel + epoch binding, so a false coordinate
        // fails closed rather than mis-attributing.
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let mut coords: Vec<(u64, [u8; 32])> = Vec::new();
        if ch.private {
            if let Some(k) = ch.key {
                coords.push((ch.epoch.0, k));
            }
            let held = crate::db::community::held_epoch_keys(&cid_hex, &ch_hex).unwrap_or_default();
            coords.extend(held.into_iter().filter(|(_, k)| *k != community.community_root).map(|(ep, k)| (ep.0, k)));
        } else {
            coords.push((community.root_epoch.0, community.community_root));
            let held = crate::db::community::held_epoch_keys(&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX).unwrap_or_default();
            coords.extend(held.into_iter().map(|(ep, k)| (ep.0, k)));
        }
        coords.dedup();

        // A restricted Channel's posts sit at their writer epoch's address, under a read epoch's key.
        let writer = ch.writers.as_ref().and_then(|l| l.writers().find(|(_, pk, _)| *pk == wrap.pubkey.to_bytes()).map(|(e, ..)| e));
        let mut found: Option<(super::stream::OpenedStream, [u8; 32])> = None;
        for (epoch, ikm) in coords {
            let group = channel_group_key(&ikm, &ch.id, Epoch(epoch));
            let event = match writer {
                Some(wepoch) => super::chat::open_writer_chat_event(wrap, &wrap.pubkey, wepoch, group.conv_key(), channel_id, Epoch(epoch)),
                None => super::chat::open_chat_event(wrap, &group, channel_id, Epoch(epoch)),
            };
            if let Ok(super::chat::ChatEvent::Message { opened, .. }) = event {
                if opened.rumor_id.to_hex() == rumor_id_hex {
                    let conv: [u8; 32] = group
                        .conv_key()
                        .as_bytes()
                        .try_into()
                        .map_err(|_| "conversation key size".to_string())?;
                    found = Some((opened, conv));
                    break;
                }
            }
        }
        let Some((opened, conv_key)) = found else {
            return Err("that message is from a key epoch this device no longer holds".to_string());
        };

        let entry = super::pins::build_pin_entry(&opened, &conv_key, &ch_hex).map_err(|e| match e {
            super::pins::PinBuildFailure::NotEncrypted => "this message's seal form cannot be pinned".to_string(),
            super::pins::PinBuildFailure::BadPayload => "that message is from a key epoch this device no longer holds".to_string(),
            super::pins::PinBuildFailure::Unverifiable => "this message's proof did not verify".to_string(),
        })?;
        entries.push(entry);

        publish_pin_list(transport, community, &ch, &entries).await
    })
    .await
}

/// The deriving secret (ikm) for a channel plane at `epoch` — the same lookup
/// `channel_conv_key_at` performs, surfaced for the open path.
fn channel_conv_ikm(community: &CommunityV2, ch: &ChannelV2, epoch: u64) -> Result<[u8; 32], String> {
    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
    if ch.private {
        if ch.epoch.0 == epoch {
            return ch.key.ok_or("this private channel's key has not arrived yet".to_string());
        }
        let ch_hex = crate::simd::hex::bytes_to_hex_32(&ch.id.0);
        crate::db::community::held_epoch_keys(&cid_hex, &ch_hex)
            .unwrap_or_default()
            .into_iter()
            .find(|(ep, _)| ep.0 == epoch)
            .map(|(_, k)| k)
            .ok_or("that message is from a key epoch this device no longer holds".to_string())
    } else if community.root_epoch.0 == epoch {
        Ok(community.community_root)
    } else {
        crate::db::community::held_epoch_keys(&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX)
            .unwrap_or_default()
            .into_iter()
            .find(|(ep, _)| ep.0 == epoch)
            .map(|(_, k)| k)
            .ok_or("that message is from a root epoch this device no longer holds".to_string())
    }
}

/// Unpin a message: the next edition without the entry (§7 — no deletion event).
pub async fn unpin_message<T: Transport + ?Sized>(
    transport: &T,
    community: &CommunityV2,
    channel_id: &ChannelId,
    rumor_id_hex: &str,
) -> Result<(), String> {
    let ch = community.channel(channel_id).ok_or("no such channel in this community")?.clone();
    let ch_hex = crate::simd::hex::bytes_to_hex_32(&channel_id.0);
    let entries = writable_pin_entries(community, channel_id)?;
    let kept: Vec<super::pins::PinEntry> = entries
        .into_iter()
        .filter(|e| {
            super::pins::verify_pin_entry(e, &ch_hex)
                .map(|v| v.rumor_id != rumor_id_hex)
                // An entry we can't verify is kept: unpin removes exactly the
                // named message, never collateral.
                .unwrap_or(true)
        })
        .collect();
    publish_pin_list(transport, community, &ch, &kept).await
}

/// §7 curator duties: converge the Pin List when a pinned message is deleted
/// or edited. Spawned fire-and-forget from ingest — a non-curator, a sealed
/// list, or an unpinned target all no-op silently; the duty is voluntary.
pub(crate) fn spawn_pin_duty(channel_hex: &str, target_rumor_hex: &str, edit: Option<super::stream::OpenedStream>) {
    let channel_hex = channel_hex.to_string();
    let target = target_rumor_hex.to_string();
    crate::db::spawn_bound(async move {
        let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
        let _ = run_pin_duty(&transport, &channel_hex, &target, edit).await;
    });
}

/// The duty body, transport-injected so tests can drive it end to end.
///
/// The affected author acts at once; every other PIN_MESSAGES holder waits a
/// deterministic 5-25s stagger (hashed from (me, target) — no thundering herd
/// of racing editions) and re-reads before publishing, so a duty another
/// curator already performed dissolves into a no-op.
async fn run_pin_duty<T: Transport + ?Sized>(
    transport: &T,
    channel_hex: &str,
    target: &str,
    edit: Option<super::stream::OpenedStream>,
) -> Result<(), String> {
    use crate::community::roles::Permissions;
    let Some(cid_hex) = crate::db::community::community_id_for_channel(channel_hex)? else {
        return Ok(());
    };
    let cid = crate::community::CommunityId(crate::simd::hex::hex_to_bytes_32(&cid_hex));
    let Some(community) = crate::db::community::load_community_v2(&cid)? else {
        return Ok(());
    };
    let channel_id = ChannelId(crate::simd::hex::hex_to_bytes_32(channel_hex));

    // Cheap pre-checks before any waiting: pinned target, readable list, held bit.
    let read = read_channel_pins(&community, &channel_id)?;
    if read.sealed {
        return Ok(());
    }
    let Some(hit) = read.pins.iter().find(|p| p.rumor_id == target) else {
        return Ok(());
    };
    if let Some(ed) = &edit {
        // Monotonic: a bundle at or past this revision needs no refresh.
        if hit.edited.as_ref().is_some_and(|held| held.ms >= ed.at_ms) {
            return Ok(());
        }
    }
    let me = me_pk()?;
    let me_hex = me.to_hex();
    let owner_hex = community.owner()?.to_hex();
    let roster = crate::db::community::get_community_roles(&cid_hex)?;
    if !roster.is_authorized(&me_hex, Some(&owner_hex), Permissions::PIN_MESSAGES) {
        return Ok(());
    }

    if hit.author != me_hex {
        let mut h: u32 = 0;
        for b in me_hex.bytes().chain(target.bytes()) {
            h = h.wrapping_mul(31).wrapping_add(u32::from(b));
        }
        crate::rt::time::sleep(std::time::Duration::from_secs(5 + u64::from(h % 21))).await;
    }

    // Re-read after the stagger: another curator's edition may have landed.
    let read = read_channel_pins(&community, &channel_id)?;
    if read.sealed {
        return Ok(());
    }
    let Some(hit) = read.pins.iter().find(|p| p.rumor_id == target) else {
        return Ok(());
    };
    let ch = community.channel(&channel_id).ok_or("no such channel")?.clone();

    let entries: Vec<super::pins::PinEntry> = match &edit {
        // Deletion: the next edition simply omits the entry (§7 — replace-entire).
        None => read
            .pins
            .iter()
            .filter(|p| p.rumor_id != target)
            .map(|p| p.entry.clone())
            .collect(),
        // Edit: the same entry, its bundle refreshed to the newest revision.
        Some(ed) => {
            if hit.edited.as_ref().is_some_and(|held| held.ms >= ed.at_ms) {
                return Ok(());
            }
            let ch_hex = crate::simd::hex::bytes_to_hex_32(&channel_id.0);
            // The edit sealed under the channel's current plane in the common
            // (realtime) case; older epochs are tried like every other read.
            let mut bundle = None;
            let mut epochs: Vec<u64> = vec![if ch.private { ch.epoch.0 } else { community.root_epoch.0 }];
            let scope = if ch.private { ch_hex.clone() } else { crate::community::SERVER_ROOT_SCOPE_HEX.to_string() };
            epochs.extend(
                crate::db::community::held_epoch_keys(&cid_hex, &scope)
                    .unwrap_or_default()
                    .into_iter()
                    .map(|(ep, _)| ep.0),
            );
            epochs.dedup();
            for epoch in epochs {
                let Some(conv) = channel_conv_key_at(&community, &ch, epoch) else { continue };
                if let Ok(b) = super::pins::build_pin_edit_bundle(ed, &conv, &hit.author, target, &ch_hex) {
                    bundle = Some(b);
                    break;
                }
            }
            let Some(bundle) = bundle else { return Ok(()) };
            read.pins
                .iter()
                .map(|p| {
                    let mut entry = p.entry.clone();
                    if p.rumor_id == target {
                        entry.edit = Some(bundle.clone());
                    }
                    entry
                })
                .collect()
        }
    };

    crate::log_info!(
        "[pins] duty {} for target {} in channel {}",
        if edit.is_some() { "edit-refresh" } else { "omission" },
        &target[..12],
        &channel_hex[..12]
    );
    publish_pin_list(transport, &community, &ch, &entries).await
}

/// Communities this session has already offered [`upgrade_admin_role_pin_bit`].
/// Per session: whether the account folding is the owner decides what it does.
struct AdminPinUpgraded;

/// `true` the first time this session asks for `community`.
fn first_admin_pin_upgrade(community: &crate::community::CommunityId) -> bool {
    let set = crate::db::current_session()
        .scoped::<AdminPinUpgraded, std::sync::Mutex<std::collections::HashSet<[u8; 32]>>>();
    let first = set.lock().unwrap_or_else(|e| e.into_inner()).insert(community.0);
    first
}

/// Silent owner-side widening: an Admin role published before PIN_MESSAGES
/// existed gains the bit, so delegated admins can curate pins in communities
/// founded before this build. One edition, idempotent, converges across owner
/// devices (both publish the same widened mask as editions of one entity).
pub async fn upgrade_admin_role_pin_bit<T: Transport + ?Sized>(
    transport: &T,
    community: &CommunityV2,
) -> Result<bool, String> {
    use crate::community::roles::{Permissions, RoleScope};
    let my_pk = me_pk()?;
    if community.owner()? != my_pk {
        return Ok(false);
    }
    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
    let roles = crate::db::community::get_community_roles(&cid_hex)?;
    let Some(role) = roles.roles.iter().find(|r| {
        matches!(r.scope, RoleScope::Server)
            && r.permissions.contains(Permissions::ADMIN_FOUNDING_MASK)
            && !r.permissions.contains(Permissions::PIN_MESSAGES)
    }) else {
        return Ok(false);
    };
    let mut widened = role.clone();
    widened.permissions.0 |= Permissions::PIN_MESSAGES;
    set_role(transport, community, &widened).await?;
    Ok(true)
}

/// Timings of one control follow's stages over what `transport` serves, for `cargo bench`:
/// (the read with its folds, one `fold_authority`, one `apply_control_fold`, editions read).
#[cfg(feature = "bench")]
pub(crate) async fn bench_control_stages<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> (std::time::Duration, std::time::Duration, std::time::Duration, usize) {
    use crate::rt::time_std::Instant;
    let t = Instant::now();
    let read = read_control(transport, community).await.unwrap();
    let read_at = t.elapsed();
    let t = Instant::now();
    let authority = fold_authority(community, &read.editions, &read.floors);
    let authority_at = t.elapsed();
    let t = Instant::now();
    std::hint::black_box(apply_control_fold(community, &read.editions, &read.floors, &authority));
    (read_at, authority_at, t.elapsed(), read.editions.len())
}

/// Forget every Control wrap held for `community`, as on a device that has read none, for `cargo bench`.
#[cfg(feature = "bench")]
pub(crate) fn bench_forget_control_wraps(community: &CommunityV2) {
    let view = control_store::View::of(community);
    for (id, _) in view.held().unwrap_or_default() {
        view.forget(&id);
    }
    let _ = crate::db::remove_setting(&format!("ctl_reads:{}", community.id().to_hex()));
}

/// Whether follows read through the wraps held, for `cargo bench`.
#[cfg(feature = "bench")]
pub(crate) fn bench_control_store_on() -> bool {
    control_store::mode() == control_store::Mode::On
}

/// An admin's whole read of the Control Plane, for `cargo bench`: the editions it held.
#[cfg(feature = "bench")]
pub(crate) async fn bench_control_whole<T: Transport + ?Sized>(transport: &T, community: &CommunityV2) -> usize {
    fetch_control_plane_whole(transport, community).await.map_or(0, |editions| editions.len())
}

/// One `ledger_chain_ok` over a Writers ledger `n` versions long, every edition authorized, read
/// newest first or oldest first, for `cargo bench`.
#[cfg(feature = "bench")]
pub(crate) fn bench_ledger_chain(n: usize, newest_first: bool) -> std::time::Duration {
    use super::writers::{Ledger, Spell};
    let ch = ChannelId([7; 32]);
    let author = Keys::generate().public_key();
    let base = now_ms() - (n as u64 + 10) * 1000;
    let mut ledger = Ledger::new(&ch);
    let mut editions = Vec::with_capacity(n);
    let mut prev = None;
    for i in 0..n as u64 {
        let at = base + i * 1000;
        let spell = Spell::Writer { epoch: Epoch(i + 1), pk: Keys::generate().public_key().to_bytes(), root: Epoch(0), by: author.to_bytes(), certifier: None };
        ledger = ledger.appended(at, spell).expect("a ledger that grows");
        let self_hash = crate::crypto::sha256::digest(&i.to_le_bytes());
        editions.push(ParsedEdition {
            author,
            vsk: String::new(),
            entity_id: [0; 32],
            version: i + 1,
            prev_hash: prev,
            content: ledger.to_json(),
            self_hash,
            created_at: at / 1000,
            inner_id: self_hash,
            authority: None,
            binding: None,
        });
        prev = Some(self_hash);
    }
    if newest_first {
        editions.reverse();
    }
    let group: Vec<&ParsedEdition> = editions.iter().collect();
    let authorized = vec![true; n];
    let ch_hex = crate::simd::hex::bytes_to_hex_32(&ch.0);
    let t = crate::rt::time_std::Instant::now();
    let ok = ledger_chain_ok(&group, &authorized, &ch_hex, &|e| (0, e.inner_id), None);
    let took = t.elapsed();
    assert!(ok.len() == n && ok.values().all(|v| *v), "every edition of a well-formed chain stands");
    took
}

#[cfg(test)]
mod tests {
    std::thread_local! {
        /// The Roster fixpoint's round bound, when a test sets one on its thread.
        pub(super) static FOLD_BOUND: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
        /// [`replay`] on fresh scratch for every call, as it ran before reusing it.
        pub(super) static FRESH_SCRATCH: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
    }

    // The legacy (pre-split) Control derivation, still reachable for the
    // migration-compat paths under test.
    use super::super::derive::control_group_key;
    use crate::ClientRelayExt;
    use super::super::super::transport::memory::MemoryRelay;
    use super::*;

    mod control_sync;
    mod paged_walks;
    mod relay_reads;
    use crate::community::roles::{MemberGrant, Permissions, Role, RoleScope};

    /// A distinct npub-shaped account-dir name (bech32 charset) per counter.
    fn account_name(n: u32) -> String {
        const B: &[u8] = b"qpzry9x8gf2tvdw0s3jn54khce6mua7l";
        let mut acct = String::from("npub1");
        let mut v = n as usize;
        for _ in 0..58 {
            acct.push(B[v % 32] as char);
            v = v / 32 + 7;
        }
        acct
    }

    /// One test participant: its identity keys and its isolated account DB dir.
    struct Actor {
        keys: Keys,
        account: String,
    }

    /// Two participants sharing one relay but isolated per-account DBs — the
    /// cross-account harness a real invite/join loop needs. `swap_to` mirrors a
    /// live `swap_session`: re-point the DB pool + rebind the identity + clear
    /// the per-account id caches, so account A's community is invisible to B
    /// until B legitimately joins.
    struct TestBed {
        _tmp: tempfile::TempDir,
        _guard: std::sync::MutexGuard<'static, ()>,
        relay: MemoryRelay,
        relays: Vec<String>,
    }

    impl TestBed {
        fn new() -> (TestBed, Actor, Actor) {
            static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(70_000);
            let guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
            crate::db::close_database();
            crate::db::clear_id_caches();
            let tmp = tempfile::tempdir().unwrap();
            crate::db::set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());

            let mk = || {
                let n = N.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                let account = account_name(n);
                std::fs::create_dir_all(tmp.path().join(&account)).unwrap();
                crate::db::set_current_account(account.clone()).unwrap();
                crate::db::init_database(&account).unwrap();
                Actor { keys: Keys::generate(), account }
            };
            let owner = mk();
            let member = mk();
            let _ = crate::state::take_nostr_client();
            let bed = TestBed {
                _tmp: tmp,
                _guard: guard,
                relay: MemoryRelay::new(),
                relays: vec!["wss://r".to_string()],
            };
            (bed, owner, member)
        }

        /// Become `actor`: swap the account DB + identity, as a real session swap.
        /// Bumps the session generation like production `swap_session` does — so any task a
        /// prior actor spawned (e.g. the migration finalize) dies at its std::sync::Arc<crate::db::Session> check
        /// instead of racing this actor's DB (a cross-test flake that can't happen in prod).
        fn swap_to(&self, actor: &Actor) {
            crate::db::close_database();
            crate::db::set_current_account(actor.account.clone()).unwrap();
            crate::db::init_database(&actor.account).unwrap();
            crate::db::clear_id_caches();
            crate::state::MY_SECRET_KEY.store_from_keys(&actor.keys, &[]);
            crate::state::set_my_public_key(actor.keys.public_key());
        }
    }

    /// Legacy single-actor helper (the create/send tests below).
    pub(super) fn init_test_db() -> (tempfile::TempDir, std::sync::MutexGuard<'static, ()>, Keys) {
        let guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
        crate::db::close_database();
        crate::db::clear_id_caches();
        let tmp = tempfile::tempdir().unwrap();
        static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(50_000);
        let n = N.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        let acct = account_name(n);
        std::fs::create_dir_all(tmp.path().join(&acct)).unwrap();
        crate::db::set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());
        crate::db::set_current_account(acct.clone()).unwrap();
        crate::db::init_database(&acct).unwrap();
        let _ = crate::state::take_nostr_client();
        let owner = Keys::generate();
        crate::state::MY_SECRET_KEY.store_from_keys(&owner, &[]);
        crate::state::set_my_public_key(owner.public_key());
        (tmp, guard, owner)
    }

    /// A transport that simulates a session swap landing DURING a fetch await —
    /// so a join straddling the fetch sees an invalid session and aborts.
    /// Switches to a real second account on the first fetch, then stays out of
    /// the way. It BORROWS the relay that built the community — a fresh one
    /// would fail verification for want of a control plane, which is not the
    /// thing being tested.
    struct SwapMidFetch<'a> {
        inner: &'a MemoryRelay,
        to: String,
        armed: std::sync::atomic::AtomicBool,
    }

    impl<'a> SwapMidFetch<'a> {
        fn arm(inner: &'a MemoryRelay) -> Self {
            static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(88_000);
            let to = account_name(N.fetch_add(1, std::sync::atomic::Ordering::Relaxed));
            std::fs::create_dir_all(crate::db::shared_test_data_dir().join(&to)).unwrap();
            Self { inner, to, armed: std::sync::atomic::AtomicBool::new(true) }
        }
    }

    #[async_trait::async_trait]
    impl Transport for SwapMidFetch<'_> {
        async fn fetch_plane(&self, _plane: &Keys, query: &Query, relays: &[String]) -> Result<crate::community::transport::PlaneFetch, String> { Ok(crate::community::transport::PlaneFetch::whole(self.fetch(query, relays).await?)) }
        async fn publish(&self, e: &Event, r: &[String]) -> Result<(), String> {
            self.inner.publish(e, r).await
        }
        async fn publish_durable(&self, e: &Event, r: &[String]) -> Result<(), String> {
            self.inner.publish_durable(e, r).await
        }
        async fn fetch(&self, q: &Query, r: &[String]) -> Result<Vec<Event>, String> {
            let out = self.inner.fetch(q, r).await;
            if self.armed.swap(false, std::sync::atomic::Ordering::SeqCst) {
                crate::db::set_current_account(self.to.clone()).unwrap();
                crate::db::init_database(&self.to).unwrap();
            }
            out
        }
    }

    /// Bumps the session generation on the first `publish_durable` — the rekey
    /// crate a private-channel create ships before it writes anything locally.
    struct SwapMidPublish {
        inner: MemoryRelay,
    }
    #[async_trait::async_trait]
    impl Transport for SwapMidPublish {
        async fn fetch_plane(&self, _plane: &Keys, query: &Query, relays: &[String]) -> Result<crate::community::transport::PlaneFetch, String> { Ok(crate::community::transport::PlaneFetch::whole(self.fetch(query, relays).await?)) }
        async fn publish(&self, e: &Event, r: &[String]) -> Result<(), String> {
            self.inner.publish(e, r).await
        }
        async fn publish_durable(&self, e: &Event, r: &[String]) -> Result<(), String> {
            let out = self.inner.publish_durable(e, r).await;
            crate::db::close_database();
            out
        }
        async fn fetch(&self, q: &Query, r: &[String]) -> Result<Vec<Event>, String> {
            self.inner.fetch(q, r).await
        }
    }

    /// A transport whose `fetch` returns a FIXED, UNSORTED event list — modelling
    /// the production `LiveTransport` union (first-responding relay's batch, no
    /// global newest-first sort), which `MemoryRelay` hides by sorting. This is
    /// the only harness that can exercise the revocation-race ordering.
    struct FixedFetch {
        events: Vec<Event>,
    }
    #[async_trait::async_trait]
    impl Transport for FixedFetch {
        async fn fetch_plane(&self, _plane: &Keys, query: &Query, relays: &[String]) -> Result<crate::community::transport::PlaneFetch, String> { Ok(crate::community::transport::PlaneFetch::whole(self.fetch(query, relays).await?)) }
        async fn publish(&self, _e: &Event, _r: &[String]) -> Result<(), String> {
            Ok(())
        }
        async fn publish_durable(&self, _e: &Event, _r: &[String]) -> Result<(), String> {
            Ok(())
        }
        async fn fetch(&self, _q: &Query, _r: &[String]) -> Result<Vec<Event>, String> {
            Ok(self.events.clone())
        }
    }

    /// Fetch a pending Direct Invite (kind 3313 giftwrap) addressed to `me` — the
    /// indexed inbox query CORD-05 §6 defines: `{1059, #p:[me], #k:["3313"]}`.
    async fn fetch_direct_invite(relay: &MemoryRelay, relays: &[String], me: &PublicKey) -> Event {
        let q = Query {
            kinds: vec![stream::KIND_WRAP],
            p_tags: vec![me.to_hex()],
            k_tags: vec!["3313".to_string()],
            ..Default::default()
        };
        relay.fetch(&q, relays).await.unwrap().into_iter().next().expect("a direct invite is waiting")
    }

    #[tokio::test]
    async fn create_persists_and_reloads_a_v2_community() {
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let relays = vec!["wss://r".to_string()];

        let created = create_community(&relay, "Vectorville", relays.clone(), Some("hi".into())).await.unwrap();
        assert!(created.identity.verify());
        assert_eq!(created.owner().unwrap(), owner.public_key());
        assert_eq!(created.channels.len(), 1);

        // Held, and it reloads byte-faithfully.
        assert!(crate::db::community::community_held(created.id()).unwrap());
        let loaded = crate::db::community::load_community_v2(created.id()).unwrap().expect("reloads");
        assert_eq!(loaded.name, "Vectorville");
        assert_eq!(loaded.community_root, created.community_root);
        assert_eq!(loaded.identity, created.identity);
        assert_eq!(loaded.channels[0].id.0, created.channels[0].id.0);
        assert!(!loaded.channels[0].private);

        // The genesis control editions + the owner Join landed on the relay.
        assert!(relay.count_on("wss://r") >= 3, "2 genesis editions + 1 guestbook join");
    }

    /// The relay stores the event but its OK never arrives.
    /// Every publish but a Channel's access-plane deliveries, as a client that doesn't deliver keys
    /// with a grant.
    struct NoAccessDeliveries<'a>(&'a MemoryRelay, PublicKey);
    #[async_trait::async_trait]
    impl Transport for NoAccessDeliveries<'_> {
        async fn publish(&self, e: &Event, r: &[String]) -> Result<(), String> {
            if e.pubkey == self.1 {
                return Ok(());
            }
            self.0.publish(e, r).await
        }
        async fn fetch(&self, query: &Query, relays: &[String]) -> Result<Vec<Event>, String> {
            self.0.fetch(query, relays).await
        }
        async fn fetch_plane(&self, plane: &Keys, query: &Query, relays: &[String]) -> Result<crate::community::transport::PlaneFetch, String> {
            self.0.fetch_plane(plane, query, relays).await
        }
        async fn publish_durable(&self, e: &Event, r: &[String]) -> Result<(), String> {
            if e.pubkey == self.1 {
                return Ok(());
            }
            self.0.publish_durable(e, r).await
        }
    }

    struct LostAck<'a>(&'a MemoryRelay);
    #[async_trait::async_trait]
    impl Transport for LostAck<'_> {
        async fn publish(&self, e: &Event, r: &[String]) -> Result<(), String> {
            self.0.publish(e, r).await?;
            Err("timed out".into())
        }
        async fn fetch(&self, query: &Query, relays: &[String]) -> Result<Vec<Event>, String> {
            self.0.fetch(query, relays).await
        }
        async fn fetch_plane(&self, plane: &Keys, query: &Query, relays: &[String]) -> Result<crate::community::transport::PlaneFetch, String> {
            self.0.fetch_plane(plane, query, relays).await
        }
        async fn publish_durable(&self, e: &Event, r: &[String]) -> Result<(), String> {
            self.0.publish_durable(e, r).await
        }
    }

    /// Nothing reaches the relay.
    struct Unreachable<'a>(&'a MemoryRelay);
    #[async_trait::async_trait]
    impl Transport for Unreachable<'_> {
        async fn publish(&self, _e: &Event, _r: &[String]) -> Result<(), String> {
            Err("no relay accepted the event".into())
        }
        async fn fetch(&self, query: &Query, relays: &[String]) -> Result<Vec<Event>, String> {
            self.0.fetch(query, relays).await
        }
        async fn fetch_plane(&self, plane: &Keys, query: &Query, relays: &[String]) -> Result<crate::community::transport::PlaneFetch, String> {
            self.0.fetch_plane(plane, query, relays).await
        }
        async fn publish_durable(&self, _e: &Event, _r: &[String]) -> Result<(), String> {
            Err("no relay accepted the event".into())
        }
    }

    /// A message sent through `transport` that fails to publish, and its rumor id.
    async fn unconfirmed_send(relay: &MemoryRelay) -> (CommunityV2, ChannelId, String) {
        let community = create_community(relay, "Chat", vec!["wss://r".into()], None).await.unwrap();
        let general = community.channels[0].id;
        let ms = now_ms();
        let (author, _, epoch) = chat_send_context(&community, &general).unwrap();
        let rumor = outbound_rumor(&community, &general, chat::build_message_rumor(author, &general, epoch, "lost", None, &[], vec![], ms));
        let id = rumor.id.unwrap().to_hex();
        assert!(send_chat_message_at(&Unreachable(relay), &community, &general, "lost", None, &[], vec![], ms).await.is_err());
        (community, general, id)
    }

    #[tokio::test]
    async fn a_send_whose_ok_was_lost_counts_as_sent() {
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Chat", vec!["wss://r".into()], None).await.unwrap();
        let general = community.channels[0].id;
        let id = send_message(&LostAck(&relay), &community, &general, "landed").await.expect("read back from the relay");
        assert!(outbox::kept(&id).is_none(), "nothing left to resend");
    }

    #[tokio::test]
    async fn a_failed_send_is_kept_to_go_again_as_itself() {
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let (community, general, id) = unconfirmed_send(&relay).await;
        let wrap = outbox::kept(&id).expect("kept until a relay confirms it");
        assert!(crate::db::community::get_message_key(&id).unwrap().is_some(), "deletable even though no relay confirmed it");
        relay.publish(&wrap, &community.relays).await.unwrap();
        let page = fetch_channel(&relay, &community, &general, 100).await.unwrap();
        assert_eq!(page.iter().filter(|f| f.event.opened().rumor_id.to_hex() == id).count(), 1, "the kept wrap is the message itself");
    }

    #[tokio::test]
    async fn our_failed_message_read_back_shows_as_sent() {
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let (community, general, id) = unconfirmed_send(&relay).await;
        let channel = crate::simd::hex::bytes_to_hex_32(&general.0);
        {
            let mut st = crate::state::STATE.lock().await;
            st.ensure_community_chat(&channel);
            st.add_message_to_chat(&channel, &crate::types::Message { id: id.clone(), mine: true, failed: true, ..Default::default() });
        }
        relay.publish(&outbox::kept(&id).unwrap(), &community.relays).await.unwrap();
        let me = crate::my_public_key().unwrap();
        for f in fetch_channel(&relay, &community, &general, 100).await.unwrap() {
            crate::community::v2::inbound::apply_chat_to_state(&mut *crate::state::STATE.lock().await, &f.event, &channel, &me);
        }
        let st = crate::state::STATE.lock().await;
        let (_, row) = st.find_message(&id).expect("still one row");
        assert!(!row.failed && !row.pending, "a relay holding it proves it sent");
        assert!(outbox::kept(&id).is_none(), "and nothing is resent");
    }

    #[tokio::test]
    async fn owner_sends_and_reads_back_a_message() {
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Chat", vec!["wss://r".into()], None).await.unwrap();
        let general = community.channels[0].id;

        let id1 = send_message(&relay, &community, &general, "hello world").await.unwrap();
        let id2 = send_message(&relay, &community, &general, "second message").await.unwrap();
        assert_ne!(id1, id2);

        let page = fetch_channel(&relay, &community, &general, 100).await.unwrap();
        let texts: Vec<String> = page
            .iter()
            .filter_map(|f| match &f.event {
                ChatEvent::Message { .. } => Some(f.event.opened().rumor.content.clone()),
                _ => None,
            })
            .collect();
        assert_eq!(texts, vec!["hello world", "second message"], "messages round-trip in ms order");
    }

    #[test]
    fn send_stamps_never_repeat_within_a_process() {
        // Ordering is by the `ms` tag, and an optimized build seals several sends
        // per millisecond. Identical stamps fell through to the reader's
        // content-derived tiebreak, which knows nothing about which was typed
        // first, so a fast sender could watch its own messages come back
        // shuffled — the flake in `owner_sends_and_reads_back_a_message` once the
        // suite began compiling optimized. Distinctness must not depend on how
        // slow the build happens to be.
        let stamps: Vec<u64> = (0..5_000).map(|_| next_send_ms()).collect();
        for pair in stamps.windows(2) {
            assert!(pair[1] > pair[0], "stamps must strictly increase: {} then {}", pair[0], pair[1]);
        }
    }

    #[tokio::test]
    async fn same_millisecond_messages_order_by_rumor_id_not_relay_order() {
        // Cross-client half: when stamps DO collide (two senders, clock skew),
        // every reader must still agree. A bare `ms` sort left ties in whatever
        // order the relay served them across pages, so two readers could show the
        // same pair in opposite orders. The rumor id is content-derived, so
        // pinning ties to it is something every client computes identically.
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Ties", vec!["wss://r".into()], None).await.unwrap();
        let general = community.channels[0].id;

        let at = now_ms();
        for i in 0..6 {
            send_chat_message_at(&relay, &community, &general, &format!("tied {i}"), None, &[], vec![], at)
                .await
                .unwrap();
        }
        let page = fetch_channel(&relay, &community, &general, 100).await.unwrap();
        let msgs: Vec<(Vec<u8>, String)> = page
            .iter()
            .filter_map(|f| match &f.event {
                ChatEvent::Message { .. } => {
                    let o = f.event.opened();
                    Some((o.rumor_id.as_bytes().to_vec(), o.rumor.content.clone()))
                }
                _ => None,
            })
            .collect();
        assert_eq!(msgs.len(), 6, "all six tied messages read back");
        let got: Vec<String> = msgs.iter().map(|(_, c)| c.clone()).collect();
        let mut by_id = msgs.clone();
        by_id.sort_by(|a, b| a.0.cmp(&b.0));
        let expected: Vec<String> = by_id.into_iter().map(|(_, c)| c).collect();
        assert_eq!(got, expected, "ties resolve by rumor id, never by the relay's serving order");
    }

    #[tokio::test]
    async fn a_rapid_burst_carries_strictly_increasing_stamps() {
        // The call-site half: sends must draw from the monotonic stamp, not the
        // raw clock. An optimized build seals several per millisecond, and equal
        // stamps hand a sender's own ordering to the content tiebreak, which
        // knows nothing about typing order.
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Burst", vec!["wss://r".into()], None).await.unwrap();
        let general = community.channels[0].id;
        for i in 0..8 {
            send_message(&relay, &community, &general, &format!("msg {i}")).await.unwrap();
        }
        let page = fetch_channel(&relay, &community, &general, 100).await.unwrap();
        let stamps: Vec<u64> = page
            .iter()
            .filter_map(|f| match &f.event {
                ChatEvent::Message { .. } => Some(f.event.opened().at_ms),
                _ => None,
            })
            .collect();
        assert_eq!(stamps.len(), 8);
        for pair in stamps.windows(2) {
            assert!(pair[1] > pair[0], "a sender's own stamps must strictly increase, got {pair:?}");
        }
    }

    #[tokio::test]
    async fn a_second_member_reads_the_public_channel_from_the_root() {
        // A member who holds the community_root (via an invite bundle, modeled
        // here by cloning the community) reads the owner's public-channel message
        // — public channels need no key delivery, they derive from the root.
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Public", vec!["wss://r".into()], None).await.unwrap();
        let general = community.channels[0].id;
        send_message(&relay, &community, &general, "everyone can read this").await.unwrap();

        // The "member" reconstructs the same read coordinates from the root.
        let member_view = community.clone();
        let page = fetch_channel(&relay, &member_view, &general, 100).await.unwrap();
        assert_eq!(page.len(), 1);
        assert!(matches!(&page[0].event, ChatEvent::Message { .. }));
        assert_eq!(page[0].event.opened().rumor.content, "everyone can read this");
    }

    // ── Two-actor end-to-end (the create → invite → join → message loop) ──────

    async fn texts_in<T: crate::community::transport::Transport + ?Sized>(relay: &T, community: &CommunityV2, channel: &ChannelId) -> Vec<String> {
        fetch_channel(relay, community, channel, 100)
            .await
            .unwrap()
            .iter()
            .filter_map(|f| match &f.event {
                ChatEvent::Message { .. } => Some(f.event.opened().rumor.content.clone()),
                _ => None,
            })
            .collect()
    }

    /// History as the BACK-PAGING cursor reads it: every held epoch. Opening a
    /// channel deliberately reads only the live planes, so pre-rotation history is
    /// reached by paging, which is what a user scrolling up actually does.
    async fn all_texts_in<T: crate::community::transport::Transport + ?Sized>(
        relay: &T,
        community: &CommunityV2,
        channel: &ChannelId,
    ) -> Vec<String> {
        let from_now = now_ms() / 1000 + 3600;
        fetch_channel_history(
            relay,
            community,
            channel,
            100,
            8,
            None,
            Some(from_now),
            crate::community::transport::Evidence::Quorum,
            |_, _| true,
            |_| Default::default(),
        )
        .await
        .unwrap()
        .iter()
        .filter_map(|f| match &f.event {
            ChatEvent::Message { .. } => Some(f.event.opened().rumor.content.clone()),
            _ => None,
        })
        .collect()
    }

    #[tokio::test]
    async fn direct_invite_full_loop_owner_and_member_converse() {
        let (bed, owner, member) = TestBed::new();

        // Owner creates a community, posts, and Direct-Invites the member's npub.
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Guild", bed.relays.clone(), None).await.unwrap();
        let general = community.channels[0].id;
        send_message(&bed.relay, &community, &general, "owner: welcome!").await.unwrap();
        send_direct_invite(&bed.relay, &community, &member.keys.public_key(), None, None).await.unwrap();

        // Member (a DIFFERENT account, no prior knowledge) finds + accepts the invite.
        bed.swap_to(&member);
        assert!(
            crate::db::community::load_community_v2(community.id()).unwrap().is_none(),
            "the member does not hold the community before joining"
        );
        let invite_wrap = fetch_direct_invite(&bed.relay, &bed.relays, &member.keys.public_key()).await;
        let joined = accept_direct_invite(&bed.relay, &invite_wrap).await.unwrap();
        assert_eq!(joined.id().0, community.id().0, "joined the same community");
        assert!(joined.identity.verify(), "the joiner independently verifies the owner commitment");
        assert_eq!(joined.owner().unwrap(), owner.keys.public_key());

        // The member reads the owner's public-channel history and replies.
        assert_eq!(texts_in(&bed.relay, &joined, &general).await, vec!["owner: welcome!"]);
        send_message(&bed.relay, &joined, &general, "member: thanks for the invite").await.unwrap();

        // The owner reads the member's reply.
        bed.swap_to(&owner);
        assert_eq!(
            texts_in(&bed.relay, &community, &general).await,
            vec!["owner: welcome!", "member: thanks for the invite"],
            "both actors' messages interleave in ms order on the shared channel"
        );

        // The Guestbook memberlist now folds both participants.
        let members = memberlist(&bed.relay, &community).await.unwrap();
        assert!(members.contains(&owner.keys.public_key()), "owner is a member (genesis Join)");
        assert!(members.contains(&member.keys.public_key()), "member is a member (invite Join)");
        assert_eq!(members.len(), 2);
    }

    #[tokio::test]
    async fn a_member_asleep_through_activation_catches_up_on_waking() {
        // A device that stopped before Roles v2 (as code from before it would) misses the
        // switch, a Role only v2 knows, and a ban that Role's holder refounds. On waking with
        // this code it folds the new Roster and follows the rotation it would have refused.
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Sleeper", bed.relays.clone(), None).await.unwrap();
        let general = community.channels[0].id;
        send_direct_invite(&bed.relay, &community, &member.keys.public_key(), None, None).await.unwrap();
        bed.swap_to(&member);
        let invite = fetch_direct_invite(&bed.relay, &bed.relays, &member.keys.public_key()).await;
        let joined = accept_direct_invite(&bed.relay, &invite).await.unwrap();
        follow_control(&bed.relay, &joined).await.unwrap();

        bed.swap_to(&owner);
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        activate_roles_v2(&bed.relay, &held(), crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        let mods = create_role_v2(&bed.relay, &held(), "Mods", 0, Permissions::BAN | Permissions::KICK).await.unwrap();
        let x = Keys::generate();
        set_member_roles(&bed.relay, &held(), &x.public_key(), vec![mods]).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        act_as(&x);
        set_members_banned(&bed.relay, held().id(), &[Keys::generate().public_key()], true).await.unwrap();
        act_as(&owner.keys);
        let epoch = held().root_epoch;
        assert_ne!(epoch, community.root_epoch, "the Mods holder refounded");
        send_message(&bed.relay, &held(), &general, "after the ban").await.unwrap();

        // Waking: floors written before families existed record none.
        bed.swap_to(&member);
        crate::db::get_write_connection_guard_static().unwrap().execute("UPDATE community_edition_heads SET family = NULL", []).unwrap();
        let mine = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let session = crate::db::current_session();
        let _ = follow_rekeys(&bed.relay, &mine(), &session).await;
        assert_eq!(mine().root_epoch, community.root_epoch, "on its old Roster the rotator has no standing");
        follow_control(&bed.relay, &mine()).await.unwrap();
        follow_rekeys(&bed.relay, &mine(), &session).await.unwrap();
        follow_control(&bed.relay, &mine()).await.unwrap();
        assert_eq!(mine().root_epoch, epoch, "it followed the rotation");
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
        assert!(roster.everyone.is_some(), "on the new Roster");
        assert!(roster.is_authorized(&x.public_key().to_hex(), Some(&owner.keys.public_key().to_hex()), Permissions::BAN), "with the Role only it knows");
        assert!(texts_in(&bed.relay, &mine(), &general).await.contains(&"after the ban".to_string()), "and reads what was said since");
    }

    /// Join-time ban gate: an honest client whose npub is on the authorized banlist
    /// refuses to join — no Guestbook Join publish, no local write — through the shared
    /// accept path every door (direct invite, parked, public link, migration) funnels into.
    #[tokio::test]
    async fn a_banned_member_is_refused_at_join_time() {
        let (bed, owner, member) = TestBed::new();

        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "NoEntry", bed.relays.clone(), None).await.unwrap();
        send_direct_invite(&bed.relay, &community, &member.keys.public_key(), None, None).await.unwrap();
        set_banlist(&bed.relay, &community, &[member.keys.public_key().to_hex()]).await.unwrap();

        bed.swap_to(&member);
        let invite_wrap = fetch_direct_invite(&bed.relay, &bed.relays, &member.keys.public_key()).await;
        let err = accept_direct_invite(&bed.relay, &invite_wrap).await.unwrap_err();
        assert!(err.contains("banned"), "refusal names the reason: {err}");
        assert!(
            crate::db::community::load_community_v2(community.id()).unwrap().is_none(),
            "a refused join persists nothing"
        );

        // The gate is the LAST word only for banned members: an unbanned bystander with
        // the same invite path still joins (the gate doesn't over-refuse).
        bed.swap_to(&owner);
        set_banlist(&bed.relay, &community, &[]).await.unwrap();
        bed.swap_to(&member);
        let joined = accept_direct_invite(&bed.relay, &invite_wrap).await.unwrap();
        assert_eq!(joined.id().0, community.id().0, "unban restores joinability");
    }

    #[tokio::test]
    async fn every_device_lists_the_links_another_minted_and_drops_those_it_revoked() {
        let (bed, owner, _member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Linked", bed.relays.clone(), None).await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let a = mint_public_link(&bed.relay, &community, "https://vectorapp.io", None, Some("Twitter".into())).await.unwrap();
        let b = mint_public_link(&bed.relay, &community, "https://vectorapp.io", None, None).await.unwrap();
        let (ta, tb) = (crate::simd::hex::bytes_to_hex_16(&a.token), crate::simd::hex::bytes_to_hex_16(&b.token));
        let listed = || {
            let mut out: Vec<(String, String, Option<String>)> = crate::db::community::list_public_invites(&cid_hex).unwrap().into_iter().map(|r| (r.token, r.url, r.label)).collect();
            out.sort();
            out
        };
        let minted = listed();
        // Another device of the same account: it minted neither.
        crate::db::community::delete_public_invite(&ta).unwrap();
        crate::db::community::delete_public_invite(&tb).unwrap();
        assert!(adopt_invite_list(&bed.relay, &held()).await.unwrap());
        assert_eq!(listed(), minted, "both links, as minted");
        assert!(!adopt_invite_list(&bed.relay, &held()).await.unwrap(), "nothing more to take");
        // Revoked on the first device while this one still lists it.
        revoke_public_link(&bed.relay, &held(), &ta).await.unwrap();
        crate::db::community::adopt_public_invite(&ta, &cid_hex, &a.url, None, Some("Twitter"), 0).unwrap();
        assert!(adopt_invite_list(&bed.relay, &held()).await.unwrap());
        assert_eq!(listed().into_iter().map(|(t, ..)| t).collect::<Vec<_>>(), vec![tb]);
    }

    #[tokio::test]
    async fn public_link_full_loop() {
        let (bed, owner, member) = TestBed::new();

        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Public Guild", bed.relays.clone(), None).await.unwrap();
        let general = community.channels[0].id;
        send_message(&bed.relay, &community, &general, "come on in").await.unwrap();
        // Mint a shareable link (a non-stock relay so the fragment carries it).
        let link = mint_public_link(&bed.relay, &community, "https://vectorapp.io", None, None).await.unwrap();
        assert!(link.url.starts_with("https://vectorapp.io/invite/"));
        assert!(link.url.contains('#'), "the fragment carries the token");

        // Member joins purely from the URL string.
        bed.swap_to(&member);
        let joined = accept_public_link(&bed.relay, &link.url).await.unwrap();
        assert_eq!(joined.id().0, community.id().0);
        assert_eq!(texts_in(&bed.relay, &joined, &general).await, vec!["come on in"]);
    }

    #[test]
    fn bundle_of_snapshots_the_held_icon() {
        let owner = Keys::generate();
        let g = control::genesis(&owner, control::CommunityMetadata { name: "Logo".into(), ..Default::default() }, 1_000).unwrap();
        let mut c = CommunityV2::from_genesis(&g, "Logo", None, vec!["wss://r".into()], 0);
        let icon = control::ImageRef { url: "https://blossom.example/i".into(), key: "k".into(), nonce: "n".into(), hash: "h".into(), extra: Default::default() };
        c.icon = Some(icon.clone());
        let bundle = bundle_of(&c, BundleAudience::Link, None, None, None);
        assert_eq!(bundle.icon, Some(icon), "a parked invite renders the real logo from the mint-time snapshot");
    }

    #[test]
    fn addressing_roots_fan_current_plus_archived_bounded_and_deduped() {
        // follow_rekeys' fetch fan AND streamauth's plane registration share
        // this. A channel rekey rides the PRIOR root (CORD-06 D2), so the set
        // MUST include archived roots or an AUTH-gated relay never serves the
        // rotation crate → the channel stalls at its old epoch.
        let (_tmp, _guard, _owner) = init_test_db();
        let cur_root = [9u8; 32];
        let cid = crate::community::CommunityId([1u8; 32]);
        let cid_hex = cid.to_hex();

        // No archives yet → just the current root.
        let roots = channel_rekey_addressing_roots(cur_root, &cid_hex);
        assert_eq!(roots, vec![cur_root], "with no archived roots the fan is the current root alone");

        // Archive two prior roots (freshest-first ordering is asserted below).
        crate::db::community::store_epoch_key(&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX, 0, &[1u8; 32]).unwrap();
        crate::db::community::store_epoch_key(&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX, 1, &[2u8; 32]).unwrap();
        let roots = channel_rekey_addressing_roots(cur_root, &cid_hex);
        assert_eq!(roots[0], cur_root, "current root leads");
        assert!(roots.contains(&[1u8; 32]) && roots.contains(&[2u8; 32]), "both archived roots are in the fan");
        assert_eq!(roots.len(), 3, "current + 2 archived, no dupes");
        // Freshest-archived-first (epoch 1 before epoch 0).
        assert_eq!(roots[1], [2u8; 32], "higher archived epoch is addressed before the lower");

        // A stored root equal to the CURRENT one must not duplicate.
        crate::db::community::store_epoch_key(&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX, 2, &cur_root).unwrap();
        let roots = channel_rekey_addressing_roots(cur_root, &cid_hex);
        assert_eq!(roots.iter().filter(|r| **r == cur_root).count(), 1, "the current root is never duplicated");

        // Cap: many archives truncate to MAX_ADDRESSING_ROOTS.
        for e in 3..20u64 {
            crate::db::community::store_epoch_key(&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX, e, &[e as u8; 32]).unwrap();
        }
        let roots = channel_rekey_addressing_roots(cur_root, &cid_hex);
        assert_eq!(roots.len(), MAX_ADDRESSING_ROOTS, "the fan is bounded so a relay can't feed an unbounded walk");
    }

    #[tokio::test]
    async fn inspecting_a_public_link_names_every_plane_and_publishes_nothing() {
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Guild", bed.relays.clone(), None).await.unwrap();
        let general = community.channels[0].id;
        send_message(&bed.relay, &community, &general, "hello").await.unwrap();
        let staff = create_private_channel(&bed.relay, &community, "staff").await.unwrap();
        let community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        send_message(&bed.relay, &community, &staff, "staff only").await.unwrap();
        let link = mint_public_link(&bed.relay, &community, "https://vectorapp.io", None, None).await.unwrap();

        bed.swap_to(&member);
        let before = bed.relay.stored_count();
        let seen = inspect_public_link(&bed.relay, &link.url, None, None).await.unwrap();
        assert_eq!(bed.relay.stored_count(), before, "inspecting publishes nothing");
        assert!(crate::db::community::load_community_v2(community.id()).unwrap().is_none(), "nor joins");
        assert!(seen.verified);
        assert_eq!((seen.name.as_str(), seen.community_id.as_str()), ("Guild", community.id().to_hex().as_str()));

        // A public link carries no Private Channel's key: #staff's posts are the one address it
        // can't name, and the inspection says so.
        let staff_ch = community.channels.iter().find(|c| c.id == staff).unwrap();
        let (staff_key, staff_epoch) = community.channel_secret(staff_ch);
        let staff_posts = channel_group_key(&staff_key, &staff, staff_epoch).pk().to_hex();
        assert!(seen.channels.iter().any(|c| c.name == "staff" && c.keyless));
        assert!(seen.gaps.iter().any(|g| g.contains("#staff")), "{:?}", seen.gaps);

        let named: std::collections::HashSet<&str> = seen.planes.iter().map(|p| p.pk.as_str()).collect();
        let wraps = bed.relay.fetch(&Query { kinds: vec![stream::KIND_WRAP], ..Default::default() }, &bed.relays).await.unwrap();
        let unnamed: Vec<String> = wraps.iter().map(|w| w.pubkey.to_hex()).filter(|pk| !named.contains(pk.as_str())).collect();
        assert_eq!(unnamed, vec![staff_posts], "planes: {:#?}", seen.planes);
        assert!(named.contains(link_signer_of(&link.url).as_str()));
    }

    #[test]
    fn a_fold_takes_the_floors_of_its_family_as_their_rows_record_it() {
        let (_tmp, _guard, _owner) = init_test_db();
        let cid = "cd".repeat(32);
        let (h, i, a) = ([1u8; 32], [2u8; 32], [3u8; 32]);
        use crate::db::community::{set_edition_head_at_epoch, set_family_head_at_epoch, FLOOR_AUTHORITY, FLOOR_CONTROL};
        set_family_head_at_epoch(&cid, "grant", 1, &h, &i, &a, 0, FLOOR_AUTHORITY).unwrap();
        set_family_head_at_epoch(&cid, "meta", 1, &h, &i, &a, 0, FLOOR_CONTROL).unwrap();
        set_family_head_at_epoch(&cid, "future", 1, &h, &i, &a, 0, "x").unwrap();
        set_edition_head_at_epoch(&cid, "legacy", 1, &h, &i, &a, 0).unwrap();
        let floors: Floors = crate::db::community::get_all_edition_heads_full(&cid).unwrap().into_iter().map(|(e, f)| (e, (f.1, f.2, f.3, f.4, f.5))).collect();
        let families = crate::db::community::edition_head_families(&cid).unwrap();
        for family in [FLOOR_AUTHORITY, FLOOR_CONTROL] {
            let mut by_query: Vec<String> = floors.keys().filter(|k| families.get(*k).is_none_or(|f| f == family)).cloned().collect();
            let mut taken: Vec<String> = floors_of_family(&floors, family).into_keys().collect();
            by_query.sort();
            taken.sort();
            assert_eq!(taken, by_query, "{family}");
        }
        let mut authority: Vec<String> = floors_of_family(&floors, FLOOR_AUTHORITY).into_keys().collect();
        authority.sort();
        assert_eq!(authority, ["grant", "legacy"], "a family this build doesn't know goes to neither fold");
    }

    #[test]
    fn ledger_chains_are_judged_as_the_reference_judges_them() {
        use super::super::writers::{Ledger, Spell};
        let mut seed: u64 = 0x9e37_79b9_7f4a_7c15;
        let mut rnd = move |n: usize| {
            seed ^= seed << 13;
            seed ^= seed >> 7;
            seed ^= seed << 17;
            (seed % n as u64) as usize
        };
        let (ch, elsewhere) = (ChannelId([7; 32]), ChannelId([8; 32]));
        let ch_hex = crate::simd::hex::bytes_to_hex_32(&ch.0);
        let authors: Vec<Keys> = (0..3).map(|_| Keys::generate()).collect();
        // One that is no point on the curve: a ledger naming it never parses.
        let writers: Vec<[u8; 32]> = (0..6).map(|_| Keys::generate().public_key().to_bytes()).chain([[0xff; 32]]).collect();
        let unserved: Vec<[u8; 32]> = (1..=3u8).map(|k| [k; 32]).collect();
        let now = now_ms();
        let mut forked = 0;
        for case in 0..600u64 {
            let n = 1 + rnd(36);
            let mut eds: Vec<ParsedEdition> = Vec::new();
            let mut ledgers: Vec<Ledger> = Vec::new();
            for i in 0..n {
                if !eds.is_empty() && rnd(14) == 0 {
                    // The same edition again, as two relays serve it. A Writers edition is read
                    // marked only, so its hash covers its signer: a copy is a copy.
                    let k = rnd(eds.len());
                    ledgers.push(ledgers[k].clone());
                    eds.push(eds[k].clone());
                    continue;
                }
                let parent = (!eds.is_empty() && rnd(5) != 0).then(|| rnd(eds.len()));
                let author = &authors[rnd(authors.len())];
                let at = now - 5_000_000 + i as u64 * 1000;
                let base = parent.map(|p| ledgers[p].clone()).unwrap_or_else(|| Ledger::new(&ch));
                let epoch = base.writers().last().map_or(1, |(e, ..)| e.0 + 1);
                let spell = match rnd(5) {
                    0 => Spell::Open,
                    1 => Spell::Stop { writer: writers[rnd(writers.len())] },
                    _ => Spell::Writer { epoch: Epoch(epoch), pk: writers[rnd(writers.len())], root: Epoch(0), by: author.public_key().to_bytes(), certifier: None },
                };
                let grown = base.appended(at, spell).unwrap_or_else(|| base.clone());
                let content = match rnd(12) {
                    0 => "not a ledger".to_string(),
                    1 => Ledger::new(&elsewhere).appended(at, Spell::Open).unwrap().to_json(),
                    2 => base.to_json(),
                    _ => grown.to_json(),
                };
                let prev_hash = match parent {
                    Some(p) => Some(eds[p].self_hash),
                    None if rnd(3) == 0 => Some(unserved[rnd(unserved.len())]),
                    None => None,
                };
                let version = parent.map_or(1, |p| eds[p].version + 1) + u64::from(rnd(12) == 0);
                let created_at = at / 1000 + if rnd(10) == 0 { 3600 } else { 0 };
                let self_hash = crate::crypto::sha256::digest(&[case.to_le_bytes(), (i as u64).to_le_bytes()].concat());
                eds.push(ParsedEdition {
                    author: author.public_key(),
                    vsk: String::new(),
                    entity_id: [0; 32],
                    version,
                    prev_hash,
                    content,
                    self_hash,
                    created_at,
                    inner_id: self_hash,
                    authority: None,
                    binding: None,
                });
                ledgers.push(grown);
            }
            forked += usize::from(eds.iter().filter(|e| eds.iter().filter(|o| o.prev_hash == e.prev_hash && e.prev_hash.is_some()).count() > 1).count() > 0);
            let mut order: Vec<usize> = (0..eds.len()).collect();
            for k in (1..order.len()).rev() {
                order.swap(k, rnd(k + 1));
            }
            let group: Vec<&ParsedEdition> = order.iter().map(|&k| &eds[k]).collect();
            let authorized: Vec<bool> = group.iter().map(|_| rnd(4) != 0).collect();
            let anchor = match rnd(4) {
                0 => {
                    let k = rnd(eds.len());
                    Some((eds[k].self_hash, ledgers[k].clone()))
                }
                1 => Some((unserved[rnd(unserved.len())], ledgers[rnd(ledgers.len())].clone())),
                _ => None,
            };
            let key = |e: &ParsedEdition| (u32::from(e.author.to_bytes()[0] % 2), e.inner_id);
            assert_eq!(
                ledger_chain_ok(&group, &authorized, &ch_hex, &key, anchor.as_ref()),
                ledger_chain_ok_reference(&group, &authorized, &ch_hex, &key, anchor.as_ref()),
                "case {case}"
            );
        }
        assert!(forked > 200, "the cases fork: {forked}");
    }

    #[tokio::test]
    async fn an_invite_bundle_inspects_as_its_link_does_less_the_link() {
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Guild", bed.relays.clone(), None).await.unwrap();
        send_message(&bed.relay, &community, &community.channels[0].id, "hello").await.unwrap();
        let link = mint_public_link(&bed.relay, &community, "https://vectorapp.io", None, None).await.unwrap();
        let json = serde_json::to_string(&bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None)).unwrap();

        bed.swap_to(&member);
        let by_link = inspect_public_link(&bed.relay, &link.url, None, None).await.unwrap();
        let before = bed.relay.stored_count();
        let bundle = CommunityInvite::from_bundle_json(&json).unwrap();
        let by_bundle = inspect_bundle(&bed.relay, &bundle, None, None).await.unwrap();
        assert_eq!(bed.relay.stored_count(), before, "inspecting publishes nothing");
        assert!(by_bundle.verified);
        assert_eq!(by_bundle.link_signer, None);
        assert!(!serde_json::to_value(&by_bundle).unwrap().as_object().unwrap().contains_key("link_signer"));
        assert_eq!((by_bundle.name.as_str(), by_bundle.community_id.as_str()), ("Guild", by_link.community_id.as_str()));
        let signer = link_signer_of(&link.url);
        let from_link: Vec<&InspectedPlane> = by_link.planes.iter().filter(|p| p.pk != signer).collect();
        assert_eq!(by_bundle.planes.iter().collect::<Vec<_>>(), from_link);
    }

    #[tokio::test]
    async fn an_inspection_reads_the_newest_posts_as_their_authors_left_them() {
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Guild", bed.relays.clone(), None).await.unwrap();
        let general = community.channels[0].id;
        let random = create_public_channel(&bed.relay, &community, "random").await.unwrap();
        let community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        create_private_channel(&bed.relay, &community, "staff").await.unwrap();
        let community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let tick = || crate::rt::time::sleep(std::time::Duration::from_millis(3));
        let one = send_message(&bed.relay, &community, &general, "one").await.unwrap();
        tick().await;
        let two = send_message(&bed.relay, &community, &general, "two").await.unwrap();
        tick().await;
        let three = send_message(&bed.relay, &community, &general, "three").await.unwrap();
        tick().await;
        send_message(&bed.relay, &community, &random, "r1").await.unwrap();
        tick().await;
        send_edit(&bed.relay, &community, &general, &two, "two, edited", &[]).await.unwrap();
        send_delete(&bed.relay, &community, &general, &three, 9, None).await.unwrap();
        let link = mint_public_link(&bed.relay, &community, "https://vectorapp.io", None, None).await.unwrap();

        bed.swap_to(&member);
        // Anyone holding the link's keys can wrap an edit or a delete; only an author's own count.
        let held = CommunityV2::from_bundle(&fetch_public_bundle(&bed.relay, &link.url).await.unwrap(), 0).unwrap();
        tick().await;
        send_edit(&bed.relay, &held, &general, &two, "hijacked", &[]).await.unwrap();
        send_delete(&bed.relay, &held, &general, &one, 9, None).await.unwrap();
        let read = |count: usize, channels: &[&str]| MessageRead { count, channels: channels.iter().map(|c| c.to_string()).collect() };
        let texts = |seen: &Inspection| seen.messages.iter().map(|m| (m.channel.clone(), m.content.clone(), m.edited)).collect::<Vec<_>>();

        let before = bed.relay.stored_count();
        let all = inspect_public_link(&bed.relay, &link.url, None, Some(&read(2, &[]))).await.unwrap();
        assert_eq!(bed.relay.stored_count(), before, "reading publishes nothing");
        assert_eq!(texts(&all), [("general".into(), "two, edited".into(), true), ("random".into(), "r1".into(), false)]);
        let npub = nostr_sdk::prelude::ToBech32::to_bech32(&owner.keys.public_key()).unwrap();
        assert!(all.messages.iter().all(|m| m.author == npub));

        let general_only = inspect_public_link(&bed.relay, &link.url, None, Some(&read(10, &["#General"]))).await.unwrap();
        assert_eq!(texts(&general_only), [("general".into(), "one".into(), false), ("general".into(), "two, edited".into(), true)], "a self-deleted post is gone");

        let missing = inspect_public_link(&bed.relay, &link.url, None, Some(&read(5, &["nope"]))).await.unwrap_err();
        assert!(missing.contains("#general") && missing.contains("#random"), "{missing}");
        assert!(inspect_public_link(&bed.relay, &link.url, None, Some(&read(5, &["staff"]))).await.unwrap_err().contains("private"));
        assert!(inspect_public_link(&bed.relay, &link.url, None, None).await.unwrap().messages.is_empty());

        // As Concord CLI reads: no account and no database.
        crate::db::close_database();
        let stateless = inspect_public_link(&bed.relay, &link.url, None, Some(&read(2, &[]))).await.unwrap();
        assert_eq!(texts(&stateless), texts(&all));
    }

    fn link_signer_of(url: &str) -> String {
        invite::parse_invite_link(url).unwrap().link_signer.to_hex()
    }

    #[tokio::test]
    async fn public_link_preview_shows_live_name_and_icon_without_joining() {
        let (bed, owner, member) = TestBed::new();

        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Soapbox", bed.relays.clone(), None).await.unwrap();
        // The icon lives on the Control Plane, never in the bundle — publish it
        // as a metadata edition so the preview must FOLD to see it.
        let icon = control::ImageRef {
            url: "https://blossom.example/soap".into(),
            key: "k".into(),
            nonce: "n".into(),
            hash: "h".into(),
            extra: Default::default(),
        };
        let mut meta = community.metadata();
        meta.icon = Some(icon.clone());
        edit_community_metadata(&bed.relay, &community, &meta).await.unwrap();
        // An any-host base — the naddr#fragment payload is domain-agnostic.
        let link = mint_public_link(&bed.relay, &community, "https://armada.buzz", None, None).await.unwrap();

        // A NON-member previews: the real name + the live icon, nothing persisted.
        bed.swap_to(&member);
        let preview = preview_public_link(&bed.relay, &link.url).await.unwrap();
        assert_eq!(preview.name, "Soapbox");
        assert_eq!(preview.icon, Some(icon), "the icon folds from the live Control Plane, not the bundle");
        assert!(
            crate::db::community::load_community_v2(preview.id()).unwrap().is_none(),
            "previewing must not persist a membership"
        );
    }

    #[tokio::test]
    async fn a_removed_icon_and_banner_leave_every_member() {
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Bare", bed.relays.clone(), None).await.unwrap();
        let image = |name: &str| control::ImageRef {
            url: format!("https://blossom.example/{name}"),
            key: "k".into(),
            nonce: "n".into(),
            hash: "h".into(),
            extra: Default::default(),
        };
        let mut meta = community.metadata();
        meta.icon = Some(image("icon"));
        meta.banner = Some(image("banner"));
        edit_community_metadata(&bed.relay, &community, &meta).await.unwrap();
        let link = mint_public_link(&bed.relay, &community, "https://vectorapp.io", None, None).await.unwrap();

        bed.swap_to(&member);
        let joined = accept_public_link(&bed.relay, &link.url).await.unwrap();
        assert!(joined.icon.is_some() && joined.banner.is_some());

        bed.swap_to(&owner);
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let mut meta = held.metadata();
        meta.icon = None;
        meta.banner = None;
        edit_community_metadata(&bed.relay, &held, &meta).await.unwrap();
        persist_community_image(community.id(), None, false).await.unwrap();
        let mine = persist_community_image(community.id(), None, true).await.unwrap();
        assert!(mine.icon.is_none() && mine.banner.is_none(), "the remover's own copy drops them at once");

        bed.swap_to(&member);
        let theirs = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        follow_control(&bed.relay, &theirs).await.unwrap();
        let theirs = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        assert!(theirs.icon.is_none(), "an edition without the icon removes it");
        assert!(theirs.banner.is_none(), "and the banner");
        assert_eq!(theirs.metadata().name, "Bare", "nothing else moves");
    }

    #[tokio::test]
    async fn an_own_metadata_edit_reads_back_before_any_control_pass() {
        let (bed, owner, _member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Echo", bed.relays.clone(), None).await.unwrap();
        let mut meta = community.metadata();
        meta.name = "Echoed".into();
        meta.extra.insert("voice_relays".into(), serde_json::json!(["https://voice.example/"]));
        edit_community_metadata(&bed.relay, &community, &meta).await.unwrap();
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        assert_eq!(held().name, "Echoed");
        assert_eq!(held().voice_relays(), vec!["https://voice.example/".to_string()]);
        follow_control(&bed.relay, &held()).await.unwrap();
        assert_eq!(held().voice_relays(), vec!["https://voice.example/".to_string()], "the fold lands the same head");
    }

    #[tokio::test]
    async fn a_previewed_join_reuses_the_verified_fold() {
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "FastJoin", bed.relays.clone(), None).await.unwrap();
        let link = mint_public_link(&bed.relay, &community, "https://vectorapp.io", None, None).await.unwrap();

        bed.swap_to(&member);
        let _ = preview_public_link(&bed.relay, &link.url).await.unwrap();
        let joined = accept_public_link(&bed.relay, &link.url).await.unwrap();
        assert_eq!(joined.id().0, community.id().0);
        assert!(joined.created_at_ms > 0, "the handoff stamps the JOIN's acquisition time, not the preview's");
        // The slot was CONSUMED by the join — proving the handoff path ran (a
        // verify re-walk would have left the preview's entry in place).
        assert!(VERIFIED_PREVIEW.lock().unwrap().is_none(), "the handoff slot must be consumed by the join");
    }

    #[tokio::test]
    async fn an_unjoined_preview_is_let_go_once_its_ttl_lapses() {
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Window", bed.relays.clone(), None).await.unwrap();
        let link = mint_public_link(&bed.relay, &community, "https://vectorapp.io", None, None).await.unwrap();
        bed.swap_to(&member);
        let _ = preview_public_link(&bed.relay, &link.url).await.unwrap();
        let seq = VERIFIED_PREVIEW.lock().unwrap().as_ref().map(|v| v.seq).expect("a preview parks its fold");

        expire_verified_preview(seq.wrapping_add(1));
        assert!(VERIFIED_PREVIEW.lock().unwrap().is_some(), "another preview's expiry leaves this one be");

        // Paused, the clock jumps straight to each due timer.
        tokio::time::pause();
        tokio::time::sleep(VERIFIED_PREVIEW_TTL + std::time::Duration::from_secs(1)).await;
        assert!(VERIFIED_PREVIEW.lock().unwrap().is_none(), "an unjoined preview must not stay resident");
    }

    #[tokio::test]
    async fn the_admin_pin_upgrade_is_offered_once_per_account_session() {
        let (a, b) = (crate::db::Session::empty(), crate::db::Session::empty());
        let id = crate::community::CommunityId([0x5A; 32]);
        let offer = |s| crate::db::with_session(s, async move { first_admin_pin_upgrade(&id) });
        assert!(offer(a.clone()).await, "the first fold offers it");
        assert!(!offer(a).await, "a one-shot within the session");
        assert!(offer(b).await, "an owner logging in later in the same process still gets it");
    }

    #[tokio::test]
    async fn guestbook_store_seeds_syncs_incrementally_and_matches_the_live_fold() {
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "GB", bed.relays.clone(), None).await.unwrap();
        let link = mint_public_link(&bed.relay, &community, "https://vectorapp.io", None, None).await.unwrap();

        bed.swap_to(&member);
        let joined = accept_public_link(&bed.relay, &link.url).await.unwrap();

        // Seed from zero: the stored fold equals the authoritative live fold.
        assert!(!sync_guestbook(&bed.relay, &joined).await.unwrap().is_empty(), "the seed folds fresh events");
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&joined.id().0);
        let (_, cursor) = crate::db::community::get_guestbook(&cid_hex).unwrap();
        assert!(cursor > 0, "the cursor advanced past zero");
        let stored: std::collections::BTreeSet<_> = stored_memberlist(&joined).unwrap().into_iter().collect();
        let live: std::collections::BTreeSet<_> = memberlist(&bed.relay, &joined).await.unwrap().into_iter().collect();
        assert_eq!(stored, live, "stored fold == live fold after the seed");
        assert!(stored.contains(&member.keys.public_key()));

        // Nothing new on the plane → an idle re-sync folds nothing.
        assert!(sync_guestbook(&bed.relay, &joined).await.unwrap().is_empty());

        // The owner kicks the member; a CURSOR catch-up folds the kick in — no full walk.
        bed.swap_to(&owner);
        kick_member(&bed.relay, &community, &member.keys.public_key()).await.unwrap();
        bed.swap_to(&member);
        assert!(!sync_guestbook(&bed.relay, &joined).await.unwrap().is_empty(), "the kick lands incrementally");
        assert!(
            !stored_memberlist(&joined).unwrap().contains(&member.keys.public_key()),
            "an owner kick removes the member from the stored fold"
        );
    }

    #[tokio::test]
    async fn a_preview_then_revoke_still_refuses_the_join() {
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "RevokeRace", bed.relays.clone(), None).await.unwrap();
        let link = mint_public_link(&bed.relay, &community, "https://vectorapp.io", None, None).await.unwrap();

        // Member previews (warming the verified handoff), THEN the owner revokes.
        bed.swap_to(&member);
        let p = preview_public_link(&bed.relay, &link.url).await.unwrap();
        assert_eq!(p.name, "RevokeRace");
        bed.swap_to(&owner);
        let tombstone = invite::build_revocation(&link.link_signer).unwrap();
        bed.relay.publish_durable(&tombstone, &bed.relays).await.unwrap();

        // The join MUST refuse: the handoff skips only the root re-verify, never
        // the bundle re-fetch that carries the revocation gate.
        bed.swap_to(&member);
        let err = accept_public_link(&bed.relay, &link.url).await.unwrap_err();
        assert!(err.contains("revoked"), "got: {err}");
    }

    #[tokio::test]
    async fn a_revoked_link_refuses_to_join() {
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Revoked", bed.relays.clone(), None).await.unwrap();
        let link = mint_public_link(&bed.relay, &community, "https://vectorapp.io", None, None).await.unwrap();
        // Owner retires the link (re-posts the coordinate as a tombstone).
        let tombstone = invite::build_revocation(&link.link_signer).unwrap();
        bed.relay.publish_durable(&tombstone, &bed.relays).await.unwrap();

        bed.swap_to(&member);
        let err = accept_public_link(&bed.relay, &link.url).await.unwrap_err();
        assert!(err.contains("revoked"), "a retired link finds the grave, not keys: {err}");
    }

    #[tokio::test]
    async fn an_expired_direct_invite_refuses_to_join() {
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Expired", bed.relays.clone(), None).await.unwrap();
        // Hand-mint an invite that expired in the past.
        let inviter = owner.keys.clone();
        let mut bundle = bundle_of(&community, BundleAudience::Link, Some(inviter.public_key()), Some(1_000), None);
        bundle.expires_at = Some(1_000); // unix ms, long past
        let wrap = invite::build_direct_invite(&inviter, &member.keys.public_key(), &bundle).unwrap();
        bed.relay.publish(&wrap, &bed.relays).await.unwrap();

        bed.swap_to(&member);
        let invite_wrap = fetch_direct_invite(&bed.relay, &bed.relays, &member.keys.public_key()).await;
        let err = accept_direct_invite(&bed.relay, &invite_wrap).await.unwrap_err();
        assert!(err.contains("expired"), "a past-expiry invite refuses to join: {err}");
    }

    #[tokio::test]
    async fn a_tombstone_beats_a_live_bundle_regardless_of_fetch_order() {
        // The revocation-durability fix: if ANY signer-valid tombstone is among the
        // fetched events, refuse — even when a Live bundle is returned FIRST (the
        // production union has no newest-first sort, so a stale relay's Live can lead).
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Rev", bed.relays.clone(), None).await.unwrap();
        let link = mint_public_link(&bed.relay, &community, "https://vectorapp.io", None, None).await.unwrap();
        let tombstone = invite::build_revocation(&link.link_signer).unwrap();

        // A relay union that hands back [Live, tombstone] — Live FIRST. Old
        // `events.first()` would join the Live; the scan-all fix must refuse.
        let union = FixedFetch { events: vec![link.bundle_event.clone(), tombstone] };

        bed.swap_to(&member);
        let err = accept_public_link(&union, &link.url).await.unwrap_err();
        assert!(err.contains("revoked"), "a tombstone must beat a Live returned first: {err}");
    }

    #[test]
    fn from_bundle_refuses_an_over_cap_bundle_before_allocating() {
        // The accept-side DoS bound: from_bundle (which accept_bundle calls)
        // rejects a >256-channel bundle via validate() BEFORE the Vec allocation.
        // (The Direct-Invite wire path is additionally bounded by NIP-44's 64KB
        // cap, which trips even earlier — but the count guard is the real defense
        // for the single-layer public-link bundle.)
        let owner = Keys::generate();
        let identity = super::super::control::CommunityIdentity::mint(&owner.public_key());
        let hex = crate::simd::hex::bytes_to_hex_32;
        let root = [0x11u8; 32];
        let mut bundle = CommunityInvite {
            community_id: hex(&identity.community_id.0),
            owner: hex(&identity.owner_xonly),
            owner_salt: hex(&identity.owner_salt),
            community_root: hex(&root),
            root_epoch: 0,
            control_pk: None,
            channels: vec![],
            relays: vec!["wss://r".into()],
            name: "X".into(),
            icon: None,
            expires_at: None,
            creator_npub: None,
            label: None,
            extra: Default::default(),
        };
        bundle.channels = (0..=invite::MAX_BUNDLE_CHANNELS)
            .map(|i| {
                let mut id = [0u8; 32];
                id[..8].copy_from_slice(&(i as u64).to_be_bytes());
                invite::ChannelGrant { id: hex(&id), key: hex(&root), epoch: 0, name: "x".into() }
            })
            .collect();
        assert!(CommunityV2::from_bundle(&bundle, 0).is_err(), "an over-cap bundle is refused before allocating");
    }

    #[tokio::test]
    async fn a_join_swap_between_fetch_and_save_lands_in_the_joining_account() {
        // A public-link accept fetches, then saves. A swap in that window used to
        // abort the join outright; the community is now written to the account
        // that clicked the link, and the account swapped in gets nothing.
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Straddle", bed.relays.clone(), None).await.unwrap();
        let link = mint_public_link(&bed.relay, &community, "https://vectorapp.io", None, None).await.unwrap();
        bed.swap_to(&member);
        let joiner = crate::db::current_session();
        let swap_relay = SwapMidFetch::arm(&bed.relay);
        accept_public_link(&swap_relay, &link.url).await.unwrap();

        assert!(
            crate::db::with_session(joiner, async {
                crate::db::community::load_community_v2(community.id()).unwrap().is_some()
            })
            .await,
            "the join completed for the account that accepted the link"
        );
    }

    #[tokio::test]
    async fn the_owner_is_a_member_even_without_a_fetched_genesis_join() {
        // The owner is derived from the self-certifying community_id, so the
        // memberlist includes them independent of any Guestbook fetch.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Owned", vec!["wss://r".into()], None).await.unwrap();
        // A memberlist over an EMPTY guestbook (fetch a community-relay-less view)
        // still contains the owner.
        let empty = MemoryRelay::new();
        let members = memberlist(&empty, &community).await.unwrap();
        assert_eq!(members, vec![owner.public_key()], "owner present with no fetched Join");
    }

    #[tokio::test]
    async fn an_expiring_minted_invite_refuses_after_the_deadline() {
        // The mint path can now produce an expiring invite, and the accept gate
        // trips on it (end-to-end through the real service, not a hand-built bundle).
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Timed", bed.relays.clone(), None).await.unwrap();
        send_direct_invite(&bed.relay, &community, &member.keys.public_key(), Some(1_000), Some("beta".into()))
            .await
            .unwrap();

        bed.swap_to(&member);
        let invite_wrap = fetch_direct_invite(&bed.relay, &bed.relays, &member.keys.public_key()).await;
        assert!(
            accept_direct_invite(&bed.relay, &invite_wrap).await.unwrap_err().contains("expired"),
            "a minted expiring invite refuses past its deadline"
        );
    }

    #[tokio::test]
    async fn a_member_who_leaves_drops_from_the_memberlist() {
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Leaving", bed.relays.clone(), None).await.unwrap();
        send_direct_invite(&bed.relay, &community, &member.keys.public_key(), None, None).await.unwrap();

        bed.swap_to(&member);
        let invite_wrap = fetch_direct_invite(&bed.relay, &bed.relays, &member.keys.public_key()).await;
        let joined = accept_direct_invite(&bed.relay, &invite_wrap).await.unwrap();
        // Let the leave land strictly after the join.
        crate::rt::time::sleep(std::time::Duration::from_millis(2)).await;
        leave_community(&bed.relay, &joined).await.unwrap();

        bed.swap_to(&owner);
        let members = memberlist(&bed.relay, &community).await.unwrap();
        assert!(members.contains(&owner.keys.public_key()));
        assert!(!members.contains(&member.keys.public_key()), "a member who left drops from the list");
    }

    #[tokio::test]
    async fn a_request_from_a_fellow_member_shows_their_pictures_until_they_leave() {
        use nostr_sdk::prelude::ToBech32;
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Mutual", bed.relays.clone(), None).await.unwrap();
        let link = mint_public_link(&bed.relay, &community, "https://vectorapp.io", None, None).await.unwrap();
        bed.swap_to(&member);
        let joined = accept_public_link(&bed.relay, &link.url).await.unwrap();

        let fellow = member.keys.public_key().to_bech32().unwrap();
        let stranger = Keys::generate().public_key().to_bech32().unwrap();
        let requests_from = |npubs: [String; 2]| async move {
            let mut guard = crate::state::STATE.lock().await;
            let state = &mut *guard;
            for npub in npubs {
                let mut chat = crate::chat::Chat::new_dm(npub, &mut state.interner);
                let hi = crate::types::Message { id: "ab".repeat(32), content: "hi".into(), at: 1_700_000_000_000, ..Default::default() };
                chat.add_message(hi, &mut state.interner);
                state.chats.push(chat);
            }
        };

        bed.swap_to(&owner);
        sync_guestbook(&bed.relay, &community).await.unwrap();
        requests_from([fellow.clone(), stranger.clone()]).await;
        assert!(!crate::requests::pictures_held(&fellow).await, "a fellow member's pictures show");
        assert!(crate::requests::pictures_held(&stranger).await, "a stranger's wait");
        assert_eq!(crate::requests::request_mutuals().await, vec![fellow.clone()]);
        assert_eq!(crate::requests::held_pictures().await, [stranger.clone()].into());

        bed.swap_to(&member);
        crate::rt::time::sleep(std::time::Duration::from_millis(2)).await;
        leave_community(&bed.relay, &joined).await.unwrap();
        bed.swap_to(&owner);
        sync_guestbook(&bed.relay, &community).await.unwrap();
        requests_from([fellow.clone(), stranger]).await;
        assert!(crate::requests::pictures_held(&fellow).await, "gone from every Community we share, their request holds them again");
    }

    #[tokio::test]
    async fn a_relay_that_has_reconciled_stays_confirmed_until_it_refuses() {
        use crate::negentropy::{neg_ever_confirmed, record_neg_support};
        let (bed, owner, _member) = TestBed::new();
        bed.swap_to(&owner);
        let url = "wss://slow.example";
        assert!(!neg_ever_confirmed(url), "unknown is not confirmed");
        record_neg_support(url, true);
        assert!(neg_ever_confirmed(url));
        record_neg_support(url, false);
        assert!(!neg_ever_confirmed(url), "a refusal unlearns it");
    }

    #[tokio::test]
    async fn a_local_leave_is_gone_at_once_and_announced_after() {
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Leaving", bed.relays.clone(), None).await.unwrap();
        send_direct_invite(&bed.relay, &community, &member.keys.public_key(), None, None).await.unwrap();

        bed.swap_to(&member);
        let invite_wrap = fetch_direct_invite(&bed.relay, &bed.relays, &member.keys.public_key()).await;
        let joined = accept_direct_invite(&bed.relay, &invite_wrap).await.unwrap();
        crate::rt::time::sleep(std::time::Duration::from_millis(2)).await;

        let at_ms = leave_locally(&joined).unwrap();
        let id_hex = crate::simd::hex::bytes_to_hex_32(&joined.id().0);
        assert!(crate::db::community::load_community_v2(joined.id()).unwrap().is_none(), "gone here before any publish");
        assert!(tombstone_suppresses(&id_hex, at_ms / 1000), "the tombstone is kept before it publishes");
        assert!(load_pending().tombstones.iter().any(|t| t.community_id == id_hex), "pending until it lands");

        bed.swap_to(&owner);
        assert!(memberlist(&bed.relay, &community).await.unwrap().contains(&member.keys.public_key()), "nothing published yet");

        bed.swap_to(&member);
        announce_leave(&bed.relay, &joined, at_ms).await;
        bed.swap_to(&owner);
        assert!(!memberlist(&bed.relay, &community).await.unwrap().contains(&member.keys.public_key()), "the Leave lands after");
    }

    async fn chats_naming(community_hex: &str) -> usize {
        crate::state::STATE.lock().await.chats.iter().filter(|c| c.metadata.community_id() == Some(community_hex)).count()
    }

    fn chat_rows(ids: &[String]) -> usize {
        let conn = crate::db::get_db_connection_guard_static().unwrap();
        ids.iter()
            .filter(|id| conn.query_row("SELECT 1 FROM chats WHERE chat_identifier = ?1", [id.as_str()], |_| Ok(())).is_ok())
            .count()
    }

    #[tokio::test]
    async fn a_leave_takes_every_chat_of_the_community_with_it() {
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Chatty", vec!["wss://r".to_string()], None).await.unwrap();
        create_public_channel(&relay, &community, "second").await.unwrap();
        let community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        crate::register_v2_chats_inner(&community).await;
        let id_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let channels: Vec<String> = community.channels.iter().map(|c| crate::simd::hex::bytes_to_hex_32(&c.id.0)).collect();
        assert_eq!((chats_naming(&id_hex).await, chat_rows(&channels)), (2, 2));

        crate::VectorCore.leave_community_now(&id_hex).await.unwrap();
        assert_eq!(chats_naming(&id_hex).await, 0);
        assert_eq!(chat_rows(&channels), 0, "no chat row is left to come back as a ghost on the next load");
    }

    #[tokio::test]
    async fn a_community_whose_chats_outlived_it_can_still_be_left_here_and_on_the_list() {
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Ghost", vec!["wss://r".to_string()], None).await.unwrap();
        crate::register_v2_chats_inner(&community).await;
        let id_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let channels: Vec<String> = community.channels.iter().map(|c| crate::simd::hex::bytes_to_hex_32(&c.id.0)).collect();
        crate::db::community::delete_community(&id_hex).unwrap();
        assert_eq!((chats_naming(&id_hex).await, chat_rows(&channels)), (1, 1), "the row is gone, its chat is not");

        let at_ms = leave_unheld_locally(community.id()).await.expect("its chat names it");
        assert_eq!((chats_naming(&id_hex).await, chat_rows(&channels)), (0, 0));
        assert!(tombstone_suppresses(&id_hex, at_ms / 1000), "kept pending before it publishes");

        announce_unheld_leave(&relay, community.id(), at_ms).await;
        let read = read_fragments(&relay, &list_read_relays(&[]).await).await.unwrap();
        let list = read.set.expect("the List was written").list;
        assert!(list.tombstones.iter().any(|t| t.community_id == id_hex), "the List carries the leave");

        assert!(leave_unheld_locally(community.id()).await.is_none(), "nothing here names it now");
        assert!(crate::VectorCore.leave_community_now(&id_hex).await.is_err());
    }

    #[tokio::test]
    async fn a_swapped_member_cannot_see_the_owners_community_until_joining() {
        // Multi-account isolation: after the swap, the member's DB holds nothing
        // of the owner's community — community storage is per-account.
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Private-so-far", bed.relays.clone(), None).await.unwrap();
        assert!(crate::db::community::load_community_v2(community.id()).unwrap().is_some());

        bed.swap_to(&member);
        assert!(
            crate::db::community::load_community_v2(community.id()).unwrap().is_none(),
            "the owner's community must be invisible in the member's account DB"
        );
        assert_eq!(crate::db::community::list_community_ids().unwrap().len(), 0);
    }

    // ── Live control-follow ──────────────────────────────────────────────────

    /// Publish an owner-grammar channel edition straight to the control plane,
    /// signed by `signer` (the owner for a legit edit, a stranger for the
    /// authority test). `version`/`deleted` drive add-vs-rename-vs-delete.
    /// The entity's current head `self_hash` on the relay (highest version wins),
    /// so a helper can chain a new edition the way a real owner client does.
    async fn head_hash_on_relay(relay: &MemoryRelay, community: &CommunityV2, entity_id: &[u8; 32]) -> Option<[u8; 32]> {
        let group = control::ControlPlane::of(&community).write_group().unwrap();
        let query = Query { kinds: vec![stream::KIND_WRAP], authors: vec![group.pk_hex()], limit: Some(500), ..Default::default() };
        let wraps = relay.fetch(&query, &community.relays).await.ok()?;
        let mut head: Option<(u64, [u8; 32])> = None;
        for w in &wraps {
            if let Ok((ed, _)) = control::open_control_edition(w, &group) {
                if ed.entity_id == *entity_id && head.is_none_or(|(v, _)| ed.version > v) {
                    head = Some((ed.version, ed.self_hash));
                }
            }
        }
        head.map(|(_, h)| h)
    }

    /// The `vac` a non-owner signer must attach, read off the Grant they were
    /// given on the relay (CORD-04 §5). The owner cites nothing. Mirrors what a
    /// real client does via `my_authority_citation`, so the fixtures publish the
    /// shape Vector actually emits.
    async fn cite_on_relay(
        relay: &MemoryRelay,
        community: &CommunityV2,
        signer: &Keys,
    ) -> Option<crate::community::edition::AuthorityCitation> {
        if community.owner().ok() == Some(signer.public_key()) {
            return None;
        }
        let entity_id = crate::community::v2::derive::grant_locator(community.id(), &signer.public_key().to_bytes());
        let group = control::ControlPlane::of(&community).write_group().unwrap();
        let query = Query { kinds: vec![stream::KIND_WRAP], authors: vec![group.pk_hex()], limit: Some(500), ..Default::default() };
        let wraps = relay.fetch(&query, &community.relays).await.ok()?;
        let mut head: Option<(u64, [u8; 32])> = None;
        for w in &wraps {
            if let Ok((ed, _)) = control::open_control_edition(w, &group) {
                if ed.entity_id == entity_id && head.is_none_or(|(v, _)| ed.version > v) {
                    head = Some((ed.version, ed.self_hash));
                }
            }
        }
        head.map(|(version, edition_hash)| crate::community::edition::AuthorityCitation { entity_id, version, edition_hash })
    }

    async fn publish_channel_edition(
        relay: &MemoryRelay,
        community: &CommunityV2,
        signer: &Keys,
        channel_id: &ChannelId,
        name: &str,
        private: bool,
        version: u64,
        deleted: bool,
    ) {
        let group = control::ControlPlane::of(&community).write_group().unwrap();
        let prev = head_hash_on_relay(relay, community, &channel_id.0).await;
        let meta = control::ChannelMetadata { name: name.into(), private, deleted: deleted.then_some(true), ..Default::default() };
        let content = serde_json::to_string(&meta).unwrap();
        let rumor = control::build_edition_rumor(signer.public_key(), vsk::CHANNEL_METADATA, &channel_id.0, version, prev.as_ref(), &content, 1_000, None);
        let (wrap, _) = control::seal_control_edition(&rumor, &group, signer, Timestamp::from_secs(1_000)).unwrap();
        relay.publish(&wrap, &community.relays).await.unwrap();
    }

    /// A channel edition at an EXPLICIT time, so a paging test can order the plane —
    /// the default helper stamps everything 1_000, which leaves newest-first paging
    /// arbitrary and any "buried edition" scenario vacuous.
    #[allow(clippy::too_many_arguments)]
    async fn publish_channel_edition_at(
        relay: &MemoryRelay,
        community: &CommunityV2,
        signer: &Keys,
        channel_id: &ChannelId,
        name: &str,
        version: u64,
        at_secs: u64,
    ) {
        let group = control::ControlPlane::of(community).write_group().unwrap();
        let meta = control::ChannelMetadata { name: name.into(), private: false, deleted: None, ..Default::default() };
        let content = serde_json::to_string(&meta).unwrap();
        let rumor = control::build_edition_rumor(signer.public_key(), vsk::CHANNEL_METADATA, &channel_id.0, version, None, &content, at_secs, None);
        let (wrap, _) = control::seal_control_edition(&rumor, &group, signer, Timestamp::from_secs(at_secs)).unwrap();
        relay.publish(&wrap, &community.relays).await.unwrap();
    }

    /// Publish an owner-grammar community-metadata edition (rename etc.), chained
    /// to the current relay head like a real owner client.
    async fn publish_community_meta(relay: &MemoryRelay, community: &CommunityV2, signer: &Keys, name: &str, version: u64) {
        publish_community_meta_at(relay, community, signer, name, version, 1_000).await;
    }

    /// As [`publish_community_meta`] with an explicit timestamp, for tests that need
    /// relay-side newest-first ordering (paging/eviction scenarios).
    async fn publish_community_meta_at(relay: &MemoryRelay, community: &CommunityV2, signer: &Keys, name: &str, version: u64, at_secs: u64) {
        let group = control::ControlPlane::of(&community).write_group().unwrap();
        let prev = head_hash_on_relay(relay, community, &community.id().0).await;
        let meta = control::CommunityMetadata { name: name.into(), ..Default::default() };
        let content = serde_json::to_string(&meta).unwrap();
        let cite = cite_on_relay(relay, community, signer).await;
        let rumor = control::build_edition_rumor(signer.public_key(), vsk::COMMUNITY_METADATA, &community.id().0, version, prev.as_ref(), &content, at_secs, cite.as_ref());
        let (wrap, _) = control::seal_control_edition(&rumor, &group, signer, Timestamp::from_secs(at_secs)).unwrap();
        relay.publish(&wrap, &community.relays).await.unwrap();
    }

    #[test]
    fn past_the_category_cap_the_lowest_ids_stand_however_they_arrive() {
        let owner = Keys::generate();
        let g = control::genesis(&owner, control::CommunityMetadata { name: "A".into(), ..Default::default() }, 1_000).unwrap();
        let cat = |name: &str| control::CategoryMetadata { name: name.into(), ..Default::default() };
        let ids: Vec<[u8; 32]> = (0..=crate::community::v2::community::MAX_CATEGORIES).map(|i| { let mut id = [0u8; 32]; id[..8].copy_from_slice(&(i as u64).to_be_bytes()); id }).collect();
        for order in [ids.clone(), ids.iter().rev().copied().collect()] {
            let mut held = CommunityV2::from_genesis(&g, "A", None, vec!["wss://r".into()], 0);
            for id in &order {
                apply_category_metadata(&mut held, *id, cat("c"));
            }
            let mut got: Vec<[u8; 32]> = held.categories.iter().map(|c| c.id).collect();
            got.sort();
            assert_eq!(got, ids[..crate::community::v2::community::MAX_CATEGORIES].to_vec(), "the {} lowest ids stand", crate::community::v2::community::MAX_CATEGORIES);
        }
    }

    #[test]
    fn metadata_apply_captures_undriven_fields_for_republish() {
        let owner = Keys::generate();
        let g = control::genesis(&owner, control::CommunityMetadata { name: "A".into(), ..Default::default() }, 1_000).unwrap();
        let mut held = CommunityV2::from_genesis(&g, "A", None, vec!["wss://r".into()], 0);
        let general = held.channels[0].id;

        // A foreign vsk-0 head carrying custom + unknown fields folds them in…
        let mut custom = serde_json::Map::new();
        custom.insert("accent".into(), serde_json::Value::from("#89f0b6"));
        let mut extra = serde_json::Map::new();
        extra.insert("vnd_flag".into(), serde_json::Value::Bool(true));
        let meta = control::CommunityMetadata { name: "A".into(), custom: Some(custom.clone()), extra: extra.clone(), ..Default::default() };
        assert!(apply_community_metadata(&mut held, meta), "gaining custom/extra is a change");
        assert_eq!(held.meta_custom, Some(custom.clone()));
        assert_eq!(held.meta_extra, extra);
        // …and the next local edit's base document republishes them verbatim.
        assert_eq!(held.metadata().custom, Some(custom));
        assert_eq!(held.metadata().extra, held.meta_extra);

        // Same contract for a vsk-2 channel head (voice included).
        let mut ch_custom = serde_json::Map::new();
        ch_custom.insert("slowmode".into(), serde_json::Value::from(30));
        let ch_meta = control::ChannelMetadata {
            name: "general".into(),
            private: false,
            voice: Some(true),
            deleted: None,
            custom: Some(ch_custom.clone()),
            extra: Default::default(),
        };
        assert!(apply_channel_metadata(&mut held, general, ch_meta), "gaining voice/custom is a change");
        let ch = held.channel(&general).unwrap();
        assert_eq!(ch.voice, Some(true));
        assert_eq!(ch.meta_custom, Some(ch_custom.clone()));
        let rename = { let mut d = ch.metadata(); d.name = "lounge".into(); d };
        assert_eq!(rename.voice, Some(true), "our rename edition carries the foreign voice flag");
        assert_eq!(rename.custom, Some(ch_custom));
    }

    #[test]
    fn community_metadata_apply_sets_and_clears_images() {
        let owner = Keys::generate();
        let g = control::genesis(&owner, control::CommunityMetadata { name: "A".into(), ..Default::default() }, 1_000).unwrap();
        let mut held = CommunityV2::from_genesis(&g, "A", None, vec!["wss://r".into()], 0);

        let icon = control::ImageRef {
            url: "https://blossom.example/i".into(),
            key: "k".into(),
            nonce: "n".into(),
            hash: "h".into(),
            extra: Default::default(),
        };
        let with_icon = control::CommunityMetadata { name: "A".into(), icon: Some(icon.clone()), ..Default::default() };
        assert!(apply_community_metadata(&mut held, with_icon), "gaining an icon is a change");
        assert_eq!(held.icon.as_ref(), Some(&icon));

        // An edition is the FULL document: a head without the icon removes it.
        let without = control::CommunityMetadata { name: "A".into(), ..Default::default() };
        assert!(apply_community_metadata(&mut held, without), "losing the icon is a change");
        assert_eq!(held.icon, None);
    }

    /// Publish a Role edition (vsk 1) signed by `signer`, chained to the current head.
    async fn publish_role(relay: &MemoryRelay, community: &CommunityV2, signer: &Keys, role: &Role, version: u64) {
        publish_role_at(relay, community, signer, role, version, 1_000).await
    }

    /// Page filler: a signed edition that occupies a slot in the pager's window and
    /// nothing else. It skips the head/citation relay scans `publish_role` does, which
    /// are linear in plane size and make a 500-edition test quadratic.
    async fn publish_filler_edition(relay: &MemoryRelay, community: &CommunityV2, signer: &Keys, role: &Role, version: u64, ts: u64) {
        let group = control::ControlPlane::of(&community).write_group().unwrap();
        let role_id = crate::simd::hex::hex_to_bytes_32_checked(&role.role_id).unwrap();
        let content = crate::community::v2::roles::role_content_json(role).unwrap();
        let rumor = control::build_edition_rumor(signer.public_key(), vsk::ROLE, &role_id, version, None, &content, ts, None);
        let (wrap, _) = control::seal_control_edition(&rumor, &group, signer, Timestamp::from_secs(ts)).unwrap();
        relay.publish(&wrap, &community.relays).await.unwrap();
    }

    /// `publish_role` with an explicit wall clock. Every other helper stamps 1_000, so a
    /// test needing more than one page of history must spread its editions out — a page
    /// that is entirely one second wide is a wall `until` cannot step past, and the
    /// pager correctly refuses rather than paging forever.
    async fn publish_role_at(relay: &MemoryRelay, community: &CommunityV2, signer: &Keys, role: &Role, version: u64, ts: u64) {
        let group = control::ControlPlane::of(&community).write_group().unwrap();
        let role_id = crate::simd::hex::hex_to_bytes_32_checked(&role.role_id).unwrap();
        let prev = head_hash_on_relay(relay, community, &role_id).await;
        let content = crate::community::v2::roles::role_content_json(role).unwrap();
        let cite = cite_on_relay(relay, community, signer).await;
        let rumor = control::build_edition_rumor(signer.public_key(), vsk::ROLE, &role_id, version, prev.as_ref(), &content, ts, cite.as_ref());
        let (wrap, _) = control::seal_control_edition(&rumor, &group, signer, Timestamp::from_secs(ts)).unwrap();
        relay.publish(&wrap, &community.relays).await.unwrap();
    }

    /// Hand-rotate a community view to `(new_root, epoch)`, minting the fresh
    /// split pair a real base rotation would (CORD-06 §3) — the control_root is
    /// the new root itself, which is fine for a test.
    fn rotate_view(c: &CommunityV2, new_root: [u8; 32], epoch: u64) -> CommunityV2 {
        let mut r = c.clone();
        r.community_root = new_root;
        r.root_epoch = Epoch(epoch);
        r.control_root = Some(new_root);
        r.control_pk = Some(crate::community::v2::derive::control_signer_group_key(&new_root, r.id(), Epoch(epoch)).pk());
        r
    }

    /// Publish a Grant edition (vsk 3) signed by `signer`, at grant_locator(cid, member).
    /// Like a compliant granter it delivers the staff write key inside the Grant
    /// (CORD-04 §3) whenever the community view holds one — the recipient's
    /// derive check drops it when it isn't owed, so attaching unconditionally
    /// keeps the helper simple while exercising the real delivery pipeline.
    async fn publish_grant(relay: &MemoryRelay, community: &CommunityV2, signer: &Keys, member: &PublicKey, role_ids: Vec<String>, version: u64) {
        let group = control::ControlPlane::of(&community).write_group().unwrap();
        let eid = crate::community::v2::derive::grant_locator(community.id(), &member.to_bytes());
        let prev = head_hash_on_relay(relay, community, &eid).await;
        let grant = MemberGrant { member: member.to_hex(), role_ids };
        let control_wrap = community.control_root.filter(|_| community.control_pk.is_some()).map(|cr| {
            let ck = nostr_sdk::prelude::nip44::v2::ConversationKey::derive(signer.secret_key(), member).unwrap();
            let payload = crate::community::cipher::encrypt_with_random_nonce(&ck, super::rekey::control_wrap_b64(community.root_epoch, &cr).as_bytes()).unwrap();
            crate::simd::base64::STANDARD.encode_to_string(&payload)
        });
        let content = crate::community::v2::roles::grant_content_json_with_wrap(&grant, control_wrap).unwrap();
        let cite = cite_on_relay(relay, community, signer).await;
        let rumor = control::build_edition_rumor(signer.public_key(), vsk::GRANT, &eid, version, prev.as_ref(), &content, 1_000, cite.as_ref());
        let (wrap, _) = control::seal_control_edition(&rumor, &group, signer, Timestamp::from_secs(1_000)).unwrap();
        relay.publish(&wrap, &community.relays).await.unwrap();
    }

    /// Publish a Banlist edition (vsk 4) signed by `signer`, at banlist_locator(cid).
    async fn publish_banlist(relay: &MemoryRelay, community: &CommunityV2, signer: &Keys, banned: &[String], version: u64) {
        let group = control::ControlPlane::of(&community).write_group().unwrap();
        let eid = crate::community::v2::derive::banlist_locator(community.id());
        let prev = head_hash_on_relay(relay, community, &eid).await;
        let content = crate::community::v2::roles::banlist_content_json(banned).unwrap();
        let cite = cite_on_relay(relay, community, signer).await;
        let rumor = control::build_edition_rumor(signer.public_key(), vsk::BANLIST, &eid, version, prev.as_ref(), &content, 1_000, cite.as_ref());
        let (wrap, _) = control::seal_control_edition(&rumor, &group, signer, Timestamp::from_secs(1_000)).unwrap();
        relay.publish(&wrap, &community.relays).await.unwrap();
    }

    fn admin_role(role_id: &str, perms: u64) -> Role {
        Role { role_id: role_id.into(), name: "Admin".into(), position: 1, permissions: Permissions(perms), scope: RoleScope::Server, color: 0, rank: None, display: false, mentionable: false, extra: Default::default() }
    }

    /// Hand-roll a LEGACY (pre-split) community exactly as a pre-0.4.2 build
    /// created one: the whole Control Plane keyed by the community_root
    /// derivation, no control pair anywhere. Publishes the two genesis-shaped
    /// editions at the LEGACY address, persists, and folds to seed floors.
    async fn create_legacy_community(relay: &MemoryRelay, owner: &Keys, name: &str, relays: Vec<String>) -> CommunityV2 {
        let identity = control::CommunityIdentity::mint(&owner.public_key());
        let root = crate::community::random_32();
        let group = control_group_key(&root, &identity.community_id, Epoch(0));
        let meta = control::CommunityMetadata { name: name.into(), relays: relays.clone(), ..Default::default() };
        let meta_rumor = control::build_edition_rumor(owner.public_key(), vsk::COMMUNITY_METADATA, &identity.community_id.0, 1, None, &serde_json::to_string(&meta).unwrap(), 1_000, None);
        let ch_id = ChannelId(crate::community::random_32());
        let ch = control::ChannelMetadata { name: "general".into(), private: false, ..Default::default() };
        let ch_rumor = control::build_edition_rumor(owner.public_key(), vsk::CHANNEL_METADATA, &ch_id.0, 1, None, &serde_json::to_string(&ch).unwrap(), 1_000, None);
        for r in [&meta_rumor, &ch_rumor] {
            let (w, _) = control::seal_control_edition(r, &group, owner, Timestamp::from_secs(1_000)).unwrap();
            relay.publish(&w, &relays).await.unwrap();
        }
        let community = CommunityV2 {
            identity,
            community_root: root,
            root_epoch: Epoch(0),
            control_pk: None,
            control_root: None,
            name: name.into(),
            description: None,
            icon: None,
            banner: None,
            meta_custom: None,
            meta_extra: Default::default(),
            relays,
            channels: vec![ChannelV2 { id: ch_id, name: "general".into(), private: false, key: None, epoch: Epoch(0), voice: None, meta_custom: None, meta_extra: Default::default(), writers: None, sealed: None }],
            categories: Vec::new(),
            dissolved: false,
            created_at_ms: 1_000_000,
        };
        crate::db::community::save_community_v2(&community).unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let _ = crate::db::community::store_epoch_key(&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX, 0, &root);
        let _ = follow_control(relay, &community).await;
        crate::db::community::load_community_v2(community.id()).unwrap().unwrap()
    }

    #[tokio::test]
    async fn a_refounding_mints_the_split_and_delivers_the_pair_by_staffness() {
        // CORD-06 §1/§3 end to end: the rotation mints a fresh control pair, a
        // STAFF recipient's blob carries the secret (136), a plain member's only
        // the address (104), the compaction publishes ONLY at the new split
        // address, and each follower adopts exactly what its blob delivered.
        let (bed, owner, admin) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "SplitRefound", bed.relays.clone(), None).await.unwrap();
        assert!(community.control_pk.is_some() && community.control_root.is_some(), "genesis mints the split");

        // A staff admin (granted; the Grant delivers the wrap) and a plain
        // member (Guestbook Join only — a recipient with no rank).
        let rid = "d1".repeat(32);
        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::ADMIN_ALL), 1).await;
        publish_grant(&bed.relay, &community, &owner.keys, &admin.keys.public_key(), vec![rid], 1).await;
        let plain = Keys::generate();
        let gb = super::super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
        let join = guestbook::build_join_rumor(plain.public_key(), None, 1_000);
        let (w, _) = guestbook::seal_guestbook_rumor(&join, &gb, &plain, Timestamp::from_secs(1_000)).unwrap();
        bed.relay.publish(&w, &community.relays).await.unwrap();

        // The admin joins and folds — adopting the write key from their Grant.
        let bundle_json = serde_json::to_string(&bundle_of(&community, BundleAudience::Link, None, None, None)).unwrap();
        bed.swap_to(&admin);
        let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
        assert_eq!(joined.control_pk, community.control_pk, "the bundle handed over the address");
        assert_eq!(joined.control_root, None, "a bundle never carries the secret");
        let _ = follow_control(&bed.relay, &joined).await;
        let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
        assert_eq!(joined.control_root, community.control_root, "the Grant's control_wrap delivered the secret");

        // The owner refounds: a FRESH pair beside the new root.
        bed.swap_to(&owner);
        let refounded = refound_community(&bed.relay, &community, &[]).await.unwrap();
        assert_eq!(refounded.root_epoch, Epoch(1));
        assert!(refounded.control_pk.is_some() && refounded.control_root.is_some());
        assert_ne!(refounded.control_pk, community.control_pk, "the pair rolls with the root");

        // Blob forms by staff-ness: the admin's carries the secret, the plain
        // member's only the pk (CORD-06 §1).
        let base_group = base_rekey_group_key(&community.community_root, community.id(), Epoch(1));
        let chunks = fetch_rekey_chunks(&bed.relay, &community, &base_group).await.unwrap();
        let rotation = &rekey::collect_rotations(&chunks)[0];
        async fn open_as(rotation: &rekey::Rotation, community_id: &crate::community::CommunityId, keys: &Keys) -> rekey::BaseKeyDelivery {
            let blob = rekey::find_my_blob(&rotation.blobs, &rotation.rotator.to_bytes(), &keys.public_key().to_bytes(), rotation.scope, rotation.new_epoch).expect("a blob for every recipient");
            let signer = crate::signer::ActiveSigner::Keys(keys.clone());
            rekey::open_base_blob(&signer, &rotation.rotator, community_id, Epoch(1), blob).await.unwrap()
        }
        let admin_delivery = open_as(rotation, community.id(), &admin.keys).await;
        assert_eq!(admin_delivery.control_root, refounded.control_root, "staff blob = 136, secret included");
        let plain_delivery = open_as(rotation, community.id(), &plain).await;
        assert_eq!(plain_delivery.control_pk.map(|p| PublicKey::from_slice(p.as_slice()).unwrap()), refounded.control_pk);
        assert_eq!(plain_delivery.control_root, None, "member blob = 104, never the secret");

        // The compaction lives ONLY at the new split address — never mirrored to
        // the new epoch's legacy-derived address (CORD-06 §3).
        let legacy_new = control_group_key(&refounded.community_root, community.id(), Epoch(1));
        let q = |pk: String| Query { kinds: vec![stream::KIND_WRAP], authors: vec![pk], limit: Some(50), ..Default::default() };
        assert!(bed.relay.fetch(&q(legacy_new.pk_hex()), &community.relays).await.unwrap().is_empty(), "no legacy mirror");
        assert!(!bed.relay.fetch(&q(refounded.control_pk.unwrap().to_hex()), &community.relays).await.unwrap().is_empty(), "the compaction rides the split address");

        // The admin's follow adopts the whole pair from their 136-byte blob.
        bed.swap_to(&admin);
        let follow = follow_rekeys(&bed.relay, &joined, &crate::db::current_session()).await.unwrap();
        let adopted = follow.updated.expect("the admin adopts the rotation");
        assert_eq!(adopted.root_epoch, Epoch(1));
        assert_eq!(adopted.control_pk, refounded.control_pk);
        assert_eq!(adopted.control_root, refounded.control_root, "staff crossing a rotation get the new secret in the blob");
    }

    #[tokio::test]
    async fn a_rescue_lets_a_stranded_member_walk_every_missed_hop() {
        // A member forgotten by two consecutive rotations is wedged at epoch 0: their
        // client derives base_rekey_group(root_0, cid, 1), finds no blob, and can never
        // even compute where epoch 2 lives. The rescue publishes the blobs that should
        // have existed, correlated into the ORIGINAL rotations — then the walk just works.
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Stranded", vec!["wss://r".into()], None).await.unwrap();
        let stranded = Keys::generate();

        // Two rotations that never vend to `stranded` (they are in no fold: never
        // joined the wire, never posted, not in the local store).
        let e1 = refound_community(&relay, &community, &[]).await.unwrap();
        let e2 = refound_community(&relay, &e1, &[]).await.unwrap();
        assert_eq!(e2.root_epoch, Epoch(2));

        // Wedged: no blob for them at the only plane they can derive.
        let hop1 = base_rekey_group_key(&community.community_root, community.id(), Epoch(1));
        let chunks = fetch_rekey_chunks(&relay, &community, &hop1).await.unwrap();
        let r1 = &rekey::collect_rotations(&chunks)[0];
        assert!(
            rekey::find_my_blob(&r1.blobs, &r1.rotator.to_bytes(), &stranded.public_key().to_bytes(), r1.scope, r1.new_epoch).is_none(),
            "genuinely stranded before the rescue"
        );

        let report = rescue_stranded_members(&relay, &e2, &[stranded.public_key()]).await.unwrap();
        assert_eq!(report.hops, 2, "one catch-up per missed hop");
        assert_eq!(report.hops_skipped, 0);

        // Walk exactly as a client would: derive each hop's plane from the PREVIOUS
        // root, find our blob inside the correlated rotation, open, adopt, repeat.
        let signer = crate::signer::ActiveSigner::Keys(stranded.clone());
        let mut held_root = community.community_root;
        for e in 1..=2u64 {
            let group = base_rekey_group_key(&held_root, community.id(), Epoch(e));
            let chunks = fetch_rekey_chunks(&relay, &community, &group).await.unwrap();
            let rotations = rekey::collect_rotations(&chunks);
            let rot = rotations
                .iter()
                .find(|r| {
                    rekey::find_my_blob(&r.blobs, &r.rotator.to_bytes(), &stranded.public_key().to_bytes(), r.scope, r.new_epoch).is_some()
                })
                .expect("a rotation now carries our blob");
            let blob = rekey::find_my_blob(&rot.blobs, &rot.rotator.to_bytes(), &stranded.public_key().to_bytes(), rot.scope, rot.new_epoch).unwrap();
            let delivery = rekey::open_base_blob(&signer, &rot.rotator, community.id(), Epoch(e), blob).await.unwrap();
            held_root = delivery.new_root;
        }
        assert_eq!(held_root, e2.community_root, "the walk ends on the live root");

        // Merge safety on DEPLOYED clients: the catch-up extended the original chunk
        // set (disjoint indices), so everything folds as ONE complete rotation and no
        // original recipient's blob was displaced — a slot collision would fold as
        // their removal.
        let chunks = fetch_rekey_chunks(&relay, &community, &hop1).await.unwrap();
        let rotations = rekey::collect_rotations(&chunks);
        assert_eq!(rotations.len(), 1, "catch-up merged into the original rotation, not a fork");
        assert!(rotations[0].is_complete(), "the extended set still reads complete");
        let owner_pk = e2.owner().unwrap();
        assert!(
            rekey::find_my_blob(&rotations[0].blobs, &rotations[0].rotator.to_bytes(), &owner_pk.to_bytes(), rotations[0].scope, rotations[0].new_epoch).is_some(),
            "the original recipient's blob survived the extension"
        );

        // And the outside world counts them again: the snapshot addendum seeded them
        // onto the current epoch's guestbook plane.
        let wire = wire_guestbook_members(&relay, &e2).await.unwrap();
        assert!(wire.contains(&stranded.public_key()), "the invite page's fold now includes them");
    }

    #[tokio::test]
    async fn a_non_owner_refounders_snapshot_seeds_the_roster() {
        // CORD-02 §5: a snapshot is honored "only from the npub whose Refounding
        // minted that epoch". Vector read that as the OWNER always, so a moderation
        // bot's containment rolled the epoch and vended the keys while its survivor
        // list was thrown away — every client then folded its own accumulated Joins,
        // keeping members the containment had cut and disagreeing with each other.
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "MintedBy", vec!["wss://r".into()], None).await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let owner = community.owner().unwrap();

        // An admin (NOT the owner) refounded to epoch 1 — this device verified and
        // adopted that rotation, so it knows who minted it.
        let admin = Keys::generate();
        let mut at_epoch_1 = community.clone();
        at_epoch_1.root_epoch = Epoch(1);
        record_epoch_minter(&cid_hex, 1, &admin.public_key().to_hex());

        // Someone the containment cut: joined at the old epoch, never banned, and
        // absent from the survivor list the refounder published.
        let cut = Keys::generate().public_key();
        let join = guestbook::GuestbookEvent {
            epoch: None, observed_at: None, rumor_id: [11u8; 32],
            entry: guestbook::GuestbookEntry::Join { member: cut, invited_by: None, at_ms: 1_000 },
        };
        let snapshot = |by: &Keys, id: u8| guestbook::GuestbookEvent {
            epoch: Some(1), observed_at: None, rumor_id: [id; 32],
            entry: guestbook::GuestbookEntry::Snapshot {
                refounder: by.public_key(),
                members: vec![owner],           // survivors: the cut member is NOT here
                snapshot_id: [id; 32],
                chunk: (1, 1),
                at_ms: 5_000,                   // newer than the Join it supersedes
            },
        };

        // A stranger's snapshot must change nothing — authority is the minter, not
        // whoever manages to write a 3312.
        let stranger = Keys::generate();
        crate::db::community::set_guestbook(&cid_hex, &[join.clone(), snapshot(&stranger, 0x51)], 6).unwrap();
        assert!(
            stored_memberlist(&at_epoch_1).unwrap().contains(&cut),
            "a snapshot from an npub that minted nothing seeds no roster"
        );

        // The actual refounder's snapshot IS the guest list.
        crate::db::community::set_guestbook(&cid_hex, &[join, snapshot(&admin, 0x52)], 6).unwrap();
        let members = stored_memberlist(&at_epoch_1).unwrap();
        assert!(
            !members.contains(&cut),
            "the refounder's survivor list is adopted, so a cut member stops being one"
        );
        assert!(members.contains(&owner), "a survivor the snapshot names stays");
    }

    #[tokio::test]
    async fn a_device_that_missed_the_rotation_takes_the_earliest_snapshot_from_someone_who_may_rotate() {
        use crate::community::roles::{CommunityRoles, MemberGrant, Permissions, Role, RoleScope};
        // A joiner holds only the epoch it was invited into, so it never saw who minted it.
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Joiner", vec!["wss://r".into()], None).await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let owner = community.owner().unwrap();
        let mut at_epoch_1 = community.clone();
        at_epoch_1.root_epoch = Epoch(1);

        let bot = Keys::generate();
        let late_mod = Keys::generate();
        let stranger = Keys::generate();
        let role = |id: &str, bits: u64| Role { role_id: id.into(), name: id.into(), position: 1, permissions: Permissions(bits), scope: RoleScope::Server, color: 0, rank: None, display: false, mentionable: false, extra: Default::default() };
        let roster = |granted: Vec<String>| CommunityRoles {
            roles: vec![role("guard", Permissions::BAN)],
            grants: granted.into_iter().map(|member| MemberGrant { member, role_ids: vec!["guard".into()] }).collect(),
            everyone: None,
            overwrites: Vec::new(), syncs: Default::default(), legacy_channels: None, creators: Default::default(),
        };

        let survivor = Keys::generate().public_key();
        let cut = Keys::generate().public_key();
        let join = |member: PublicKey, id: u8| guestbook::GuestbookEvent {
            epoch: None, observed_at: None, rumor_id: [id; 32],
            entry: guestbook::GuestbookEntry::Join { member, invited_by: None, at_ms: 1_000 },
        };
        let snapshot = |by: &Keys, members: Vec<PublicKey>, at_ms: u64, id: u8| guestbook::GuestbookEvent {
            epoch: Some(1), observed_at: None, rumor_id: [id; 32],
            entry: guestbook::GuestbookEntry::Snapshot { refounder: by.public_key(), members, snapshot_id: [id; 32], chunk: (1, 1), at_ms },
        };
        let events = vec![
            join(cut, 1),
            snapshot(&stranger, vec![cut], 4_000, 0x61),
            snapshot(&bot, vec![owner, survivor], 5_000, 0x62),
            snapshot(&late_mod, vec![owner, cut], 9_000, 0x63),
        ];
        crate::db::community::set_guestbook(&cid_hex, &events, 10).unwrap();

        // Nobody but the owner may rotate: no snapshot here is theirs, so none seeds anything.
        crate::db::community::set_community_roles(&cid_hex, &roster(vec![]), 1).unwrap();
        let members = stored_memberlist(&at_epoch_1).unwrap();
        assert!(!members.contains(&survivor) && members.contains(&cut), "without the right to rotate, a snapshot is noise");

        // The bot and a later moderator both hold BAN: the bot's came first, so it is the Refounding's.
        crate::db::community::set_community_roles(&cid_hex, &roster(vec![bot.public_key().to_hex(), late_mod.public_key().to_hex()]), 2).unwrap();
        let members = stored_memberlist(&at_epoch_1).unwrap();
        assert!(members.contains(&survivor), "the refounder's survivors are members without re-posting");
        assert!(!members.contains(&cut), "and whoever it cut is not, whatever a later snapshot says");

        // A device that saw the rotation keeps the minter it verified.
        record_epoch_minter(&cid_hex, 1, &late_mod.public_key().to_hex());
        assert!(stored_memberlist(&at_epoch_1).unwrap().contains(&cut), "a verified minter outranks the inference");
    }

    /// A moderation report quotes what was said, so it may only reach someone who
    /// could have read the room it was said in. Community power is NOT that
    /// question — BAN says what a moderator may do to people, never which rooms
    /// they may see — and a bot holding every key would otherwise forward a
    /// private channel's contents to whoever holds the ban bit.
    #[tokio::test]
    async fn reading_a_private_channel_needs_its_own_role_not_community_power() {
        let (bed, owner, mod_without_access) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Rooms", bed.relays.clone(), None).await.unwrap();
        let public = community.channels[0].id;
        let private = create_private_channel(&bed.relay, &community, "back-room").await.unwrap();
        let community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);

        use nostr_sdk::prelude::ToBech32;
        let them = mod_without_access.keys.public_key();
        let them_npub = them.to_bech32().unwrap();

        // Give them the fullest COMMUNITY powers there are. It must buy nothing
        // in a room they were never admitted to.
        let admin_rid = crate::simd::hex::bytes_to_hex_32(&[0xa7; 32]);
        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&admin_rid, Permissions::ADMIN_ALL), 1).await;
        publish_grant(&bed.relay, &community, &owner.keys, &them, vec![admin_rid], 1).await;
        follow_control(&bed.relay, &community).await.unwrap();
        assert!(
            crate::VectorCore.member_has_permission(&cid_hex, &them_npub, Permissions::BAN).unwrap(),
            "they really do hold BAN"
        );

        let pub_hex = crate::simd::hex::bytes_to_hex_32(&public.0);
        let priv_hex = crate::simd::hex::bytes_to_hex_32(&private.0);
        assert!(
            crate::VectorCore.member_can_read_channel(&cid_hex, &pub_hex, &them_npub).unwrap(),
            "a public channel is the community's"
        );
        assert!(
            !crate::VectorCore.member_can_read_channel(&cid_hex, &priv_hex, &them_npub).unwrap(),
            "BAN is not a key: community power must never open a private room"
        );

        // The access role is what opens it — and it carries no powers at all.
        grant_channel_access(&bed.relay, &community, &private, &them).await.unwrap();
        let community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let _ = follow_control(&bed.relay, &community).await;
        assert!(
            crate::VectorCore.member_can_read_channel(&cid_hex, &priv_hex, &them_npub).unwrap(),
            "the channel-scoped grant is what admits them"
        );
    }

    /// An empty retain means "cut nobody", never "keep nobody".
    ///
    /// The console's "Rotate keys" sends an empty retain when nothing is unticked.
    /// `members_to_remove` reads that correctly and removes nobody — but the same
    /// empty list also became an ALLOW-LIST, and an allow-list keeps only the
    /// rotating device and the owner. So a plain rotation vended to two people and
    /// stranded everyone else at the previous epoch, permanently, presenting as
    /// members vanishing some time later nowhere near the button that did it.
    ///
    /// The two paths are pinned here against each other, because they take the same
    /// empty list and must disagree about what it means.
    #[tokio::test]
    async fn an_empty_retain_cuts_nobody_rather_than_keeping_nobody() {
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "EmptyRetain", bed.relays.clone(), None).await.unwrap();

        // A third party who is neither the rotator nor the owner — the only kind of
        // member an empty allow-list silently drops.
        let bundle = serde_json::to_string(&bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None)).unwrap();
        bed.swap_to(&member);
        accept_parked_invite(&bed.relay, &bundle, None).await.unwrap();
        bed.swap_to(&owner);
        assert!(memberlist(&bed.relay, &community).await.unwrap().contains(&member.keys.public_key()));

        // The plain reading: cut nobody, vend to everybody. This is what the button
        // must reach. (The allow-list reading of the same empty list is covered by
        // `a_rotation_that_would_strand_staff_refuses_to_publish`.)
        refound_community(&bed.relay, &community, &[]).await.expect("cutting nobody must succeed");
        assert!(
            vended_to(&bed, &community, &member.keys).await,
            "a plain rotation must vend to a member who is neither the rotator nor the owner"
        );
    }

    /// The console's rotate button reaches the "cut nobody" path, not the allow-list
    /// one. Pinned from source: the two are one `if` apart and read the same empty
    /// list in opposite directions, which is exactly how this shipped.
    #[test]
    fn an_empty_retain_does_not_become_an_allow_list() {
        let src = include_str!("../../lib.rs");
        let at = src.find("pub async fn purge_and_refound").expect("purge_and_refound");
        let body = &src[at..at + 3000];
        let guard = body.find("if keep.is_empty()").expect("an empty retain must branch away from the allow-list");
        let retaining = body.find("refound_community_retaining").expect("the allow-list call");
        assert!(guard < retaining, "the branch has to come BEFORE the allow-list call");
    }

    /// If the recipients would strand a granted member, publish NOTHING.
    ///
    /// A member missed at a hop is stranded there permanently, and every other
    /// client goes on reading them as staff — silent, irreversible without the
    /// rescue primitive, and only noticed because a human saw the member list
    /// shrink. So the rotation refuses instead, exactly as the entity carry-forward
    /// already refuses a floored head it cannot serve.
    #[tokio::test]
    async fn a_rotation_that_would_strand_staff_refuses_to_publish() {
        let (bed, owner, staffer) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "NoSilentSever", bed.relays.clone(), None).await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let them = staffer.keys.public_key();

        let rid = crate::simd::hex::bytes_to_hex_32(&[0xb6; 32]);
        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::ADMIN_ALL), 1).await;
        publish_grant(&bed.relay, &community, &owner.keys, &them, vec![rid], 1).await;
        follow_control(&bed.relay, &community).await.unwrap();

        // An operator purge whose allow-list forgets an admin: the recipient set
        // ends up without somebody the roster still grants a role to.
        let err = refound_community_retaining(&bed.relay, &community, &[], &[owner.keys.public_key()])
            .await
            .expect_err("must refuse rather than strand staff");
        assert!(
            err.contains("stranded"),
            "the refusal has to say what it protected, got: {err}"
        );

        // And nothing was published: the epoch did not move.
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        assert_eq!(held.root_epoch, community.root_epoch, "no state published");
        assert!(!vended_to(&bed, &community, &staffer.keys).await, "no half-rotation left on the plane");
        let _ = cid_hex;
    }

    /// The backstop protects a SILENT granted member. An ACTIVE one is the gap.
    ///
    /// `fold_members` seeds granted members with `observed.entry(pk).or_insert(0)`,
    /// and ts 0 is what dodges `stale_pre_refound`. A staffer who actually talks
    /// already sits in `observed` with a REAL timestamp, so `or_insert` leaves it
    /// alone — and if some earlier refounding's snapshot omitted them while their
    /// last word predates its cut, they are suppressed despite holding a grant.
    ///
    /// That is Sentire, 2026-08-26: admin, constantly posting, vended no key.
    #[tokio::test]
    async fn a_granted_member_who_talks_is_not_dropped_by_an_old_snapshot() {
        let (bed, owner, staffer) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "TalkingAdmin", bed.relays.clone(), None).await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let them = staffer.keys.public_key();

        let rid = crate::simd::hex::bytes_to_hex_32(&[0xb5; 32]);
        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::ADMIN_ALL), 1).await;
        publish_grant(&bed.relay, &community, &owner.keys, &them, vec![rid], 1).await;
        follow_control(&bed.relay, &community).await.unwrap();

        // They joined and spoke — so `observed` holds a REAL timestamp for them,
        // not the 0 the grant backstop would have inserted.
        let spoke_at = 5_000u64;
        let join = guestbook::GuestbookEvent {
            epoch: Some(community.root_epoch.0), observed_at: None, rumor_id: [0x31; 32],
            entry: guestbook::GuestbookEntry::Join { member: them, invited_by: None, at_ms: spoke_at },
        };
        // A PRIOR refounding whose snapshot omitted them, cutting after they spoke.
        let snapshot = guestbook::GuestbookEvent {
            epoch: Some(community.root_epoch.0), observed_at: None, rumor_id: [0x32; 32],
            entry: guestbook::GuestbookEntry::Snapshot {
                refounder: owner.keys.public_key(),
                members: vec![owner.keys.public_key()],   // them: omitted
                snapshot_id: [0x32; 32],
                chunk: (1, 1),
                at_ms: spoke_at + 1_000,
            },
        };
        crate::db::community::set_guestbook(&cid_hex, &[join, snapshot], 9).unwrap();

        assert!(
            stored_memberlist(&community).unwrap().contains(&them),
            "a grant is proof of membership — an old snapshot must not shed the staff it forgot"
        );

        let _ = refound_community(&bed.relay, &community, &[]).await.unwrap();
        assert!(
            vended_to(&bed, &community, &staffer.keys).await,
            "and the rotation must vend to them, or they are stranded holding a grant"
        );
    }

    /// A GRANT is proof of membership, so a rotation must vend to it.
    ///
    /// Sentire's shape, 2026-08-26: an admin whose Join had been superseded by an
    /// earlier refounding's snapshot fell out of BOTH folds the recipient union is
    /// built from, held a valid admin grant the whole time, and was vended no key.
    /// It could then only derive `held + 1`, so it was stranded permanently while
    /// still appearing to be staff to everyone else.
    ///
    /// `fold_members` already treats a grant as consensus-complete proof — "this is
    /// what keeps a Refounding from severing a lurking admin". The rotation has to
    /// agree with it.
    #[tokio::test]
    async fn a_rotation_vends_to_a_granted_member_the_folds_forgot() {
        let (bed, owner, staffer) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "LurkingAdmin", bed.relays.clone(), None).await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let them = staffer.keys.public_key();

        // Staff by GRANT, with no Join anywhere — the lurking admin the backstop
        // exists for. Never posted, never announced.
        let rid = crate::simd::hex::bytes_to_hex_32(&[0xb4; 32]);
        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::ADMIN_ALL), 1).await;
        publish_grant(&bed.relay, &community, &owner.keys, &them, vec![rid], 1).await;
        follow_control(&bed.relay, &community).await.unwrap();
        assert!(
            crate::db::community::get_community_roles(&cid_hex).unwrap().is_admin(&them.to_hex()),
            "they hold the grant"
        );

        // An empty guestbook is the whole point: neither fold can see them.
        crate::db::community::set_guestbook(&cid_hex, &[], 1).unwrap();

        let _rotated = refound_community(&bed.relay, &community, &[]).await.unwrap();

        // The blob is the answer. A member absent from the rotation's recipients is
        // stranded at the previous epoch for good — they can only ever derive
        // `held + 1`, so no later rotation reaches them.
        assert!(
            vended_to(&bed, &community, &staffer.keys).await,
            "a rotation removing nobody must vend to a granted member, or it severs its own staff"
        );
    }

    /// "Rotate keys" with nobody unticked must remove NOBODY — and must vend to
    /// everyone, not merely leave them on a list. A rotation that forgets a
    /// member strands them at the previous epoch permanently: they can only
    /// derive `held + 1`, so no later rotation can ever reach them.
    #[tokio::test]
    async fn a_rotation_that_removes_nobody_vends_to_everybody() {
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "KeepAll", bed.relays.clone(), None).await.unwrap();

        // A second member joins for real, via the invite path.
        let bundle = serde_json::to_string(&bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None)).unwrap();
        bed.swap_to(&member);
        accept_parked_invite(&bed.relay, &bundle, None).await.unwrap();
        bed.swap_to(&owner);
        let before = memberlist(&bed.relay, &community).await.unwrap();
        assert!(before.contains(&member.keys.public_key()), "present before the rotation");

        // Rotate keeping everyone — the empty `removed` the console sends when
        // nothing is unticked.
        let rotated = refound_community(&bed.relay, &community, &[]).await.unwrap();
        assert_eq!(rotated.root_epoch.0, community.root_epoch.0 + 1, "the epoch rolled");

        let after = memberlist(&bed.relay, &community).await.unwrap();
        assert!(
            after.contains(&member.keys.public_key()),
            "a rotation removing nobody must keep everybody: {before:?} -> {after:?}"
        );

        // And the member must actually be able to WALK to the new epoch, which is
        // the half a memberlist cannot show.
        bed.swap_to(&member);
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let follow = follow_rekeys(&bed.relay, &held, &crate::db::current_session()).await.unwrap();
        assert!(!follow.self_removed, "they were not excluded");
        let now = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        assert_eq!(now.root_epoch.0, rotated.root_epoch.0, "they adopted the new epoch — a blob was vended to them");
    }

    /// A revocation has to reach the NETWORK, not just the revoker.
    ///
    /// Every other client decides who is staff by folding the control plane, so
    /// an owner whose demotion never published is the only person who believes
    /// it happened — and the demoted admin keeps every power everywhere else,
    /// which is the worst possible direction for this to fail in.
    #[tokio::test]
    async fn revoking_admin_publishes_where_everyone_else_reads_it() {
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Demotion", bed.relays.clone(), None).await.unwrap();
        let them = member.keys.public_key();
        let them_hex = them.to_hex();

        grant_admin(&bed.relay, &community, &them).await.unwrap();
        let view = fetch_authority(&bed.relay, &community).await;
        assert!(view.roles.is_admin(&them_hex), "granted, and readable from the plane");

        revoke_admin(&bed.relay, &community, &them).await.unwrap();

        // The plane, NOT the local row: this is the copy every peer folds.
        let view = fetch_authority(&bed.relay, &community).await;
        assert!(
            !view.roles.is_admin(&them_hex),
            "the demotion must be on the plane, or only the owner believes it"
        );

        // And the same answer through the public API a bot or client would ask.
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        use nostr_sdk::prelude::ToBech32;
        assert!(
            !crate::VectorCore
                .member_has_permission(&cid_hex, &them.to_bech32().unwrap(), crate::community::roles::Permissions::BAN)
                .unwrap(),
            "a demoted admin holds no powers"
        );
    }

    /// Authority must fail CLOSED. A bot gating a chat command on this is the
    /// only thing standing between "a moderator asked" and "anyone in the room
    /// asked", so an unfolded, empty or unreadable roster has to authorise
    /// nobody — `has_permission` finds no grant and denies. The owner is the one
    /// exception, and is answered without consulting the roster at all.
    #[tokio::test]
    async fn permission_is_refused_to_everyone_the_roster_does_not_name() {
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Authority", vec!["wss://r".into()], None).await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        use nostr_sdk::prelude::ToBech32;
        let owner_npub = community.owner().unwrap().to_bech32().unwrap();
        let stranger = Keys::generate().public_key().to_bech32().unwrap();

        use crate::community::roles::Permissions;
        for p in [Permissions::KICK, Permissions::BAN, Permissions::MANAGE_ROLES] {
            assert!(
                !crate::VectorCore.member_has_permission(&cid_hex, &stranger, p).unwrap(),
                "an npub the roster never granted anything holds nothing"
            );
            assert!(
                crate::VectorCore.member_has_permission(&cid_hex, &owner_npub, p).unwrap(),
                "the owner is supreme without a grant to cite"
            );
        }

        // A banned npub holds nothing, whatever a stale grant still says.
        crate::db::community::set_community_banlist(&cid_hex, &[community.owner().unwrap().to_hex()], 1).unwrap();
        let banned_owner_is_still_owner =
            crate::VectorCore.member_has_permission(&cid_hex, &owner_npub, Permissions::BAN).unwrap();
        assert!(banned_owner_is_still_owner, "the owner cannot be locked out of their own community");

        // And a malformed npub is an error, never a silent grant.
        assert!(crate::VectorCore.member_has_permission(&cid_hex, "not-an-npub", Permissions::BAN).is_err());
    }

    #[tokio::test]
    async fn stored_members_fold_observed_authors_grants_and_bans() {
        use nostr_sdk::prelude::ToBech32;
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Observed", vec!["wss://r".into()], None).await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let channel_hex = crate::simd::hex::bytes_to_hex_32(&community.channels[0].id.0);
        let [talker, banned, staff, revoked] = std::array::from_fn(|_| Keys::generate().public_key());

        for (i, pk) in [talker, banned, revoked].iter().enumerate() {
            let mut m = crate::types::Message::default();
            m.id = format!("{:02x}", i + 1).repeat(32);
            m.npub = Some(pk.to_bech32().unwrap());
            m.at = 1_000_000;
            crate::db::events::save_message(&channel_hex, &m).await.unwrap();
        }
        crate::db::community::set_community_banlist(&cid_hex, &[banned.to_hex()], 1).unwrap();
        let roles = crate::community::roles::CommunityRoles {
            roles: Vec::new(),
            grants: vec![
                MemberGrant { member: staff.to_hex(), role_ids: vec!["ab".repeat(32)] },
                MemberGrant { member: revoked.to_hex(), role_ids: Vec::new() },
            ],
            everyone: None,
            overwrites: Vec::new(), syncs: Default::default(), legacy_channels: None, creators: Default::default(),
        };
        crate::db::community::set_community_roles(&cid_hex, &roles, 1).unwrap();

        // A reaction later than their text, ahead of it in index order: the newest of the two counts.
        let chat = crate::db::id_cache::get_chat_id_by_identifier(&channel_hex).unwrap();
        crate::db::get_write_connection_guard_static()
            .unwrap()
            .execute(
                "INSERT INTO events (id, kind, chat_id, content, created_at, received_at, npub) VALUES (?1, 7, ?2, '', 2000000, 2000000, ?3)",
                rusqlite::params!["ee".repeat(32), chat, talker.to_bech32().unwrap()],
            )
            .unwrap();
        let activity: std::collections::HashMap<String, u64> =
            crate::db::community::community_member_activity(&cid_hex).unwrap().into_iter().collect();
        let at = |pk: &PublicKey| activity.get(&pk.to_bech32().unwrap()).copied();
        assert_eq!(at(&talker), Some(2_000_000), "an author keeps the newest time they spoke");
        assert!(at(&revoked).is_some_and(|t| t < 1_000_000_000), "an empty grant is not re-asserted");
        assert!(at(&staff).is_some(), "a grant holder counts without a word");
        assert_eq!(at(&banned), None);

        let members = stored_memberlist(&community).unwrap();
        for pk in [community.owner().unwrap(), talker, staff, revoked] {
            assert!(members.contains(&pk));
        }
        assert!(!members.contains(&banned));
        assert!(crate::db::community::community_member_activity(&"cd".repeat(32)).unwrap().is_empty());
    }

    #[tokio::test]
    async fn a_refound_keeps_a_quiet_member_the_network_fold_forgot() {
        // The network fold only sees the current guestbook + the recent posting window,
        // so a quiet member whose Join lives on a buried epoch vanishes from it — and a
        // rotation that trusts the fold alone silently sheds them. Being forgotten must
        // not be a removal: only the explicit `removed` list is.
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "QuietOnes", vec!["wss://r".into()], None).await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);

        // A member the LOCAL store remembers (an old synced Join) but the WIRE has no
        // trace of: never posted, Join never published on the current plane.
        let quiet = Keys::generate().public_key();
        let ev = guestbook::GuestbookEvent { epoch: None, observed_at: None,
            rumor_id: [7u8; 32],
            entry: guestbook::GuestbookEntry::Join { member: quiet, invited_by: None, at_ms: 1_000 },
        };
        crate::db::community::set_guestbook(&cid_hex, std::slice::from_ref(&ev), 1).unwrap();
        assert!(stored_memberlist(&community).unwrap().contains(&quiet), "locally known");
        assert!(!memberlist(&relay, &community).await.unwrap().contains(&quiet), "network fold has forgotten them");

        let rotated = refound_community(&relay, &community, &[]).await.unwrap();

        // They made the new epoch's snapshot — the wire now carries them, so an outside
        // reader counts them and their client has a rekey blob to walk forward on.
        let wire = wire_guestbook_members(&relay, &rotated).await.unwrap();
        assert!(wire.contains(&quiet), "the quiet member survived the rotation onto the wire");

        // The explicit removed list still removes, union or no union.
        let rotated2 = refound_community(&relay, &rotated, &[quiet]).await.unwrap();
        let wire2 = wire_guestbook_members(&relay, &rotated2).await.unwrap();
        assert!(!wire2.contains(&quiet), "an explicit removal is honoured");
    }

    #[tokio::test]
    async fn revoking_a_husk_prunes_the_local_row_instead_of_erroring_forever() {
        // The list is per-creator and cross-device: another device (or Armada) can
        // retire a link this one still holds a row for. That row carries no signer_sk,
        // so no revocation can ever be built from it — the old behaviour errored with
        // "no such link in the invite list" BEFORE the local delete, leaving an entry
        // the owner could neither use nor remove.
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Husks", vec!["wss://r".into()], None).await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);

        let minted = mint_public_link(&relay, &community, "https://x", None, None).await.unwrap();
        let token_hex = crate::simd::hex::bytes_to_hex_16(&minted.token);
        assert_eq!(crate::db::community::list_public_invites(&cid_hex).unwrap().len(), 1);

        // "Another device" retires the link: republish the invite list without it.
        let signer = crate::signer::active_signer().unwrap();
        let my_pk = me_pk().unwrap();
        let mut list = fetch_invite_list(&relay, &community.relays).await.unwrap().unwrap();
        list.entries.retain(|e| e.token != token_hex);
        let ev = invite::build_invite_list_event_signed(&signer, my_pk, &list).await.unwrap();
        relay.publish(&ev, &community.relays).await.unwrap();

        // This device's revoke now completes by pruning, not by erroring.
        revoke_public_link(&relay, &community, &token_hex).await.unwrap();
        assert!(
            crate::db::community::list_public_invites(&cid_hex).unwrap().is_empty(),
            "the husk row is gone — the panel can no longer show a link nobody can use or remove"
        );

        // An unreadable list is NOT proof of absence: only a fetched list may prune.
        // (Guarded by the ok_or above the husk branch; a fresh row + an empty relay
        // would hit "no invite list found", never the prune.)
    }

    #[tokio::test]
    async fn revoking_the_last_link_privatizes_and_rotates_but_an_earlier_revoke_does_not() {
        // CORD-06 §3: converting a Public Community to Private is a Refounding
        // trigger — revoking stops NEW acquisitions, only the rotation cuts off
        // everyone who already fetched the bundle. Revoking a link while ANOTHER
        // stays live is not the conversion, and must not burn an epoch.
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Privatize", vec!["wss://r".into()], None).await.unwrap();
        assert_eq!(community.root_epoch, Epoch(0));

        let a = mint_public_link(&relay, &community, "https://x", None, None).await.unwrap();
        let b = mint_public_link(&relay, &community, "https://x", None, None).await.unwrap();
        assert!(community_is_public(&relay, &community).await, "two live links = Public");

        // Revoking ONE of two: still Public, still epoch 0 — no rotation.
        revoke_public_link(&relay, &community, &crate::simd::hex::bytes_to_hex_16(&a.token)).await.unwrap();
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        assert_eq!(held.root_epoch, Epoch(0), "a link remains live — not the Public→Private conversion");
        assert!(community_is_public(&relay, &held).await, "still Public");

        // Revoking the LAST one privatizes AND rotates.
        revoke_public_link(&relay, &held, &crate::simd::hex::bytes_to_hex_16(&b.token)).await.unwrap();
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        assert!(!community_is_public(&relay, &held).await, "no live links = Private");
        assert_eq!(held.root_epoch, Epoch(1), "privatizing rotated the base key");
        // The rotation is a real one: the new epoch carries the split pair and
        // the old root is retired, so a link-joined lurker's key is now dead.
        assert!(held.control_pk.is_some(), "the privatize rotation mints the split like any base rotation");
        assert_ne!(held.community_root, community.community_root, "the base key actually rolled");
    }

    #[tokio::test]
    async fn a_legacy_community_upgrades_as_a_side_effect_of_its_next_refounding() {
        // CORD-06 §3: a compliant Rotator performing ANY base rotation MUST mint
        // the split — a pre-split community upgrades with nobody deciding to.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_legacy_community(&relay, &owner, "Legacy", vec!["wss://r".into()]).await;
        assert!(community.control_pk.is_none(), "starts pre-split");

        let refounded = refound_community(&relay, &community, &[]).await.unwrap();
        assert_eq!(refounded.root_epoch, Epoch(1));
        assert!(refounded.control_pk.is_some() && refounded.control_root.is_some(), "the rotation minted the split");
        // And the persisted row agrees (the pair survives a reload).
        let reloaded = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        assert_eq!(reloaded.control_pk, refounded.control_pk);
        assert_eq!(reloaded.control_root, refounded.control_root);
    }

    #[tokio::test]
    async fn an_old_build_deletion_recovers_from_the_stale_bundle_across_the_split() {
        // The 0.4.0/0.4.1 upgrade path: those builds hit the widened base blob,
        // conclude a false removal, and DELETE the community locally. Recovery on
        // upgrade is the Community-List resurrection: re-accept the STALE-epoch
        // material (the old plane is still served), then walk the rekey chain
        // forward — now parsing the 104-byte form — to the current epoch.
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_legacy_community(&bed.relay, &owner.keys, "Recover", bed.relays.clone()).await;
        let stale_bundle = serde_json::to_string(&bundle_of(&community, BundleAudience::Link, None, None, None)).unwrap();

        // The member joins at the legacy epoch 0.
        bed.swap_to(&member);
        let joined = accept_parked_invite(&bed.relay, &stale_bundle, None).await.unwrap();
        assert!(joined.control_pk.is_none());

        // The owner bans nobody but rotates (any refound upgrades to the split).
        bed.swap_to(&owner);
        let refounded = refound_community(&bed.relay, &community, &[]).await.unwrap();

        // The member's OLD build falsely self-removes and deletes the community.
        bed.swap_to(&member);
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        crate::db::community::delete_community(&cid_hex).unwrap();
        assert!(crate::db::community::load_community_v2(community.id()).unwrap().is_none());

        // Upgrade-recovery: re-accept the stale epoch-0 material (what
        // sync_community_list does from the surviving 13302 entry)...
        let readopted = accept_parked_invite(&bed.relay, &stale_bundle, None).await.unwrap();
        assert_eq!(readopted.root_epoch, Epoch(0), "re-anchored at the stale epoch");
        // ...then the walk crosses the split rotation and adopts the pair.
        let follow = follow_rekeys(&bed.relay, &readopted, &crate::db::current_session()).await.unwrap();
        assert!(!follow.self_removed, "never a false removal on this build");
        let healed = follow.updated.expect("the walk adopts the split rotation");
        assert_eq!(healed.root_epoch, Epoch(1));
        assert_eq!(healed.control_pk, refounded.control_pk, "the member reads the upgraded plane");
        assert_eq!(healed.control_root, None, "a plain member never receives the secret");
        // And the upgraded control plane folds for them (the compacted state).
        let folded = follow_control(&bed.relay, &healed).await;
        assert!(folded.is_ok(), "the recovered member folds the split plane: {folded:?}");
    }

    #[tokio::test]
    async fn an_unopenable_blob_at_my_locator_never_concludes_removal() {
        // CORD-06 §2: removal = NO blob for my locator across a complete
        // rotation. A blob that EXISTS but won't open (a future width, a rotator
        // bug) must park — turning it into a self-removal is exactly how the
        // pre-split builds deleted communities on the first widened rotation.
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Garbled", bed.relays.clone(), None).await.unwrap();
        let bundle_json = serde_json::to_string(&bundle_of(&community, BundleAudience::Link, None, None, None)).unwrap();
        bed.swap_to(&member);
        let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();

        // The owner mints a complete, authorized rotation whose blob AT THE
        // MEMBER'S LOCATOR is garbage (undecryptable), owner's own blob real.
        bed.swap_to(&owner);
        let new_epoch = Epoch(1);
        let new_root = [0x4Du8; 32];
        let control_root = [0x4Eu8; 32];
        let control_pk = super::super::derive::control_signer_group_key(&control_root, community.id(), new_epoch).pk();
        let prev_commit = super::super::derive::epoch_key_commitment(Epoch(0), &community.community_root);
        let garbled = rekey::RekeyBlob {
            locator: rekey::blob_locator(&owner.keys.public_key().to_bytes(), &member.keys.public_key().to_bytes(), RekeyScope::Root, new_epoch),
            wrapped: "bm90LWEtcmVhbC1uaXA0NC1wYXlsb2Fk".into(),
        };
        let own = rekey::build_base_blob(
            &crate::signer::ActiveSigner::Keys(owner.keys.clone()),
            &owner.keys.public_key().to_bytes(),
            &owner.keys.public_key(),
            new_epoch,
            &new_root,
            &control_pk.to_bytes(),
            Some(&control_root),
        )
        .await
        .unwrap();
        let base_group = base_rekey_group_key(&community.community_root, community.id(), new_epoch);
        let chunks = rekey::build_rekey_chunks_local(&owner.keys, &base_group, RekeyScope::Root, new_epoch, Epoch(0), &prev_commit, &[garbled, own], 2_000, None, false).unwrap();
        for c in &chunks {
            bed.relay.publish(c, &community.relays).await.unwrap();
        }

        // The member's follow PARKS: no adoption, and NEVER a removal.
        bed.swap_to(&member);
        let follow = follow_rekeys(&bed.relay, &joined, &crate::db::current_session()).await.unwrap();
        assert!(!follow.self_removed, "an unopenable blob at my locator is not an exclusion");
        assert!(follow.updated.is_none(), "nothing adopted from an unreadable blob");
        assert!(crate::db::community::load_community_v2(community.id()).unwrap().is_some(), "the community survives");
        // …and the park is LEGIBLE. A silent park is indistinguishable from "no
        // rotation happened", which is what makes an undecryptable blob planted
        // at a protected member's locator an abusable severing tool.
        assert!(follow.wedged, "an unopenable key delivery must be surfaced, not swallowed");
    }

    #[tokio::test]
    async fn a_control_wrap_is_refused_on_a_stale_epoch_or_a_non_deriving_secret() {
        // What the "no rank-gating on adoption" argument rests on (CORD-04 §3):
        // a wrap is adopted only if its secret derives to the control_pk held
        // for the epoch named INSIDE its ciphertext. That derive check is the
        // load-bearing gate (revert-verified); the explicit epoch comparison
        // beside it is defense in depth and can't be isolated, since deriving
        // at a stale epoch already misses the held address. Compaction re-wraps
        // a Grant head verbatim across Refoundings, so stale wraps are a
        // structural certainty, not an edge case.
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "AdoptGate", bed.relays.clone(), None).await.unwrap();
        let bundle_json = serde_json::to_string(&bundle_of(&community, BundleAudience::Link, None, None, None)).unwrap();
        bed.swap_to(&member);
        let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
        assert!(joined.control_root.is_none());

        // Build a Grant edition carrying `control_wrap` with a chosen plaintext.
        let wrap_for = |epoch: Epoch, secret: &[u8; 32]| {
            let ck = nostr_sdk::prelude::nip44::v2::ConversationKey::derive(owner.keys.secret_key(), &member.keys.public_key()).unwrap();
            let ct = crate::community::cipher::encrypt_with_random_nonce(&ck, super::rekey::control_wrap_b64(epoch, secret).as_bytes()).unwrap();
            crate::simd::base64::STANDARD.encode_to_string(&ct)
        };
        let eid = crate::community::v2::derive::grant_locator(community.id(), &member.keys.public_key().to_bytes());
        let ed_with = |wrap: String| {
            let grant = MemberGrant { member: member.keys.public_key().to_hex(), role_ids: vec![] };
            let content = crate::community::v2::roles::grant_content_json_with_wrap(&grant, Some(wrap)).unwrap();
            let rumor = control::build_edition_rumor(owner.keys.public_key(), vsk::GRANT, &eid, 1, None, &content, 1_000, None);
            control::parse_edition_rumor(&rumor).unwrap()
        };

        // (a) A wrap for a DIFFERENT epoch — the real secret, wrong epoch.
        let real = community.control_root.unwrap();
        let stale = ed_with(wrap_for(Epoch(joined.root_epoch.0 + 1), &real));
        assert_eq!(adopt_my_control_wrap(&joined, std::slice::from_ref(&stale)).await, None, "a stale-epoch wrap is refused");

        // (b) Right epoch, a secret that does NOT derive to the held pk.
        let forged = ed_with(wrap_for(joined.root_epoch, &[0x66u8; 32]));
        assert_eq!(adopt_my_control_wrap(&joined, std::slice::from_ref(&forged)).await, None, "a non-deriving secret is refused");

        // (c) The real secret at the held epoch IS adopted — the gates above
        // reject on their own merits, not because adoption is broken.
        let good = ed_with(wrap_for(joined.root_epoch, &real));
        assert_eq!(adopt_my_control_wrap(&joined, std::slice::from_ref(&good)).await, Some(real), "the true wrap adopts");
    }

    #[test]
    fn the_vault_carries_the_control_split() {
        // CORD-02 §8: the list carries every key its holder has — the address
        // for all, the secret for staff.
        let owner = Keys::generate();
        let g = control::genesis(&owner, control::CommunityMetadata { name: "Vault".into(), ..Default::default() }, 1_000).unwrap();
        let c = CommunityV2::from_genesis(&g, "Vault", None, vec!["wss://r".into()], 0);
        let jm = join_material(&c);
        assert_eq!(jm.control_pk, c.control_pk.map(|p| p.to_hex()));
        assert_eq!(jm.control_root, Some(crate::simd::hex::bytes_to_hex_32(&g.control_root)));
        let bundle = material_to_invite(&jm);
        assert_eq!(bundle.control_pk, jm.control_pk, "a rehydrating bundle carries the address");
    }

    // ── CORD-04 §1 author-aware fold: a seat-holder (holds community_root, so can seal
    // any control edition) must not be able to SUPPRESS a role or grant by forging a
    // higher version at its coordinate. Owner-only signers mask this entirely, so every
    // attacker below signs as a NON-owner member.

    #[tokio::test]
    async fn a_non_owner_cannot_suppress_the_admin_role_by_forging_a_higher_version() {
        let (bed, owner, attacker) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "AttackA", bed.relays.clone(), None).await.unwrap();
        let victim = Keys::generate().public_key();
        grant_admin(&bed.relay, &community, &victim).await.unwrap();

        // The admin role sits at a deterministic, publicly-computable coordinate.
        let admin_rid = fetch_authority(&bed.relay, &community)
            .await
            .roles
            .roles
            .iter()
            .find(|r| r.permissions.contains(Permissions::ADMIN_ALL))
            .unwrap()
            .role_id
            .clone();
        // Attacker forges v2 of that exact role, stripping its powers.
        publish_role(
            &bed.relay,
            &community,
            &attacker.keys,
            &Role { role_id: admin_rid.clone(), name: "pwned".into(), position: 1, permissions: Permissions(0), scope: RoleScope::Server, color: 0, rank: None, display: false, mentionable: false, extra: Default::default() },
            2,
        )
        .await;

        let authority = fold_authority(&community, &fetch_control(&bed.relay, &community).await, &load_floors(&community));
        assert!(authority.roles.is_admin(&victim.to_hex()), "the forged strip is DROPPED; the owner's admin role survives beneath it");
        assert!(
            authority.heads.iter().any(|h| h.entity_hex == admin_rid && h.version == 1),
            "the floor advances only to the AUTHORIZED head (owner v1)"
        );
        assert!(!authority.heads.iter().any(|h| h.version == 2), "the forged v2 never poisons the floor");
    }

    #[tokio::test]
    async fn a_non_owner_cannot_strip_a_members_grant_by_forging_a_higher_version() {
        let (bed, owner, attacker) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "AttackC", bed.relays.clone(), None).await.unwrap();
        let victim = Keys::generate();
        grant_admin(&bed.relay, &community, &victim.public_key()).await.unwrap();

        // Attacker forges a higher-version EMPTY grant at the victim's grant coordinate.
        publish_grant(&bed.relay, &community, &attacker.keys, &victim.public_key(), vec![], 9).await;

        let authority = fold_authority(&community, &fetch_control(&bed.relay, &community).await, &load_floors(&community));
        assert!(
            authority.roles.is_admin(&victim.public_key().to_hex()),
            "the forged strip is dropped; the owner's grant survives and the victim keeps admin"
        );
    }

    #[tokio::test]
    async fn forged_low_id_roles_by_a_non_owner_never_enter_the_authorized_roster() {
        let (bed, owner, attacker) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "AttackB", bed.relays.clone(), None).await.unwrap();
        let victim = Keys::generate().public_key();
        grant_admin(&bed.relay, &community, &victim).await.unwrap();

        // Low-id roles that WOULD evict the admin from a pre-authorize cap — but they're
        // unauthorized, so the post-authorize cap never sees them.
        for i in 0u8..6 {
            let rid = crate::simd::hex::bytes_to_hex_32(&[i; 32]);
            publish_role(&bed.relay, &community, &attacker.keys, &admin_role(&rid, Permissions::ADMIN_ALL), 1).await;
        }

        let authority = fold_authority(&community, &fetch_control(&bed.relay, &community).await, &load_floors(&community));
        assert!(authority.roles.is_admin(&victim.to_hex()), "the legit admin survives the forged flood");
        assert_eq!(authority.roles.roles.len(), 1, "only the owner's admin role is authorized; every forgery is dropped");
    }

    #[tokio::test]
    async fn a_same_version_role_fork_folds_to_the_lowest_rumor_id_in_any_order() {
        // CORD-04 §1: two authorized editions tying on version converge on the LOWEST
        // id — the rule grants, metadata, the persisted floor and Armada all apply.
        let (bed, owner, _m) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "RoleFork", bed.relays.clone(), None).await.unwrap();
        let eid = [0x42u8; 32];
        let rid = crate::simd::hex::bytes_to_hex_32(&eid);
        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::ADMIN_ALL), 1).await;
        let v1 = head_hash_on_relay(&bed.relay, &community, &eid).await.unwrap();

        // The owner on two devices: two v2 editions off the same v1.
        let group = control::ControlPlane::of(&community).write_group().unwrap();
        let mut forks: Vec<(&str, [u8; 32])> = Vec::new();
        for (name, ts) in [("Left", 2_000u64), ("Right", 2_001)] {
            let mut role = admin_role(&rid, Permissions::ADMIN_ALL);
            role.name = name.into();
            let content = crate::community::v2::roles::role_content_json(&role).unwrap();
            let rumor = control::build_edition_rumor(owner.keys.public_key(), vsk::ROLE, &eid, 2, Some(&v1), &content, ts, None);
            forks.push((name, rumor.id.unwrap().to_bytes()));
            let (wrap, _) = control::seal_control_edition(&rumor, &group, &owner.keys, Timestamp::from_secs(ts)).unwrap();
            bed.relay.publish(&wrap, &community.relays).await.unwrap();
        }
        let (winner, winner_id) = *forks.iter().min_by_key(|(_, id)| *id).unwrap();

        let editions = fetch_control(&bed.relay, &community).await;
        let floors = load_floors(&community);
        let mut reversed = editions.clone();
        reversed.reverse();
        for (order, set) in [("served", &editions), ("reversed", &reversed)] {
            let folded = fold_authority(&community, set, &floors);
            assert_eq!(folded.roles.role(&rid).unwrap().name, winner, "{order} order folds the lowest-id fork");
            // The head the floor commits to — and a refound re-wraps — is that same edition.
            let head = folded.heads.iter().find(|h| h.entity_hex == rid).unwrap();
            assert_eq!((head.version, head.inner_id), (2, winner_id), "{order} order heads the lowest-id fork");
        }
    }

    /// Publish one side of a same-version fork to every relay given, nudging its clock until
    /// its rumor id sorts as `order` against another id. A test can then pit authority against
    /// the id rule instead of hoping the hashes fall the right way.
    #[allow(clippy::too_many_arguments)]
    async fn publish_fork(
        relays: &[&MemoryRelay],
        community: &CommunityV2,
        signer: &Keys,
        vsk_code: &str,
        eid: &[u8; 32],
        version: u64,
        prev: Option<[u8; 32]>,
        content: &str,
        order: Option<(std::cmp::Ordering, [u8; 32])>,
    ) -> [u8; 32] {
        let group = control::ControlPlane::of(community).write_group().unwrap();
        let cite = cite_on_relay(relays[0], community, signer).await;
        for ts in 5_000u64.. {
            let rumor = control::build_edition_rumor(signer.public_key(), vsk_code, eid, version, prev.as_ref(), content, ts, cite.as_ref());
            let id = rumor.id.unwrap().to_bytes();
            if order.is_some_and(|(want, other)| id.cmp(&other) != want) {
                continue;
            }
            for relay in relays {
                let (wrap, _) = control::seal_control_edition(&rumor, &group, signer, Timestamp::from_secs(ts)).unwrap();
                relay.publish(&wrap, &community.relays).await.unwrap();
            }
            return id;
        }
        unreachable!()
    }

    fn channel_meta_json(name: &str) -> String {
        serde_json::to_string(&control::ChannelMetadata { name: name.into(), private: false, ..Default::default() }).unwrap()
    }

    /// The persisted floor of one entity: `(version, inner_id, author)`.
    /// Drop every Control wrap held of `community`: its floors and roster stay, as on a device
    /// that kept no wraps when it read them.
    fn forget_held(community: &CommunityV2) {
        let view = control_store::View::of(community);
        for (id, _) in view.held().unwrap() {
            view.forget(&id);
        }
    }

    fn floor_of(community: &CommunityV2, entity: &[u8; 32]) -> (u64, Option<[u8; 32]>, Option<[u8; 32]>) {
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let f = crate::db::community::get_all_edition_heads_full(&cid_hex).unwrap()[&crate::simd::hex::bytes_to_hex_32(entity)];
        (f.1, f.3, f.4)
    }

    /// A community whose `admin` holds a position-1 role with `perms`, granted by the owner.
    async fn with_admin(relay: &MemoryRelay, name: &str, owner: &Keys, perms: u64) -> (CommunityV2, Keys) {
        let community = create_community(relay, name, vec!["wss://r".into()], None).await.unwrap();
        let admin = Keys::generate();
        let rid = "d1".repeat(32);
        publish_role(relay, &community, owner, &admin_role(&rid, perms), 1).await;
        publish_grant(relay, &community, owner, &admin.public_key(), vec![rid], 1).await;
        (community, admin)
    }

    #[tokio::test]
    async fn a_same_version_channel_fork_goes_to_the_owner_over_a_lower_id_admin_edit() {
        // CORD-04 §1: authority first, then the lower rumor id. The admin's edit sorts
        // lower, so the old id-only rule would have seated it; Armada seats the owner's.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let (community, admin) = with_admin(&relay, "ForkAuth", &owner, Permissions::MANAGE_CHANNELS).await;
        let ch = community.channels[0].id;
        let v1 = head_hash_on_relay(&relay, &community, &ch.0).await;
        let owner_id = publish_fork(&[&relay], &community, &owner, vsk::CHANNEL_METADATA, &ch.0, 2, v1, &channel_meta_json("owner-pick"), None).await;
        let admin_id = publish_fork(&[&relay], &community, &admin, vsk::CHANNEL_METADATA, &ch.0, 2, v1, &channel_meta_json("admin-pick"), Some((std::cmp::Ordering::Less, owner_id))).await;

        let updated = follow_control(&relay, &community).await.unwrap().updated.expect("the fork folds");
        assert_eq!(updated.channel(&ch).unwrap().name, "owner-pick", "authority beats the lower id");
        assert_eq!(floor_of(&community, &ch.0), (2, Some(owner_id), Some(owner.public_key().to_bytes())), "the floor commits to the owner's edition");
        assert_ne!(owner_id, admin_id);

        // A fresh joiner (no floor for the entity) bootstraps to the same head.
        let editions = fetch_control(&relay, &community).await;
        let mut floors = load_floors(&community);
        floors.remove(&crate::simd::hex::bytes_to_hex_32(&ch.0));
        let authority = fold_authority(&community, &editions, &floors);
        for set in [editions.clone(), editions.iter().rev().cloned().collect()] {
            let fold = apply_control_fold(&community, &set, &floors, &authority);
            let head = fold.heads.iter().find(|h| h.entity_hex == crate::simd::hex::bytes_to_hex_32(&ch.0)).unwrap();
            assert_eq!(head.inner_id, owner_id, "bootstrap picks the owner's fork in any order");
        }
    }

    #[tokio::test]
    async fn a_tracking_client_holding_the_admins_fork_converges_to_the_owners_higher_id() {
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let (community, admin) = with_admin(&relay, "ForkTrack", &owner, Permissions::MANAGE_CHANNELS).await;
        let ch = community.channels[0].id;
        let v1 = head_hash_on_relay(&relay, &community, &ch.0).await;
        let admin_id = publish_fork(&[&relay], &community, &admin, vsk::CHANNEL_METADATA, &ch.0, 2, v1, &channel_meta_json("admin-pick"), None).await;
        let first = follow_control(&relay, &community).await.unwrap().updated.expect("the admin's edit folds");
        assert_eq!(first.channel(&ch).unwrap().name, "admin-pick");
        assert_eq!(floor_of(&community, &ch.0).1, Some(admin_id));

        // The owner's sibling arrives later and sorts HIGHER: only authority can seat it.
        let owner_id = publish_fork(&[&relay], &community, &owner, vsk::CHANNEL_METADATA, &ch.0, 2, v1, &channel_meta_json("owner-pick"), Some((std::cmp::Ordering::Greater, admin_id))).await;
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let second = follow_control(&relay, &held).await.unwrap().updated.expect("the floor converges");
        assert_eq!(second.channel(&ch).unwrap().name, "owner-pick");
        assert_eq!(floor_of(&community, &ch.0), (2, Some(owner_id), Some(owner.public_key().to_bytes())));
    }

    #[tokio::test]
    async fn a_withheld_owner_floor_is_not_swapped_for_a_served_admin_sibling() {
        // The floor holds the owner's v2. A relay serving only the admin's v2 (lower id)
        // must not flip it: the held key carries the owner's authority even unserved.
        let (_tmp, _guard, owner) = init_test_db();
        let full = MemoryRelay::new();
        let (community, admin) = with_admin(&full, "ForkHold", &owner, Permissions::MANAGE_CHANNELS).await;
        let thin = MemoryRelay::new();
        mirror_control(&full, &thin, &community).await;
        let ch = community.channels[0].id;
        let v1 = head_hash_on_relay(&full, &community, &ch.0).await;
        let owner_id = publish_fork(&[&full], &community, &owner, vsk::CHANNEL_METADATA, &ch.0, 2, v1, &channel_meta_json("owner-pick"), None).await;
        publish_fork(&[&full, &thin], &community, &admin, vsk::CHANNEL_METADATA, &ch.0, 2, v1, &channel_meta_json("admin-pick"), Some((std::cmp::Ordering::Less, owner_id))).await;

        follow_control(&full, &community).await.unwrap();
        assert_eq!(floor_of(&community, &ch.0).1, Some(owner_id));
        // The thin relay's plane is coherent: the admin's edit alone would fold there.
        let editions = fetch_control(&thin, &community).await;
        let authority = fold_authority(&community, &editions, &load_floors(&community));
        assert!(
            editions.iter().any(|e| e.entity_id == ch.0 && e.version == 2 && authority.roles.is_authorized(&admin.public_key().to_hex(), None, Permissions::MANAGE_CHANNELS)),
            "the admin's sibling is served and authorized on the thin relay"
        );
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        follow_control(&thin, &held).await.unwrap();
        assert_eq!(floor_of(&community, &ch.0).1, Some(owner_id), "a served worse sibling never takes the floor");
        let after = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        assert_eq!(after.channel(&ch).unwrap().name, "owner-pick");
    }

    /// Copy every control wrap one relay holds onto another, so both serve one coherent plane.
    async fn mirror_control(from: &MemoryRelay, to: &MemoryRelay, community: &CommunityV2) {
        let group = control::ControlPlane::of(community).write_group().unwrap();
        let query = Query { kinds: vec![stream::KIND_WRAP], authors: vec![group.pk_hex()], limit: Some(500), ..Default::default() };
        for w in from.fetch(&query, &community.relays).await.unwrap() {
            to.publish(&w, &community.relays).await.unwrap();
        }
    }

    #[tokio::test]
    async fn a_floor_written_before_authors_were_recorded_still_converges_on_authority() {
        // A pre-upgrade client held the admin's v2 (lower id) with no author recorded. With
        // both siblings served, the tiebreak decides: authority seats the owner's.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let (community, admin) = with_admin(&relay, "ForkLegacy", &owner, Permissions::MANAGE_CHANNELS).await;
        let ch = community.channels[0].id;
        let v1 = head_hash_on_relay(&relay, &community, &ch.0).await;
        let owner_id = publish_fork(&[&relay], &community, &owner, vsk::CHANNEL_METADATA, &ch.0, 2, v1, &channel_meta_json("owner-pick"), None).await;
        let admin_id = publish_fork(&[&relay], &community, &admin, vsk::CHANNEL_METADATA, &ch.0, 2, v1, &channel_meta_json("admin-pick"), Some((std::cmp::Ordering::Less, owner_id))).await;
        let editions = fetch_control(&relay, &community).await;
        let admin_hash = editions.iter().find(|e| e.inner_id == admin_id).unwrap().self_hash;
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        crate::db::community::set_edition_head_with_id(&cid_hex, &crate::simd::hex::bytes_to_hex_32(&ch.0), 2, &admin_hash, &admin_id).unwrap();
        assert_eq!(floor_of(&community, &ch.0), (2, Some(admin_id), None), "a legacy row: id, no author");

        let updated = follow_control(&relay, &community).await.unwrap().updated.expect("the legacy floor converges");
        assert_eq!(updated.channel(&ch).unwrap().name, "owner-pick");
        assert_eq!(floor_of(&community, &ch.0), (2, Some(owner_id), Some(owner.public_key().to_bytes())));
    }

    #[tokio::test]
    async fn a_role_floor_written_before_authors_were_recorded_still_converges_on_authority() {
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let (community, admin) = with_admin(&relay, "RoleLegacy", &owner, Permissions::ADMIN_ALL).await;
        let rlow = "f1".repeat(32);
        let mut low = admin_role(&rlow, Permissions::KICK);
        low.position = 5;
        publish_role(&relay, &community, &owner, &low, 1).await;
        let eid = crate::simd::hex::hex_to_bytes_32_checked(&rlow).unwrap();
        let v1 = head_hash_on_relay(&relay, &community, &eid).await;
        let named = |name: &str| {
            let mut r = low.clone();
            r.name = name.into();
            crate::community::v2::roles::role_content_json(&r).unwrap()
        };
        let owner_id = publish_fork(&[&relay], &community, &owner, vsk::ROLE, &eid, 2, v1, &named("owner-pick"), None).await;
        let admin_id = publish_fork(&[&relay], &community, &admin, vsk::ROLE, &eid, 2, v1, &named("admin-pick"), Some((std::cmp::Ordering::Less, owner_id))).await;
        let editions = fetch_control(&relay, &community).await;
        let admin_hash = editions.iter().find(|e| e.inner_id == admin_id).unwrap().self_hash;
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        crate::db::community::set_edition_head_with_id(&cid_hex, &rlow, 2, &admin_hash, &admin_id).unwrap();
        assert_eq!(floor_of(&community, &eid), (2, Some(admin_id), None));

        let a = fold_authority(&community, &editions, &load_floors(&community));
        assert_eq!(a.roles.role(&rlow).unwrap().name, "owner-pick", "a served held edition competes on the tiebreak");
        assert_eq!(a.heads.iter().find(|h| h.entity_hex == rlow).map(|h| h.inner_id), Some(owner_id));
    }

    #[tokio::test]
    async fn a_floor_holding_a_marked_editions_unsigned_hash_heals_and_its_authority_returns() {
        // The admin's grant moved to a marked v2, and a build before marked editions floored it
        // under its unsigned hash, which nothing served carries: the grant folded no head, and
        // every edition the admin signed after it fell unauthorized.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let (community, admin) = with_admin(&relay, "UnsignedFloor", &owner, Permissions::MANAGE_CHANNELS).await;
        let eid = crate::community::v2::derive::grant_locator(community.id(), &admin.public_key().to_bytes());
        let group = control::ControlPlane::of(&community).write_group().unwrap();
        let prev = head_hash_on_relay(&relay, &community, &eid).await;
        let grant = MemberGrant { member: admin.public_key().to_hex(), role_ids: vec!["d1".repeat(32)] };
        let content = crate::community::v2::roles::grant_content_json_with_wrap(&grant, None).unwrap();
        let cite = cite_on_relay(&relay, &community, &owner).await;
        let binding = Some(crate::community::v2::derive::edition_binding(community.id()));
        let rumor = control::build_edition_rumor_bound(owner.public_key(), vsk::GRANT, &eid, 2, prev.as_ref(), &content, 1_001, cite.as_ref(), binding);
        let (wrap, _) = control::seal_control_edition(&rumor, &group, &owner, Timestamp::from_secs(1_001)).unwrap();
        relay.publish(&wrap, &community.relays).await.unwrap();
        follow_control(&relay, &community).await.unwrap();

        let v2 = fetch_control(&relay, &community).await.into_iter().find(|e| e.entity_id == eid && e.version == 2).unwrap();
        let unsigned = crate::community::version::edition_hash(&eid, 2, v2.prev_hash.as_ref(), v2.content.as_bytes());
        assert!(v2.binding.is_some() && unsigned != v2.self_hash, "a marked edition's hash covers its signer");
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let eid_hex = crate::simd::hex::bytes_to_hex_32(&eid);
        crate::db::community::delete_edition_head(&cid_hex, &eid_hex).unwrap();
        crate::db::community::set_edition_head_at_epoch(&cid_hex, &eid_hex, 2, &unsigned, &v2.inner_id, &owner.public_key().to_bytes(), community.root_epoch.0).unwrap();

        let ch = community.channels[0].id;
        let v1 = head_hash_on_relay(&relay, &community, &ch.0).await;
        publish_fork(&[&relay], &community, &admin, vsk::CHANNEL_METADATA, &ch.0, 2, v1, &channel_meta_json("renamed-by-admin"), None).await;
        let updated = follow_control(&relay, &community).await.unwrap().updated.expect("the admin's rename folds");
        assert_eq!(updated.channel(&ch).unwrap().name, "renamed-by-admin", "the admin's authority is back");
        let held = crate::db::community::get_all_edition_heads_full(&cid_hex).unwrap()[&eid_hex];
        assert_eq!((held.1, held.2), (2, v2.self_hash), "the floor names the served edition");
    }

    #[tokio::test]
    async fn only_the_same_edition_heals_an_unsigned_floor() {
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "HealScope", vec!["wss://r".into()], None).await.unwrap();
        let group = control::ControlPlane::of(&community).write_group().unwrap();
        let binding = Some(crate::community::v2::derive::edition_binding(community.id()));
        let eid = [7u8; 32];
        let key = crate::simd::hex::bytes_to_hex_32(&eid);
        let publish = |rumor: nostr_sdk::prelude::UnsignedEvent, signer: Keys, ts: u64| {
            let (wrap, _) = control::seal_control_edition(&rumor, &group, &signer, Timestamp::from_secs(ts)).unwrap();
            (wrap, signer)
        };
        let (wrap, _) = publish(control::build_edition_rumor_bound(owner.public_key(), vsk::CHANNEL_METADATA, &eid, 3, Some(&[1u8; 32]), &channel_meta_json("x"), 1_000, None, binding), owner.clone(), 1_000);
        relay.publish(&wrap, &community.relays).await.unwrap();
        let mine = fetch_control(&relay, &community).await;
        let e = mine.iter().find(|x| x.entity_id == eid).unwrap().clone();
        let unsigned = crate::community::version::edition_hash(&eid, 3, e.prev_hash.as_ref(), e.content.as_bytes());
        let owner_pk = Some(owner.public_key().to_bytes());
        let heal = |floor: Floor, served: &[ParsedEdition]| {
            let mut floors: Floors = Default::default();
            floors.insert(key.clone(), floor);
            let mut healed = Vec::new();
            heal_unsigned_floors(&mut floors, owner_pk, served, &mut healed);
            (floors[&key].1, healed.len())
        };
        let only_e = std::slice::from_ref(&e);
        assert_eq!(heal((3, unsigned, None, None, None), only_e), (e.self_hash, 1), "its unsigned hash, by the owner, heals");
        assert_eq!(heal((3, [9u8; 32], Some(e.inner_id), None, None), only_e), (e.self_hash, 1), "its inner id heals");
        assert_eq!(heal((3, [9u8; 32], Some([8u8; 32]), None, None), only_e), ([9u8; 32], 0), "another edition stays");
        assert_eq!(heal((2, unsigned, None, None, None), only_e), (unsigned, 0), "another version stays");
        assert_eq!(heal((3, unsigned, None, Some([5u8; 32]), None), only_e), (unsigned, 0), "another signer's floor stays");

        // The same content re-signed by another key carries the same unsigned hash.
        let other = Keys::generate();
        let (wrap, _) = publish(control::build_edition_rumor_bound(other.public_key(), vsk::CHANNEL_METADATA, &eid, 3, Some(&[1u8; 32]), &channel_meta_json("x"), 1_001, None, binding), other.clone(), 1_001);
        relay.publish(&wrap, &community.relays).await.unwrap();
        let both: Vec<ParsedEdition> = fetch_control(&relay, &community).await.into_iter().filter(|x| x.entity_id == eid).collect();
        assert_eq!(both.len(), 2);
        let theirs: Vec<ParsedEdition> = both.iter().filter(|x| x.author == other.public_key()).cloned().collect();
        assert_eq!(heal((3, unsigned, None, None, None), &theirs), (unsigned, 0), "with no signer recorded, nobody's copy but the owner's");
        assert_eq!(heal((3, unsigned, None, None, None), &both), (e.self_hash, 1), "the owner's copy when none was recorded");
        assert_eq!(heal((3, unsigned, None, Some(other.public_key().to_bytes()), None), &both).0, theirs[0].self_hash, "the recorded signer's copy");

        // An unmarked copy carries the unsigned hash itself, but not the floor's inner id: it
        // must not pass for the held edition and keep the real one from healing.
        let (wrap, _) = publish(control::build_edition_rumor(other.public_key(), vsk::CHANNEL_METADATA, &eid, 3, Some(&[1u8; 32]), &channel_meta_json("x"), 1_002, None), other.clone(), 1_002);
        relay.publish(&wrap, &community.relays).await.unwrap();
        let all: Vec<ParsedEdition> = fetch_control(&relay, &community).await.into_iter().filter(|x| x.entity_id == eid).collect();
        assert!(all.iter().any(|x| x.self_hash == unsigned), "the unmarked copy's hash is the unsigned one");
        assert_eq!(heal((3, unsigned, Some(e.inner_id), None, None), &all), (e.self_hash, 1), "the floor's own edition still heals");
    }

    /// A channel edition sealed for the plane and published nowhere: only a live fold sees it.
    fn live_edition(community: &CommunityV2, signer: &Keys, eid: &[u8; 32], version: u64, prev: Option<[u8; 32]>, name: &str, ts: u64) -> Event {
        let group = control::ControlPlane::of(community).write_group().unwrap();
        let rumor = control::build_edition_rumor(signer.public_key(), vsk::CHANNEL_METADATA, eid, version, prev.as_ref(), &channel_meta_json(name), ts, None);
        control::seal_control_edition(&rumor, &group, signer, Timestamp::from_secs(ts)).unwrap().0
    }

    #[tokio::test]
    async fn a_settled_community_folds_live_editions_without_reading_the_plane() {
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "LiveFold", vec!["wss://r".into()], None).await.unwrap();
        let ch = community.channels[0].id;
        follow_control(&relay, &community).await.unwrap();
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();

        let v1 = head_hash_on_relay(&relay, &community, &ch.0).await;
        let rename = live_edition(&held, &owner, &ch.0, 2, v1, "live-name", 5_000);
        let follow = follow_control_live(&held, &rename).await.expect("the held window decides it");
        assert_eq!(follow.updated.expect("the rename folds").channel(&ch).unwrap().name, "live-name");
        assert_eq!(floor_of(&community, &ch.0).0, 2);
        let after = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        assert_eq!(after.channel(&ch).unwrap().name, "live-name", "persisted");
        assert!(!follow_control_live(&after, &rename).await.expect("already held").moved(), "a repeat folds nothing");

        let v2 = control::ControlPlane::of(&after).open_edition(&rename).unwrap().self_hash;
        let again = live_edition(&after, &owner, &ch.0, 3, Some(v2), "again", 5_001);
        let follow = follow_control_live(&after, &again).await.expect("extends the edition folded live");
        assert_eq!(follow.updated.unwrap().channel(&ch).unwrap().name, "again");

        // A relay that never saw them can't roll the live editions back.
        let latest = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        follow_control(&relay, &latest).await.unwrap();
        let reread = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        assert_eq!(reread.channel(&ch).unwrap().name, "again");
        assert_eq!(floor_of(&community, &ch.0).0, 3);
    }

    #[tokio::test]
    async fn a_live_edition_only_a_read_can_settle_waits_for_one() {
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "LiveRead", vec!["wss://r".into()], None).await.unwrap();
        let ch = community.channels[0].id;
        follow_control(&relay, &community).await.unwrap();
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let v1 = head_hash_on_relay(&relay, &community, &ch.0).await;

        let stranger = Keys::generate();
        assert!(follow_control_live(&held, &live_edition(&held, &stranger, &ch.0, 2, v1, "theirs", 5_000)).await.is_none(), "an author the window grants nothing");

        let gone = serde_json::to_string(&control::ChannelMetadata { name: "x".into(), deleted: Some(true), ..Default::default() }).unwrap();
        let group = control::ControlPlane::of(&held).write_group().unwrap();
        let rumor = control::build_edition_rumor(owner.public_key(), vsk::CHANNEL_METADATA, &ch.0, 2, v1.as_ref(), &gone, 5_001, None);
        let delete = control::seal_control_edition(&rumor, &group, &owner, Timestamp::from_secs(5_001)).unwrap().0;
        assert!(follow_control_live(&held, &delete).await.is_none(), "a deletion");

        let fine = live_edition(&held, &owner, &ch.0, 2, v1, "fine", 5_002);
        let read = reading(community.id());
        assert!(follow_control_live(&held, &fine).await.is_none(), "a read in flight");
        drop(read);
        super::super::realtime::note_resubscribe();
        assert!(follow_control_live(&held, &fine).await.is_none(), "a resubscribe since the read");

        assert_eq!(floor_of(&community, &ch.0).0, 1);
        // No relay kept those: the read finds the plane as it was.
        forget_held(&held);
        follow_control(&relay, &held).await.unwrap();
        assert!(follow_control_live(&held, &fine).await.expect("a fresh read holds again").updated.is_some());
    }

    #[tokio::test]
    async fn a_live_edition_the_roster_refuses_waits_for_a_read() {
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let (community, admin) = with_admin(&relay, "LiveRefused", &owner, Permissions::KICK).await;
        let ch = community.channels[0].id;
        follow_control(&relay, &community).await.unwrap();
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let v1 = head_hash_on_relay(&relay, &community, &ch.0).await;
        let group = control::ControlPlane::of(&held).write_group().unwrap();
        let cite = cite_on_relay(&relay, &held, &admin).await;
        let rumor = control::build_edition_rumor(admin.public_key(), vsk::CHANNEL_METADATA, &ch.0, 2, v1.as_ref(), &channel_meta_json("not-theirs"), 5_000, cite.as_ref());
        let rename = control::seal_control_edition(&rumor, &group, &admin, Timestamp::from_secs(5_000)).unwrap().0;
        assert!(follow_control_live(&held, &rename).await.is_none(), "staff, but without the permission");
        assert_eq!(floor_of(&community, &ch.0).0, 1);
    }

    #[tokio::test]
    async fn a_window_missing_a_floored_grant_waits_for_a_read() {
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let (community, admin) = with_admin(&relay, "LiveDemoted", &owner, Permissions::MANAGE_CHANNELS).await;
        let ch = community.channels[0].id;
        follow_control(&relay, &community).await.unwrap();
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        // The admin's demotion floored by another path, and so not in the window.
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let geid = crate::community::v2::derive::grant_locator(community.id(), &admin.public_key().to_bytes());
        crate::db::community::set_edition_head_with_id(&cid_hex, &crate::simd::hex::bytes_to_hex_32(&geid), 2, &[2u8; 32], &[2u8; 32]).unwrap();
        let v1 = head_hash_on_relay(&relay, &community, &ch.0).await;
        let group = control::ControlPlane::of(&held).write_group().unwrap();
        let cite = cite_on_relay(&relay, &held, &admin).await;
        let rumor = control::build_edition_rumor(admin.public_key(), vsk::CHANNEL_METADATA, &ch.0, 2, v1.as_ref(), &channel_meta_json("demoted-rename"), 5_000, cite.as_ref());
        let rename = control::seal_control_edition(&rumor, &group, &admin, Timestamp::from_secs(5_000)).unwrap().0;
        assert!(follow_control_live(&held, &rename).await.is_none(), "the window can't see the newer grant");
        let owners = live_edition(&held, &owner, &ch.0, 2, v1, "owner-rename", 5_001);
        assert!(follow_control_live(&held, &owners).await.is_none(), "nor fold anything over it");
        assert_eq!(floor_of(&community, &ch.0).0, 1);
    }

    #[tokio::test]
    async fn our_own_grant_joins_the_held_window_and_its_member_folds_live() {
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let (community, _admin) = with_admin(&relay, "LiveOwn", &owner, Permissions::MANAGE_CHANNELS).await;
        let ch = community.channels[0].id;
        follow_control(&relay, &community).await.unwrap();
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let fresh = Keys::generate();
        grant_roles(&relay, &held, &fresh.public_key(), vec!["d1".repeat(32)]).await.unwrap();
        let geid = crate::community::v2::derive::grant_locator(community.id(), &fresh.public_key().to_bytes());
        let window = held_control().lock().unwrap().get(&community.id().0).cloned().expect("still held");
        assert!(window.editions.iter().any(|e| e.entity_id == geid), "our grant is in the window");

        let v1 = head_hash_on_relay(&relay, &community, &ch.0).await;
        let now = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let group = control::ControlPlane::of(&now).write_group().unwrap();
        let cite = cite_on_relay(&relay, &now, &fresh).await;
        let rumor = control::build_edition_rumor(fresh.public_key(), vsk::CHANNEL_METADATA, &ch.0, 2, v1.as_ref(), &channel_meta_json("by-the-new-admin"), 5_000, cite.as_ref());
        let rename = control::seal_control_edition(&rumor, &group, &fresh, Timestamp::from_secs(5_000)).unwrap().0;
        let follow = follow_control_live(&now, &rename).await.expect("the window holds their grant");
        assert_eq!(follow.updated.unwrap().channel(&ch).unwrap().name, "by-the-new-admin");
    }

    #[tokio::test]
    async fn a_read_a_newer_floor_overtook_persists_nothing() {
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Overtaken", vec!["wss://r".into()], None).await.unwrap();
        let ch = community.channels[0].id;
        let name = community.channels[0].name.clone();
        let v1 = head_hash_on_relay(&relay, &community, &ch.0).await;
        publish_fork(&[&relay], &community, &owner, vsk::CHANNEL_METADATA, &ch.0, 2, v1, &channel_meta_json("on-the-relay"), None).await;
        let read = read_control(&relay, &community).await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        crate::db::community::set_edition_head_with_id(&cid_hex, &crate::simd::hex::bytes_to_hex_32(&ch.0), 3, &[3u8; 32], &[3u8; 32]).unwrap();
        let (follow, window) = persist_control(&relay, &community, read).await.unwrap();
        assert!(follow.updated.is_none() && window.is_none(), "folded against floors that have moved on");
        let after = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        assert_eq!(after.channel(&ch).unwrap().name, name);
    }

    #[tokio::test]
    async fn a_live_edition_the_held_window_cannot_decide_waits_for_a_follow() {
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "LiveGap", vec!["wss://r".into()], None).await.unwrap();
        let ch = community.channels[0].id;
        let name = community.channels[0].name.clone();
        follow_control(&relay, &community).await.unwrap();
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let v1 = head_hash_on_relay(&relay, &community, &ch.0).await;

        let gap = live_edition(&held, &owner, &ch.0, 3, Some([9u8; 32]), "gap", 5_000);
        assert!(follow_control_live(&held, &gap).await.is_none(), "a link the window doesn't hold");

        let fine = live_edition(&held, &owner, &ch.0, 2, v1, "fine", 5_001);
        let mut rotated = held.clone();
        rotated.root_epoch = crate::community::Epoch(held.root_epoch.0 + 1);
        assert!(follow_control_live(&rotated, &fine).await.is_none(), "another epoch's window");
        hold_control(&held, None);
        assert!(follow_control_live(&held, &fine).await.is_none(), "no settled window");

        let after = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        assert_eq!(after.channel(&ch).unwrap().name, name);
        assert_eq!(floor_of(&community, &ch.0).0, 1);
    }

    #[tokio::test]
    async fn a_fork_branch_the_chain_extended_is_followed_not_stranded() {
        // CORD-04 §1 "the highest version whose chain is intact": the admin's v2 lost the
        // tiebreak to the owner's, but v3 was built on the admin's. The head is v3.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let (community, admin) = with_admin(&relay, "ForkExtend", &owner, Permissions::MANAGE_CHANNELS).await;
        let ch = community.channels[0].id;
        let v1 = head_hash_on_relay(&relay, &community, &ch.0).await;
        publish_fork(&[&relay], &community, &owner, vsk::CHANNEL_METADATA, &ch.0, 2, v1, &channel_meta_json("owner-v2"), None).await;
        let admin_v2 = publish_fork(&[&relay], &community, &admin, vsk::CHANNEL_METADATA, &ch.0, 2, v1, &channel_meta_json("admin-v2"), None).await;
        let editions = fetch_control(&relay, &community).await;
        let admin_hash = editions.iter().find(|e| e.inner_id == admin_v2).unwrap().self_hash;
        publish_fork(&[&relay], &community, &admin, vsk::CHANNEL_METADATA, &ch.0, 3, Some(admin_hash), &channel_meta_json("admin-v3"), None).await;

        let updated = follow_control(&relay, &community).await.unwrap().updated.expect("folds");
        assert_eq!(updated.channel(&ch).unwrap().name, "admin-v3", "the extended branch is followed");
        assert_eq!(floor_of(&community, &ch.0).0, 3);
        // A client that had already settled on the owner's v2 follows it too.
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let owner_v2 = editions.iter().find(|e| e.version == 2 && e.author == owner.public_key()).unwrap();
        let ch_hex = crate::simd::hex::bytes_to_hex_32(&ch.0);
        crate::db::community::delete_edition_head(&cid_hex, &ch_hex).unwrap();
        crate::db::community::set_edition_head_at_epoch(&cid_hex, &ch_hex, 2, &owner_v2.self_hash, &owner_v2.inner_id, &owner.public_key().to_bytes(), community.root_epoch.0).unwrap();
        let editions = fetch_control(&relay, &community).await;
        let floors = load_floors(&community);
        let authority = fold_authority(&community, &editions, &floors);
        let fold = apply_control_fold(&community, &editions, &floors, &authority);
        let head = fold.heads.iter().find(|h| h.entity_hex == ch_hex).expect("a head, not a gap");
        assert_eq!(head.version, 3, "the sibling's descendant outranks a dead-end winner");
        assert!(!fold.gapped);
    }

    #[tokio::test]
    async fn a_same_content_copy_does_not_rekey_the_floor_to_a_weaker_author() {
        // The edition hash covers content, not signer: an admin re-signing the owner's exact
        // v2 makes the same hash. Serving only that copy must not lower the floor's bar.
        let (_tmp, _guard, owner) = init_test_db();
        let full = MemoryRelay::new();
        let (community, admin) = with_admin(&full, "ForkCopy", &owner, Permissions::MANAGE_CHANNELS).await;
        let thin = MemoryRelay::new();
        mirror_control(&full, &thin, &community).await;
        let ch = community.channels[0].id;
        let v1 = head_hash_on_relay(&full, &community, &ch.0).await;
        let owner_id = publish_fork(&[&full], &community, &owner, vsk::CHANNEL_METADATA, &ch.0, 2, v1, &channel_meta_json("same"), None).await;
        publish_fork(&[&thin], &community, &admin, vsk::CHANNEL_METADATA, &ch.0, 2, v1, &channel_meta_json("same"), None).await;
        follow_control(&full, &community).await.unwrap();
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        follow_control(&thin, &held).await.unwrap();
        assert_eq!(floor_of(&community, &ch.0), (2, Some(owner_id), Some(owner.public_key().to_bytes())), "the floor keeps the owner's key");
    }

    #[tokio::test]
    async fn a_role_above_its_granter_stays_out_of_reach_when_bundled_with_one_below() {
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Bundled", vec!["wss://r".into()], None).await.unwrap();
        let (moderator, member) = (Keys::generate(), Keys::generate().public_key());
        let (rhigh, rmod, rlow) = ("a1".repeat(32), "a2".repeat(32), "a3".repeat(32));
        for (rid, perms, position) in [(&rhigh, Permissions::ADMIN_ALL, 1), (&rmod, Permissions::MANAGE_ROLES, 2), (&rlow, Permissions::KICK, 3)] {
            let mut role = admin_role(rid, perms);
            role.position = position;
            publish_role(&relay, &community, &owner, &role, 1).await;
        }
        publish_grant(&relay, &community, &owner, &moderator.public_key(), vec![rmod], 1).await;
        let held_by = |community: &CommunityV2| {
            let roles = crate::db::community::get_community_roles(&community.id().to_hex()).unwrap();
            let mut ids: Vec<String> = roles.roles_of(&member.to_hex()).map(|r| r.role_id.clone()).collect();
            ids.sort();
            ids
        };

        publish_grant(&relay, &community, &moderator, &member, vec![rlow.clone()], 1).await;
        follow_control(&relay, &community).await.unwrap();
        assert_eq!(held_by(&community), [rlow.clone()], "a role beneath the granter stands");

        publish_grant(&relay, &community, &moderator, &member, vec![rhigh.clone(), rlow.clone()], 2).await;
        follow_control(&relay, &community).await.unwrap();
        assert_eq!(held_by(&community), [rlow], "the highest role a grant names sets its reach, so the bundle is refused");
    }

    #[tokio::test]
    async fn a_higher_ranked_admin_wins_a_fork_over_a_lower_id_from_a_lesser_admin() {
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "ForkRanks", vec!["wss://r".into()], None).await.unwrap();
        let (senior, junior) = (Keys::generate(), Keys::generate());
        let (rs, rj) = ("e1".repeat(32), "e2".repeat(32));
        let mut junior_role = admin_role(&rj, Permissions::MANAGE_CHANNELS);
        junior_role.position = 2;
        publish_role(&relay, &community, &owner, &admin_role(&rs, Permissions::MANAGE_CHANNELS), 1).await;
        publish_role(&relay, &community, &owner, &junior_role, 1).await;
        publish_grant(&relay, &community, &owner, &senior.public_key(), vec![rs], 1).await;
        publish_grant(&relay, &community, &owner, &junior.public_key(), vec![rj], 1).await;
        let ch = community.channels[0].id;
        let v1 = head_hash_on_relay(&relay, &community, &ch.0).await;
        let senior_id = publish_fork(&[&relay], &community, &senior, vsk::CHANNEL_METADATA, &ch.0, 2, v1, &channel_meta_json("senior-pick"), None).await;
        publish_fork(&[&relay], &community, &junior, vsk::CHANNEL_METADATA, &ch.0, 2, v1, &channel_meta_json("junior-pick"), Some((std::cmp::Ordering::Less, senior_id))).await;
        let updated = follow_control(&relay, &community).await.unwrap().updated.expect("folds");
        assert_eq!(updated.channel(&ch).unwrap().name, "senior-pick", "position 1 outranks position 2 whatever the ids");
    }

    #[tokio::test]
    async fn role_grant_and_banlist_forks_go_to_authority_in_any_order() {
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let (community, admin) = with_admin(&relay, "ForkAuthority", &owner, Permissions::ADMIN_ALL).await;
        // A role beneath the admin, and a member holding it.
        let (rlow, rextra) = ("f1".repeat(32), "f2".repeat(32));
        let mut low = admin_role(&rlow, Permissions::KICK);
        low.position = 5;
        let mut extra = admin_role(&rextra, 0);
        extra.position = 6;
        publish_role(&relay, &community, &owner, &low, 1).await;
        publish_role(&relay, &community, &owner, &extra, 1).await;
        let member = Keys::generate().public_key();
        publish_grant(&relay, &community, &owner, &member, vec![rlow.clone()], 1).await;

        // Role fork at v2.
        let role_eid = crate::simd::hex::hex_to_bytes_32_checked(&rlow).unwrap();
        let rv1 = head_hash_on_relay(&relay, &community, &role_eid).await;
        let named = |name: &str| {
            let mut r = low.clone();
            r.name = name.into();
            crate::community::v2::roles::role_content_json(&r).unwrap()
        };
        let owner_role = publish_fork(&[&relay], &community, &owner, vsk::ROLE, &role_eid, 2, rv1, &named("owner-pick"), None).await;
        publish_fork(&[&relay], &community, &admin, vsk::ROLE, &role_eid, 2, rv1, &named("admin-pick"), Some((std::cmp::Ordering::Less, owner_role))).await;

        // Grant fork at v2.
        let grant_eid = crate::community::v2::derive::grant_locator(community.id(), &member.to_bytes());
        let gv1 = head_hash_on_relay(&relay, &community, &grant_eid).await;
        let grant_json = |ids: Vec<String>| crate::community::v2::roles::grant_content_json_with_wrap(&MemberGrant { member: member.to_hex(), role_ids: ids }, None).unwrap();
        let owner_grant = publish_fork(&[&relay], &community, &owner, vsk::GRANT, &grant_eid, 2, gv1, &grant_json(vec![rlow.clone(), rextra.clone()]), None).await;
        publish_fork(&[&relay], &community, &admin, vsk::GRANT, &grant_eid, 2, gv1, &grant_json(vec![]), Some((std::cmp::Ordering::Less, owner_grant))).await;

        // Banlist fork at v1: each bans a different roleless member.
        let (x, y) = ("aa".repeat(32), "bb".repeat(32));
        let ban_eid = crate::community::v2::derive::banlist_locator(community.id());
        let ban_json = |t: &str| crate::community::v2::roles::banlist_content_json(&[t.to_string()]).unwrap();
        let owner_ban = publish_fork(&[&relay], &community, &owner, vsk::BANLIST, &ban_eid, 1, None, &ban_json(&x), None).await;
        publish_fork(&[&relay], &community, &admin, vsk::BANLIST, &ban_eid, 1, None, &ban_json(&y), Some((std::cmp::Ordering::Less, owner_ban))).await;

        let editions = fetch_control(&relay, &community).await;
        let floors = load_floors(&community);
        for set in [editions.clone(), editions.iter().rev().cloned().collect::<Vec<_>>()] {
            let a = fold_authority(&community, &set, &floors);
            assert_eq!(a.roles.role(&rlow).unwrap().name, "owner-pick", "role fork");
            let mut held = a.roles.grants.iter().find(|g| g.member == member.to_hex()).expect("the owner's grant stands").role_ids.clone();
            held.sort();
            assert_eq!(held, vec![rlow.clone(), rextra.clone()], "grant fork");
            assert!(a.banned.contains(&x) && !a.banned.contains(&y), "banlist fork");
            let head = |eid: &[u8; 32]| a.heads.iter().find(|h| h.entity_hex == crate::simd::hex::bytes_to_hex_32(eid)).map(|h| h.inner_id);
            assert_eq!((head(&role_eid), head(&grant_eid), head(&ban_eid)), (Some(owner_role), Some(owner_grant), Some(owner_ban)));
        }
    }

    #[tokio::test]
    async fn a_withheld_owner_role_head_is_not_replaced_by_a_served_admin_sibling() {
        let (_tmp, _guard, owner) = init_test_db();
        let full = MemoryRelay::new();
        let community = create_community(&full, "RoleHold", vec!["wss://r".into()], None).await.unwrap();
        let admin = Keys::generate();
        let (radmin, rlow) = ("d1".repeat(32), "f1".repeat(32));
        let mut low = admin_role(&rlow, Permissions::KICK);
        low.position = 5;
        publish_role(&full, &community, &owner, &admin_role(&radmin, Permissions::ADMIN_ALL), 1).await;
        publish_grant(&full, &community, &owner, &admin.public_key(), vec![radmin.clone()], 1).await;
        publish_role(&full, &community, &owner, &low, 1).await;
        // The thin relay gets everything the full one has so far.
        let thin = MemoryRelay::new();
        let group = control::ControlPlane::of(&community).write_group().unwrap();
        let query = Query { kinds: vec![stream::KIND_WRAP], authors: vec![group.pk_hex()], limit: Some(500), ..Default::default() };
        for w in full.fetch(&query, &community.relays).await.unwrap() {
            thin.publish(&w, &community.relays).await.unwrap();
        }
        let role_eid = crate::simd::hex::hex_to_bytes_32_checked(&rlow).unwrap();
        let rv1 = head_hash_on_relay(&full, &community, &role_eid).await;
        let named = |name: &str| {
            let mut r = low.clone();
            r.name = name.into();
            crate::community::v2::roles::role_content_json(&r).unwrap()
        };
        let owner_id = publish_fork(&[&full], &community, &owner, vsk::ROLE, &role_eid, 2, rv1, &named("owner-pick"), None).await;
        let admin_id = publish_fork(&[&full, &thin], &community, &admin, vsk::ROLE, &role_eid, 2, rv1, &named("admin-pick"), Some((std::cmp::Ordering::Less, owner_id))).await;
        follow_control(&full, &community).await.unwrap();
        assert_eq!(floor_of(&community, &role_eid).1, Some(owner_id));

        let editions = fetch_control(&thin, &community).await;
        let a = fold_authority(&community, &editions, &load_floors(&community));
        let head = a.heads.iter().find(|h| h.entity_hex == rlow).map(|h| h.inner_id);
        assert_ne!(head, Some(admin_id), "the admin's sibling never heads over the held owner edition");
        assert_ne!(a.roles.role(&rlow).map(|r| r.name.as_str()), Some("admin-pick"));
    }

    /// Owner grants a senior admin (position 1) and a junior admin (position 2), both full
    /// admins, plus a role beneath both held by a member.
    async fn two_admins(relay: &MemoryRelay, name: &str, owner: &Keys) -> (CommunityV2, Keys, Keys, String, PublicKey) {
        let community = create_community(relay, name, vec!["wss://r".into()], None).await.unwrap();
        let (senior, junior) = (Keys::generate(), Keys::generate());
        let (rs, rj, rlow) = ("e1".repeat(32), "e2".repeat(32), "f1".repeat(32));
        let mut jr = admin_role(&rj, Permissions::ADMIN_ALL);
        jr.position = 2;
        let mut low = admin_role(&rlow, Permissions::KICK);
        low.position = 5;
        publish_role(relay, &community, owner, &admin_role(&rs, Permissions::ADMIN_ALL), 1).await;
        publish_role(relay, &community, owner, &jr, 1).await;
        publish_role(relay, &community, owner, &low, 1).await;
        publish_grant(relay, &community, owner, &senior.public_key(), vec![rs], 1).await;
        publish_grant(relay, &community, owner, &junior.public_key(), vec![rj], 1).await;
        let member = Keys::generate().public_key();
        publish_grant(relay, &community, owner, &member, vec![rlow.clone()], 1).await;
        (community, senior, junior, rlow, member)
    }

    #[tokio::test]
    async fn admin_versus_admin_role_grant_and_banlist_forks_go_to_the_higher_position() {
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let (community, senior, junior, rlow, member) = two_admins(&relay, "ForkPositions", &owner).await;
        let low_eid = crate::simd::hex::hex_to_bytes_32_checked(&rlow).unwrap();
        let rv1 = head_hash_on_relay(&relay, &community, &low_eid).await;
        let named = |name: &str| {
            let mut r = admin_role(&rlow, Permissions::KICK);
            r.position = 5;
            r.name = name.into();
            crate::community::v2::roles::role_content_json(&r).unwrap()
        };
        let senior_role = publish_fork(&[&relay], &community, &senior, vsk::ROLE, &low_eid, 2, rv1, &named("senior-pick"), None).await;
        publish_fork(&[&relay], &community, &junior, vsk::ROLE, &low_eid, 2, rv1, &named("junior-pick"), Some((std::cmp::Ordering::Less, senior_role))).await;

        let grant_eid = crate::community::v2::derive::grant_locator(community.id(), &member.to_bytes());
        let gv1 = head_hash_on_relay(&relay, &community, &grant_eid).await;
        let grant_json = |ids: Vec<String>| crate::community::v2::roles::grant_content_json_with_wrap(&MemberGrant { member: member.to_hex(), role_ids: ids }, None).unwrap();
        let senior_grant = publish_fork(&[&relay], &community, &senior, vsk::GRANT, &grant_eid, 2, gv1, &grant_json(vec![rlow.clone()]), None).await;
        publish_fork(&[&relay], &community, &junior, vsk::GRANT, &grant_eid, 2, gv1, &grant_json(vec![]), Some((std::cmp::Ordering::Less, senior_grant))).await;

        let (x, y) = ("aa".repeat(32), "bb".repeat(32));
        let ban_eid = crate::community::v2::derive::banlist_locator(community.id());
        let ban_json = |t: &str| crate::community::v2::roles::banlist_content_json(&[t.to_string()]).unwrap();
        let senior_ban = publish_fork(&[&relay], &community, &senior, vsk::BANLIST, &ban_eid, 1, None, &ban_json(&x), None).await;
        publish_fork(&[&relay], &community, &junior, vsk::BANLIST, &ban_eid, 1, None, &ban_json(&y), Some((std::cmp::Ordering::Less, senior_ban))).await;

        let editions = fetch_control(&relay, &community).await;
        let floors = load_floors(&community);
        for set in [editions.clone(), editions.iter().rev().cloned().collect::<Vec<_>>()] {
            let a = fold_authority(&community, &set, &floors);
            assert_eq!(a.roles.role(&rlow).unwrap().name, "senior-pick", "role fork");
            assert_eq!(a.roles.grants.iter().find(|g| g.member == member.to_hex()).map(|g| g.role_ids.clone()), Some(vec![rlow.clone()]), "grant fork");
            assert!(a.banned.contains(&x) && !a.banned.contains(&y), "banlist fork");
        }
    }

    #[tokio::test]
    async fn a_withheld_owner_grant_head_is_not_replaced_by_a_served_admin_revocation() {
        let (_tmp, _guard, owner) = init_test_db();
        let full = MemoryRelay::new();
        let (community, _senior, junior, rlow, member) = two_admins(&full, "GrantHold", &owner).await;
        let thin = MemoryRelay::new();
        mirror_control(&full, &thin, &community).await;
        let grant_eid = crate::community::v2::derive::grant_locator(community.id(), &member.to_bytes());
        let gv1 = head_hash_on_relay(&full, &community, &grant_eid).await;
        let grant_json = |ids: Vec<String>| crate::community::v2::roles::grant_content_json_with_wrap(&MemberGrant { member: member.to_hex(), role_ids: ids }, None).unwrap();
        let owner_id = publish_fork(&[&full], &community, &owner, vsk::GRANT, &grant_eid, 2, gv1, &grant_json(vec![rlow.clone()]), None).await;
        let junior_id = publish_fork(&[&full, &thin], &community, &junior, vsk::GRANT, &grant_eid, 2, gv1, &grant_json(vec![]), Some((std::cmp::Ordering::Less, owner_id))).await;
        follow_control(&full, &community).await.unwrap();
        assert_eq!(floor_of(&community, &grant_eid).1, Some(owner_id));

        let editions = fetch_control(&thin, &community).await;
        let a = fold_authority(&community, &editions, &load_floors(&community));
        let head = a.heads.iter().find(|h| h.entity_hex == crate::simd::hex::bytes_to_hex_32(&grant_eid)).map(|h| h.inner_id);
        assert_ne!(head, Some(junior_id), "the junior's revocation never heads over the held owner grant");
        // Without the guard the junior's empty grant would stand: prove it is admissible on its own.
        let mut unfloored = load_floors(&community);
        unfloored.remove(&crate::simd::hex::bytes_to_hex_32(&grant_eid));
        let free = fold_authority(&community, &editions, &unfloored);
        assert_eq!(free.heads.iter().find(|h| h.entity_hex == crate::simd::hex::bytes_to_hex_32(&grant_eid)).map(|h| h.inner_id), Some(junior_id));
    }

    #[test]
    fn a_held_key_ranks_rivals_by_what_the_row_recorded() {
        let (lo, hi) = ([1u8; 32], [9u8; 32]);
        let floor = |inner, author| -> Floor { (2, [0u8; 32], inner, author, None) };
        let owner_ranked = |_: &[u8; 32]| 0u32;
        assert!(HeldKey::of(&floor(None, None), &owner_ranked).beaten_by(u32::MAX, &hi), "an unkeyed row yields to anyone");
        let legacy = HeldKey::of(&floor(Some(hi), None), &owner_ranked);
        assert!(legacy.beaten_by(u32::MAX, &lo) && !legacy.beaten_by(0, &[0xFF; 32]), "a row without an author compares ids only");
        let ranked = HeldKey::of(&floor(Some(hi), Some([7u8; 32])), &owner_ranked);
        assert!(!ranked.beaten_by(1, &lo), "the owner's held head beats a lower-id admin");
        assert!(ranked.beaten_by(0, &lo), "and loses only to a lower id at the same rank");
    }

    /// A canonical (order-independent) fingerprint of an AuthoritySet's authorized
    /// roster + banlist — two clients converge iff these match.
    fn authority_fingerprint(a: &AuthoritySet) -> String {
        let mut roles = a.roles.roles.clone();
        roles.sort_by(|x, y| x.role_id.cmp(&y.role_id));
        let mut grants = a.roles.grants.clone();
        for g in &mut grants {
            g.role_ids.sort();
        }
        grants.sort_by(|x, y| x.member.cmp(&y.member));
        let banned: Vec<&String> = a.banned.iter().collect();
        serde_json::json!({ "roles": roles, "grants": grants, "banned": banned }).to_string()
    }

    fn folded_role<'a>(view: &'a AuthorityView, id: &str) -> &'a crate::community::roles::Role {
        view.roles.role(id).unwrap_or_else(|| panic!("role {id} folded"))
    }

    #[tokio::test]
    async fn roles_are_created_at_the_bottom_edited_in_place_and_reordered() {
        use crate::community::roles::{Permissions, RoleScope};
        let (bed, owner, _m) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Roles", bed.relays.clone(), None).await.unwrap();

        let a = create_role(&bed.relay, &community, "Alpha", 0, Permissions::KICK, RoleScope::Server).await.unwrap();
        let b = create_role(&bed.relay, &community, "Beta", 0, 0, RoleScope::Server).await.unwrap();
        let c = create_role(&bed.relay, &community, "Gamma", 0, 0, RoleScope::Server).await.unwrap();
        let view = fetch_authority(&bed.relay, &community).await;
        let pos = |v: &AuthorityView, id: &str| folded_role(v, id).position;
        assert!(pos(&view, &a) < pos(&view, &b) && pos(&view, &b) < pos(&view, &c), "each new role lands beneath the last");
        assert!(pos(&view, &a) >= 1, "no role claims the owner's position");

        edit_role(&bed.relay, &community, &b, "Beta Prime", 0x59fcb3, Permissions::BAN, RoleScope::Server).await.unwrap();
        let view = fetch_authority(&bed.relay, &community).await;
        let edited = folded_role(&view, &b);
        assert_eq!((edited.name.as_str(), edited.color, edited.permissions.0), ("Beta Prime", 0x59fcb3, Permissions::BAN));
        assert_eq!(edited.position, pos(&view, &b), "an edit keeps the role where it was");

        let moved = reorder_roles(&bed.relay, &community, &[c.clone(), a.clone(), b.clone()]).await.unwrap();
        assert_eq!(moved, 3, "every role whose position changed is republished");
        let view = fetch_authority(&bed.relay, &community).await;
        assert!(pos(&view, &c) < pos(&view, &a) && pos(&view, &a) < pos(&view, &b), "the fold holds the requested order");
        assert_eq!(pos(&view, &c), 1, "renumbered from just beneath the owner");

        let again = reorder_roles(&bed.relay, &community, &[c, a, b]).await.unwrap();
        assert_eq!(again, 0, "the same order again publishes nothing");
    }

    #[tokio::test]
    async fn new_roles_stack_above_the_access_band_and_never_share_a_position() {
        use crate::community::roles::{Permissions, RoleScope};
        let (bed, owner, _m) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Band", bed.relays.clone(), None).await.unwrap();
        create_private_channel(&bed.relay, &community, "secret").await.unwrap();
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let a = create_role(&bed.relay, &held, "A", 0, Permissions::empty().0, RoleScope::Server).await.unwrap();
        let b = create_role(&bed.relay, &held, "B", 0, Permissions::empty().0, RoleScope::Server).await.unwrap();
        let view = fetch_authority(&bed.relay, &held).await;
        let (pa, pb) = (folded_role(&view, &a).position, folded_role(&view, &b).position);
        assert!(pa < pb, "each new role lands beneath the last");
        assert!(pb < ACCESS_ROLE_POSITION, "and above the access band, never in the slot beneath it");
    }

    #[tokio::test]
    async fn a_members_role_set_is_written_whole_and_the_owner_holds_roles_for_display_alone() {
        use crate::community::roles::{Permissions, RoleScope};
        let (bed, owner, _m) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Grants", bed.relays.clone(), None).await.unwrap();
        let a = create_role(&bed.relay, &community, "A", 0, Permissions::KICK, RoleScope::Server).await.unwrap();
        let b = create_role(&bed.relay, &community, "B", 0, 0, RoleScope::Server).await.unwrap();
        let admin_role = create_role(&bed.relay, &community, "Admin", 0, Permissions::MANAGE_ROLES, RoleScope::Server).await.unwrap();
        let below = create_role(&bed.relay, &community, "Below", 0, 0, RoleScope::Server).await.unwrap();
        let lowest = create_role(&bed.relay, &community, "Lowest", 0, 0, RoleScope::Server).await.unwrap();
        let member = Keys::generate().public_key();

        set_member_roles(&bed.relay, &community, &member, vec![a.clone(), b.clone()]).await.unwrap();
        let view = fetch_authority(&bed.relay, &community).await;
        let held: Vec<String> = view.roles.roles_of(&member.to_hex()).map(|r| r.role_id.clone()).collect();
        assert!(held.contains(&a) && held.contains(&b), "both roles granted");

        set_member_roles(&bed.relay, &community, &member, vec![b.clone()]).await.unwrap();
        let view = fetch_authority(&bed.relay, &community).await;
        let held: Vec<String> = view.roles.roles_of(&member.to_hex()).map(|r| r.role_id.clone()).collect();
        assert_eq!(held, vec![b.clone()], "the set replaces, it does not append");

        // The owner may hold Roles, for display alone, on the new roles (CORD-04 §3).
        let owner_pk = owner.keys.public_key();
        let owner_hex = owner_pk.to_hex();
        let err = set_member_roles(&bed.relay, &community, &owner_pk, vec![below.clone()]).await.unwrap_err();
        assert!(err.contains("new roles"), "not on the legacy roles: {err}");
        activate_roles_v2(&bed.relay, &community, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
        let community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        set_member_roles(&bed.relay, &community, &owner_pk, vec![below.clone()]).await.unwrap();
        let view = fetch_authority(&bed.relay, &community).await;
        let held: Vec<String> = view.roles.roles_of(&owner_hex).map(|r| r.role_id.clone()).collect();
        assert_eq!(held, vec![below.clone()], "the owner holds the role they gave themselves");
        assert!(view.roles.outranks(&owner_hex, Some(&owner_hex), 1), "and still outranks every role");
        assert_eq!(fork_rank(&view.roles, Some(&owner_hex), &owner_hex), 0, "their rank stays the owner's");

        // Nobody else's Grant names the owner, even an admin above every Role it touches.
        let admin = Keys::generate();
        publish_grant(&bed.relay, &community, &owner.keys, &admin.public_key(), vec![admin_role], 1).await;
        publish_grant(&bed.relay, &community, &admin, &owner_pk, vec![below.clone(), lowest.clone()], 2).await;
        let view = fetch_authority(&bed.relay, &community).await;
        let held: Vec<String> = view.roles.roles_of(&owner_hex).map(|r| r.role_id.clone()).collect();
        assert_eq!(held, vec![below.clone()], "an admin's Grant naming the owner is refused");
        let other = Keys::generate().public_key();
        publish_grant(&bed.relay, &community, &admin, &other, vec![below.clone(), lowest], 1).await;
        let view = fetch_authority(&bed.relay, &community).await;
        assert_eq!(view.roles.roles_of(&other.to_hex()).count(), 2, "the same Grant stands for anyone else");
    }

    #[tokio::test]
    async fn losing_the_last_role_that_opens_a_channel_rotates_it_and_keeping_one_does_not() {
        use crate::community::roles::{Permissions, RoleScope};
        let (bed, owner, _m) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Keys", bed.relays.clone(), None).await.unwrap();
        let chan = create_private_channel(&bed.relay, &community, "secret").await.unwrap();
        let chan_hex = crate::simd::hex::bytes_to_hex_32(&chan.0);
        let reload = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let epoch = |c: &CommunityV2| c.channel(&chan).unwrap().epoch.0;

        let held = reload();
        let access = fetch_authority(&bed.relay, &held).await.roles.channel_role_ids(&chan_hex);
        assert!(!access.is_empty(), "the private channel came with its access role");
        let second = create_role(&bed.relay, &held, "Also Secret", 0, Permissions::empty().0, RoleScope::Channel(chan_hex.clone())).await.unwrap();
        let member = Keys::generate().public_key();

        set_member_roles(&bed.relay, &reload(), &member, vec![access[0].clone(), second.clone()]).await.unwrap();
        let start = epoch(&reload());

        // Drop one of the two: still entitled, so nobody is cut and nothing rotates.
        set_member_roles(&bed.relay, &reload(), &member, vec![second.clone()]).await.unwrap();
        assert_eq!(epoch(&reload()), start, "a kept role still opens the channel");

        // Drop the last: the channel rotates without them.
        set_member_roles(&bed.relay, &reload(), &member, vec![]).await.unwrap();
        assert_eq!(epoch(&reload()), start + 1, "losing the last access role severs them");
    }

    #[test]
    fn a_role_author_carries_only_bits_they_hold_and_acts_only_beneath_themselves() {
        use crate::community::roles::{CommunityRoles, MemberGrant, Permissions, Role, RoleScope};
        let role = |id: &str, position: u32, bits: u64| Role { role_id: id.into(), name: id.into(), position, permissions: Permissions(bits), scope: RoleScope::Server, color: 0, rank: None, display: false, mentionable: false, extra: Default::default() };
        // A moderator at 3 holding MANAGE_ROLES|KICK, plus a low role at 8 carrying BAN.
        let roles = CommunityRoles {
            roles: vec![role("mod", 3, Permissions::MANAGE_ROLES | Permissions::KICK), role("low", 8, Permissions::BAN)],
            grants: vec![MemberGrant { member: "m".into(), role_ids: vec!["mod".into(), "low".into()] }],
            everyone: None,
            overwrites: Vec::new(), syncs: Default::default(), legacy_channels: None, creators: Default::default(),
        };
        let moderator = RoleAuthor { me_hex: "m".into(), owner_hex: "o".into(), is_owner: false, rank: 3, roles };
        assert!(moderator.supports(4, Permissions::KICK), "a bit they hold, beneath them");
        assert!(moderator.supports(4, 0), "or none at all");
        assert!(!moderator.supports(4, Permissions::BAN), "BAN comes only from a role beneath 4, so it can't support acting there");
        assert!(moderator.supports(9, Permissions::BAN), "but it does beneath that role");
        assert!(!moderator.supports(3, 0), "never at their own position");
        assert!(moderator.outranks(4) && !moderator.outranks(3) && !moderator.outranks(1), "strictly beneath only");
        let owner = RoleAuthor { is_owner: true, rank: 0, ..moderator };
        assert!(owner.supports(1, u64::MAX) && owner.outranks(1));
    }

    /// Everything a fold decides, as one comparable string.
    fn authority_whole(a: &AuthoritySet) -> String {
        let mut admitted: Vec<String> = a.admitted.iter().map(crate::simd::hex::bytes_to_hex_32).collect();
        admitted.sort();
        format!("{} refused={:?} carried={:?} admitted={admitted:?} gapped={} complete={}", authority_and_heads(a), a.refused, a.carried, a.gapped, a.complete)
    }

    /// The roster, banlist and the heads a follow would floor, as one comparable string.
    fn authority_and_heads(a: &AuthoritySet) -> String {
        let mut heads: Vec<_> = a.heads.iter().map(|h| (h.entity_hex.clone(), h.version, crate::simd::hex::bytes_to_hex_32(&h.self_hash), crate::simd::hex::bytes_to_hex_32(&h.inner_id), h.rebased)).collect();
        heads.sort();
        format!("{} heads={heads:?} converged={}", authority_fingerprint(a), a.converged)
    }

    #[test]
    fn hash_groups_list_each_hash_in_index_order_whatever_came_before() {
        let mut seed = 0x2545_f491_4f6c_dd1du64;
        let mut next = move |n: u64| {
            seed ^= seed << 13;
            seed ^= seed >> 7;
            seed ^= seed << 17;
            seed % n
        };
        let mut groups = HashGroups::default();
        for _ in 0..200 {
            let n = next(12) as usize;
            let hashes: Vec<[u8; 32]> = (0..n).map(|_| [next(4) as u8; 32]).collect();
            groups.build(n, |j| hashes[j]);
            let mut want: std::collections::HashMap<[u8; 32], Vec<usize>> = Default::default();
            for (j, h) in hashes.iter().enumerate() {
                want.entry(*h).or_default().push(j);
            }
            for h in (0..5u8).map(|b| [b; 32]) {
                assert_eq!(groups.get(&h), want.get(&h).map(|v| v.as_slice()), "{hashes:?}");
            }
        }
    }

    #[tokio::test]
    async fn random_control_planes_fold_alike_in_any_order_and_for_a_reader_holding_its_heads() {
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Random planes", vec!["wss://r".into()], None).await.unwrap();
        let group = control::ControlPlane::of(&community).write_group().unwrap();
        let cid = community.id();
        let actors: Vec<Keys> = (0..4).map(|_| Keys::generate()).collect();
        let mut signers = vec![owner.clone()];
        signers.extend(actors.iter().cloned());
        let roles: Vec<String> = (1..=3u8).map(|i| crate::simd::hex::bytes_to_hex_32(&[i; 32])).collect();
        let mut seed = 0x9e37_79b9_7f4a_7c15u64;
        let mut next = move |n: u64| {
            seed ^= seed << 13;
            seed ^= seed >> 7;
            seed ^= seed << 17;
            seed % n
        };
        let perms: [u64; 5] = [Permissions::MANAGE_ROLES | Permissions::BAN, Permissions::MANAGE_ROLES, Permissions::BAN, Permissions::KICK, 0];
        let mut failures: Vec<String> = Vec::new();
        for case in 0..400 {
            // Entities: three Roles, a Grant per actor, the Banlist.
            let mut entities: Vec<([u8; 32], &str)> = roles.iter().map(|r| (crate::simd::hex::hex_to_bytes_32(r), vsk::ROLE)).collect();
            entities.extend(actors.iter().map(|a| (crate::community::v2::derive::grant_locator(cid, &a.public_key().to_bytes()), vsk::GRANT)));
            entities.push((crate::community::v2::derive::banlist_locator(cid), vsk::BANLIST));
            let mut eds: Vec<ParsedEdition> = Vec::new();
            // Grants written so far by entity: what a citation can name.
            let mut written: std::collections::HashMap<[u8; 32], Vec<(u64, [u8; 32])>> = Default::default();
            // Interleave entities by version, so a citation can name what came before it.
            let lens: Vec<u64> = entities.iter().map(|_| 1 + next(3)).collect();
            let mut at_version: std::collections::HashMap<[u8; 32], Vec<[u8; 32]>> = Default::default();
            // Every entity's editions one version down: what a link aimed at another entity names.
            let mut any_below: Vec<[u8; 32]> = Vec::new();
            for v in 1..=3u64 {
                let mut any_here: Vec<[u8; 32]> = Vec::new();
                for (k, (eid, kind)) in entities.iter().enumerate() {
                    if v > lens[k] {
                        continue;
                    }
                    let below = at_version.get(eid).cloned().unwrap_or_default();
                    let mut here = Vec::new();
                    for _ in 0..(1 + u64::from(next(4) == 0)) {
                        let signer = if next(2) == 0 { &signers[0] } else { &signers[1 + next(4) as usize] };
                        let prev = match (v, next(7)) {
                            (1, _) => None,
                            (_, 0) => Some([0xee; 32]),
                            (_, 1) if !any_below.is_empty() => Some(any_below[next(any_below.len() as u64) as usize]),
                            _ if below.is_empty() => None,
                            _ => Some(below[next(below.len() as u64) as usize]),
                        };
                        let content = match *kind {
                            vsk::ROLE => {
                                let rid = crate::simd::hex::bytes_to_hex_32(eid);
                                let mut r = admin_role(&rid, perms[next(perms.len() as u64) as usize]);
                                r.position = 1 + next(4) as u32;
                                crate::community::v2::roles::role_content_json(&r).unwrap()
                            }
                            vsk::GRANT => {
                                let member = actors.iter().find(|a| crate::community::v2::derive::grant_locator(cid, &a.public_key().to_bytes()) == *eid).unwrap();
                                let role_ids = roles.iter().filter(|_| next(2) == 0).cloned().collect();
                                crate::community::v2::roles::grant_content_json(&MemberGrant { member: member.public_key().to_hex(), role_ids }).unwrap()
                            }
                            _ => {
                                let banned: Vec<String> = actors.iter().filter(|_| next(3) == 0).map(|a| a.public_key().to_hex()).collect();
                                crate::community::v2::roles::banlist_content_json(&banned).unwrap()
                            }
                        };
                        let own = crate::community::v2::derive::grant_locator(cid, &signer.public_key().to_bytes());
                        let cite = match (signer.public_key() == owner.public_key(), next(3), written.get(&own)) {
                            (true, ..) | (_, 0, _) => None,
                            (_, 1, Some(held)) if !held.is_empty() => {
                                let (version, edition_hash) = held[next(held.len() as u64) as usize];
                                Some(crate::community::edition::AuthorityCitation { entity_id: own, version, edition_hash })
                            }
                            _ => Some(crate::community::edition::AuthorityCitation { entity_id: own, version: 1, edition_hash: [0xcc; 32] }),
                        };
                        let ts = 1_000 + next(3);
                        let rumor = control::build_edition_rumor(signer.public_key(), kind, eid, v, prev.as_ref(), &content, ts, cite.as_ref());
                        let (wrap, _) = control::seal_control_edition(&rumor, &group, signer, Timestamp::from_secs(ts)).unwrap();
                        let (ed, _) = control::open_control_edition(&wrap, &group).unwrap();
                        here.push(ed.self_hash);
                        if *kind == vsk::GRANT {
                            written.entry(*eid).or_default().push((v, ed.self_hash));
                        }
                        eds.push(ed);
                        // A copy of it under another signer: the same hash, on that signer's authority.
                        if next(3) == 0 {
                            let copier = &signers[next(signers.len() as u64) as usize];
                            let rumor = control::build_edition_rumor(copier.public_key(), kind, eid, v, prev.as_ref(), &content, ts + 1, None);
                            let (wrap, _) = control::seal_control_edition(&rumor, &group, copier, Timestamp::from_secs(ts + 1)).unwrap();
                            eds.push(control::open_control_edition(&wrap, &group).unwrap().0);
                        }
                    }
                    any_here.extend(&here);
                    at_version.insert(*eid, here);
                }
                any_below = any_here;
            }
            let base = fold_authority(&community, &eds, &Floors::default());
            let want = authority_and_heads(&base);
            for order in 0..4 {
                let mut shuffled = eds.clone();
                for i in (1..shuffled.len()).rev() {
                    shuffled.swap(i, next(i as u64 + 1) as usize);
                }
                let got = authority_and_heads(&fold_authority(&community, &shuffled, &Floors::default()));
                if got != want {
                    failures.push(format!("case {case} order {order}:\n  want {want}\n   got {got}"));
                }
            }
            // A reader holding exactly the heads it decided folds them again.
            let floors: Floors = base.heads.iter().map(|h| (h.entity_hex.clone(), (h.version, h.self_hash, Some(h.inner_id), Some(h.author), None))).collect();
            let tracked = authority_fingerprint(&fold_authority(&community, &eds, &floors));
            if tracked != authority_fingerprint(&base) {
                failures.push(format!("case {case} tracking:\n  fresh {}\n  held  {tracked}", authority_fingerprint(&base)));
            }
            // A reader holding any served edition of each entity, refused ones among them.
            let mut held: Floors = Floors::default();
            for (eid, _) in &entities {
                let of: Vec<&ParsedEdition> = eds.iter().filter(|e| e.entity_id == *eid).collect();
                if !of.is_empty() && next(4) != 0 {
                    let e = of[next(of.len() as u64) as usize];
                    held.insert(crate::simd::hex::bytes_to_hex_32(eid), (e.version, e.self_hash, Some(e.inner_id), Some(e.author.to_bytes()), None));
                }
            }
            // Every fold above again with fresh scratch per entity, as replay ran before reusing it.
            for (label, f) in [("floorless", Floors::default()), ("tracking", floors.clone()), ("holding", held)] {
                let reused = authority_whole(&fold_authority(&community, &eds, &f));
                FRESH_SCRATCH.with(|x| x.set(true));
                let fresh = authority_whole(&fold_authority(&community, &eds, &f));
                FRESH_SCRATCH.with(|x| x.set(false));
                if reused != fresh {
                    failures.push(format!("case {case} scratch {label}:\n  fresh  {fresh}\n  reused {reused}"));
                }
            }
        }
        assert!(failures.is_empty(), "{} of 400 cases folded differently:\n{}", failures.len(), failures.join("\n"));
    }

    #[tokio::test]
    async fn the_v2_authority_fold_is_order_independent() {
        // THE core consensus property: two honest clients that receive the SAME
        // control editions in DIFFERENT arrival orders must resolve the IDENTICAL
        // authorized roster + banlist (author-aware select_authorized + banlist
        // fold + cap, all deterministic). A divergence here would fork the
        // community's moderation state between honest members.
        let (bed, owner, _a) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Determinism", bed.relays.clone(), None).await.unwrap();

        // A rich control plane: two admins, an extra role, two grants (one of them a
        // grant to a member the owner then bans), a banlist, a rename, a channel.
        let admin1 = Keys::generate().public_key();
        let admin2 = Keys::generate().public_key();
        grant_admin(&bed.relay, &community, &admin1).await.unwrap();
        grant_admin(&bed.relay, &community, &admin2).await.unwrap();
        let mod_rid = "5c".repeat(32);
        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&mod_rid, Permissions::KICK | Permissions::MANAGE_MESSAGES), 1).await;
        let member = Keys::generate().public_key();
        publish_grant(&bed.relay, &community, &owner.keys, &member, vec![mod_rid.clone()], 1).await;
        let banned_member = Keys::generate().public_key();
        publish_grant(&bed.relay, &community, &owner.keys, &banned_member, vec![mod_rid], 1).await;
        set_banlist(&bed.relay, &community, &[banned_member.to_hex()]).await.unwrap();
        let meta = control::CommunityMetadata { name: "Renamed".into(), relays: community.relays.clone(), ..Default::default() };
        edit_community_metadata(&bed.relay, &community, &meta).await.unwrap();
        create_public_channel(&bed.relay, &community, "extra").await.unwrap();

        let editions = fetch_control(&bed.relay, &community).await;
        let floors = load_floors(&community);
        assert!(editions.len() >= 6, "a rich plane was built ({} editions)", editions.len());

        let baseline = authority_fingerprint(&fold_authority(&community, &editions, &floors));

        // Fold under many arrival permutations: reversed, and several deterministic
        // rotations/interleavings. Every one must match the baseline.
        let mut orders: Vec<Vec<ParsedEdition>> = Vec::new();
        let mut rev = editions.clone();
        rev.reverse();
        orders.push(rev);
        for shift in [1usize, 3, 5, 7] {
            let n = editions.len();
            orders.push((0..n).map(|i| editions[(i + shift) % n].clone()).collect());
        }
        // A deterministic "shuffle": interleave from both ends.
        let mut zip = Vec::with_capacity(editions.len());
        let (mut lo, mut hi) = (0isize, editions.len() as isize - 1);
        while lo <= hi {
            zip.push(editions[lo as usize].clone());
            if lo != hi {
                zip.push(editions[hi as usize].clone());
            }
            lo += 1;
            hi -= 1;
        }
        orders.push(zip);

        for (i, order) in orders.iter().enumerate() {
            let got = authority_fingerprint(&fold_authority(&community, order, &floors));
            assert_eq!(got, baseline, "arrival order #{i} must resolve the identical authority (consensus)");
        }
        // Sanity: the fingerprint reflects real state (the banned member is out, the
        // honest admins are in).
        assert!(baseline.contains(&admin1.to_hex()) || baseline.contains(&member.to_hex()), "grants are present in the fingerprint");
        assert!(baseline.contains(&banned_member.to_hex()), "the banlist entry is in the fingerprint");
    }

    /// A transport that ACKs publishes but ERRORS every fetch — a relay outage / withhold.
    struct FetchErrors(MemoryRelay);
    #[async_trait::async_trait]
    impl crate::community::transport::Transport for FetchErrors {
        async fn fetch_plane(&self, _plane: &Keys, query: &Query, relays: &[String]) -> Result<crate::community::transport::PlaneFetch, String> { Ok(crate::community::transport::PlaneFetch::whole(self.fetch(query, relays).await?)) }
        async fn publish(&self, e: &Event, r: &[String]) -> Result<(), String> {
            self.0.publish(e, r).await
        }
        async fn fetch(&self, _q: &Query, _r: &[String]) -> Result<Vec<Event>, String> {
            Err("relay down".to_string())
        }
        async fn publish_durable(&self, e: &Event, r: &[String]) -> Result<(), String> {
            self.0.publish_durable(e, r).await
        }
    }

    #[tokio::test]
    async fn fetch_authority_retains_the_persisted_banlist_on_a_transport_error() {
        let (bed, owner, victim) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "BanRetain", bed.relays.clone(), None).await.unwrap();
        let victim_hex = victim.keys.public_key().to_hex();
        // A ban is persisted locally (as a completed set_banlist + follow leaves it).
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        crate::db::community::set_community_banlist(&cid_hex, &[victim_hex.clone()], 1).unwrap();

        // A relay that ERRORS on fetch must degrade FAIL-SAFE: retain the ban, never
        // return an empty banlist (which would silently un-ban on withheld data).
        let down = FetchErrors(MemoryRelay::new());
        let view = fetch_authority(&down, &community).await;
        assert!(view.banned.contains(&victim_hex), "a transport error retains the persisted banlist");
    }

    #[tokio::test]
    async fn the_fold_pages_past_a_full_window_to_find_the_roster_it_tracks() {
        // Soapbox's actual shape. The grants that define the admin list are OLDER than
        // one page of a busy control plane. An entity absent from the window dangles no
        // link, so it raises no gap, so the pager called the very first page "coherent"
        // and stopped — every fold offered zero grants, forever, and only the
        // completeness guard retaining the cache kept the admin list alive. That made
        // the cache the last surviving copy of the roster rather than a cache.
        //
        // Coherent is not complete. The fold must page until what it tracks is found.
        let (bed, owner, _m) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "DeepFold", bed.relays.clone(), None).await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let rid = "e7".repeat(32);
        let admin = Keys::generate();

        // The roster, at t=1_000 — the OLDEST thing on the plane.
        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN), 1).await;
        publish_grant(&bed.relay, &community, &owner.keys, &admin.public_key(), vec![rid.clone()], 1).await;
        follow_control(&bed.relay, &community).await.unwrap();
        assert!(
            crate::db::community::get_community_roles(&cid_hex).unwrap().is_admin(&admin.public_key().to_hex()),
            "baseline: the admin folds while its editions are still in reach",
        );

        // Bury it under MORE than one page of strictly NEWER control traffic.
        for i in 0..(FOLLOW_PAGE + 50) {
            publish_channel_edition_at(
                &bed.relay, &community, &owner.keys,
                &ChannelId(crate::simd::hex::hex_to_bytes_32(&format!("{:064x}", i + 1))),
                &format!("ch{i}"), 1, 2_000 + i as u64,
            ).await;
        }

        // Forget the grant's FLOOR. Re-establishing it is the observable proof that
        // the fold actually reached the grant edition, rather than merely retaining a
        // cached roster it could not re-derive.
        let grant_eid = crate::simd::hex::bytes_to_hex_32(
            &crate::community::v2::derive::grant_locator(community.id(), &admin.public_key().to_bytes()),
        );
        crate::db::community::delete_edition_head(&cid_hex, &grant_eid).unwrap();
        assert!(
            crate::db::community::get_edition_head(&cid_hex, &grant_eid).unwrap().is_none(),
            "precondition: the floor is gone",
        );

        follow_control(&bed.relay, &community).await.unwrap();

        assert!(
            crate::db::community::get_edition_head(&cid_hex, &grant_eid).unwrap().is_some(),
            "the fold MUST page past the newest window and reach the grant that defines the \
             admin list — stopping at the first coherent-looking page is how a community \
             becomes unable to re-derive its own roster",
        );
        assert!(
            crate::db::community::get_community_roles(&cid_hex).unwrap().is_admin(&admin.public_key().to_hex()),
            "and the admin survives",
        );
    }

    #[tokio::test]
    async fn a_grant_whose_roles_resolve_to_none_leaves_no_entry() {
        let (bed, owner, _m) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Unresolved", bed.relays.clone(), None).await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let (kept, lost) = (Keys::generate(), Keys::generate());
        let role = "aa".repeat(32);
        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&role, Permissions::BAN), 1).await;
        publish_grant(&bed.relay, &community, &owner.keys, &kept.public_key(), vec!["cc".repeat(32), role.clone()], 1).await;
        publish_grant(&bed.relay, &community, &owner.keys, &lost.public_key(), vec!["dd".repeat(32)], 1).await;
        follow_control(&bed.relay, &community).await.unwrap();
        let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
        let of = |k: &Keys| roster.grants.iter().find(|g| g.member == k.public_key().to_hex()).map(|g| g.role_ids.clone());
        assert_eq!(of(&kept), Some(vec![role]), "a grant keeps only the roles that resolve");
        assert_eq!(of(&lost), None, "and one that resolves none stands for nothing");
    }

    #[tokio::test]
    async fn a_grant_naming_a_role_its_own_holder_created_still_folds() {
        // The deadlock that emptied two live communities' rosters.
        //
        // A community grows the ordinary way: the owner promotes an admin, the admin
        // creates a role of their own, and the owner then grants that role onward. Now
        // the grant references a role whose AUTHOR draws authority from a grant — and
        // under all-or-nothing resolution neither can go first. The fixpoint lands
        // empty, and every grant in the community dies with it, the owner's included.
        //
        // Resolving the roles a grant CAN resolve breaks the cycle without granting
        // anything the author did not write: the retained roles are still rank-checked,
        // and the rest fold in on a later iteration.
        let (bed, owner, _m) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "GrantCycle", bed.relays.clone(), None).await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let admin = Keys::generate();
        let member = Keys::generate();

        // 1. The owner's own role, and a grant of it to the admin.
        let owner_role = "aa".repeat(32);
        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&owner_role, Permissions::ADMIN_ALL), 1).await;
        publish_grant(&bed.relay, &community, &owner.keys, &admin.public_key(), vec![owner_role.clone()], 1).await;
        follow_control(&bed.relay, &community).await.unwrap();
        assert!(
            crate::db::community::get_community_roles(&cid_hex).unwrap().is_admin(&admin.public_key().to_hex()),
            "the admin is promoted",
        );

        // 2. The ADMIN creates a role of their own, beneath theirs.
        let admin_made = "bb".repeat(32);
        let mut made = admin_role(&admin_made, Permissions::BAN);
        made.position = 5;
        publish_role(&bed.relay, &community, &admin, &made, 1).await;

        follow_control(&bed.relay, &community).await.unwrap();
        let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
        assert!(
            roster.role(&admin_made).is_some(),
            "an admin-authored role folds while its author's grant is resolvable",
        );
        assert!(
            roster.is_admin(&admin.public_key().to_hex()),
            "and the admin keeps their own standing — a cycle here empties the roster",
        );

        // 3. The owner grants the ADMIN-MADE role to a member, alongside a role that
        //    is not resolvable at all. Under all-or-nothing the whole grant dies and
        //    takes the roster with it; resolved partially, the member gets what the
        //    owner actually granted.
        publish_grant(
            &bed.relay, &community, &owner.keys, &member.public_key(),
            vec![admin_made.clone(), "cc".repeat(32)], 1,
        ).await;
        follow_control(&bed.relay, &community).await.unwrap();
        let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
        let mg = roster.grants.iter().find(|g| g.member == member.public_key().to_hex());
        assert!(
            mg.is_some_and(|g| g.role_ids.contains(&admin_made)),
            "the resolvable half of the grant is honored",
        );
        assert!(
            mg.is_some_and(|g| !g.role_ids.iter().any(|r| r == &"cc".repeat(32))),
            "and the unresolvable half is NOT — partial resolution only ever grants less",
        );
        assert!(
            roster.is_admin(&admin.public_key().to_hex()),
            "the rest of the roster survives it",
        );
    }

    #[tokio::test]
    async fn a_cold_device_pages_past_the_first_window_to_find_an_older_grant() {
        // The early break stops paging once every entity we track has a head. On a
        // COLD device we track NOTHING, so that condition is vacuously true and the
        // walk stops at page one — the roster is then whatever the newest window
        // happened to hold, and an admin granted before it silently is not one.
        // That is the roster collapse, arrived at by an optimisation.
        let (bed, owner, _m) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "ColdPage", bed.relays.clone(), None).await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);

        // The grant that matters goes down FIRST, so a full newest-first page buries it.
        let admin = Keys::generate();
        let rid = "e5".repeat(32);
        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN), 1).await;
        publish_grant(&bed.relay, &community, &owner.keys, &admin.public_key(), vec![rid.clone()], 1).await;

        // Then bury it under a full page of newer editions.
        for v in 2..(FOLLOW_PAGE as u64 + 2) {
            publish_filler_edition(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN), v, 1_000 + v).await;
        }

        follow_control(&bed.relay, &community).await.unwrap();

        assert!(
            crate::db::community::get_community_roles(&cid_hex).unwrap().is_admin(&admin.public_key().to_hex()),
            "a cold device must page PAST the first window — stopping there caches a \
             partial authority as its own baseline and drops every older grant",
        );
    }

    #[tokio::test]
    async fn a_truncated_cold_fold_banks_nothing_at_all() {
        // A second holding more than a page is a wall for a relay read by pages: what else it
        // holds there cannot be asked for, so the fold is TRUNCATED. Refusing to show that
        // partial roster is not enough — it must not be BANKED either. A stored baseline
        // carries a provenance stamp that the next, complete fold has to beat, and names
        // entities that a complete fold may not head, so banking a partial window is how a
        // client talks itself into a permanent wedge.
        let (bed, owner, _m) = TestBed::new();
        bed.relay.without_reconcile(&bed.relays);
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Wall", bed.relays.clone(), None).await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);

        let admin = Keys::generate();
        let rid = "e5".repeat(32);
        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN), 1).await;
        publish_grant(&bed.relay, &community, &owner.keys, &admin.public_key(), vec![rid.clone()], 1).await;
        // A full page of editions sharing ONE second, burying the grant behind the wall.
        for v in 2..(FOLLOW_PAGE as u64 + 2) {
            publish_filler_edition(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN), v, 1_000).await;
        }

        follow_control(&bed.relay, &community).await.unwrap();

        assert_eq!(
            crate::db::community::get_community_roles_at(&cid_hex).unwrap(),
            0,
            "a truncated fold must bank NO baseline — a stored partial roster outranks \
             the complete fold that follows it and can never be replaced",
        );
    }

    #[tokio::test]
    async fn an_older_window_never_overwrites_a_newer_cached_roster() {
        // The roster cache carries the provenance timestamp of the fold that wrote it.
        // A later fold reading an OLDER window (a lagging relay, a short page) must not
        // replace it — that is a downgrade with no gap and no truncation to catch it.
        let (bed, owner, _m) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Monotone", bed.relays.clone(), None).await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);

        let admin = Keys::generate();
        let rid = "e5".repeat(32);
        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN), 1).await;
        publish_grant(&bed.relay, &community, &owner.keys, &admin.public_key(), vec![rid], 1).await;
        follow_control(&bed.relay, &community).await.unwrap();
        assert!(crate::db::community::get_community_roles(&cid_hex).unwrap().is_admin(&admin.public_key().to_hex()));

        // Stamp the cached roster now: every edition here is older.
        let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
        let now = (now_ms() / 1000) as i64;
        crate::db::community::set_community_roles(&cid_hex, &roster, now).unwrap();

        follow_control(&bed.relay, &community).await.unwrap();
        assert!(
            crate::db::community::get_community_roles(&cid_hex).unwrap().is_admin(&admin.public_key().to_hex()),
            "an older window must not overwrite a newer cached roster",
        );
        assert_eq!(
            crate::db::community::get_community_roles_at(&cid_hex).unwrap(),
            now,
            "and the newer provenance stamp survives — otherwise the next fold downgrades freely",
        );
    }

    /// A fast majority that does not hold the older editions. Quorum returns as soon
    /// as it answers, so those editions read as absent; only a Full read waits for the
    /// relay that has them. This is the shape a slow Ditto/Soapbox relay produces.
    struct SlowMajority<'a>(&'a MemoryRelay, u64);
    #[async_trait::async_trait]
    impl Transport for SlowMajority<'_> {
        async fn publish(&self, e: &Event, r: &[String]) -> Result<(), String> {
            self.0.publish(e, r).await
        }
        async fn fetch(&self, query: &Query, relays: &[String]) -> Result<Vec<Event>, String> {
            let out = self.0.fetch(query, relays).await?;
            if query.evidence == crate::community::transport::Evidence::Full {
                return Ok(out);
            }
            Ok(out.into_iter().filter(|e| e.created_at.as_secs() > self.1).collect())
        }
        async fn fetch_plane(&self, plane: &Keys, query: &Query, relays: &[String]) -> Result<crate::community::transport::PlaneFetch, String> {
            self.0.fetch_plane(plane, query, relays).await
        }
        async fn publish_durable(&self, e: &Event, r: &[String]) -> Result<(), String> {
            self.0.publish_durable(e, r).await
        }
    }

    #[tokio::test]
    async fn a_live_link_a_quorum_cannot_see_still_reads_public() {
        // The ban path asks this to decide whether to refound. CORD-05 §5 forbids
        // refounding a Public community — the link refresh re-posts the bundle behind
        // the same URL, so the rotation severs nothing and strands foreign-link joiners
        // on a buried epoch. A Quorum read that misses another creator's Registry makes
        // a Public community read Private, which takes exactly that forbidden branch.
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "QuorumBlind", vec!["wss://r".into()], None).await.unwrap();
        mint_public_link(&relay, &community, "https://x", None, None).await.unwrap();
        assert!(community_is_public(&relay, &community).await, "the link is live on the plane");

        // u64::MAX: nothing is newer, so the Quorum read is blinded entirely. The
        // link is minted with the real clock, so a small cutoff filters nothing.
        let slow = SlowMajority(&relay, u64::MAX);
        assert!(
            community_is_public(&slow, &community).await,
            "a live link only a minority relay serves must still read Public — reading \
             Private here refounds a Public community on ban, severing nothing",
        );
    }

    #[tokio::test]
    async fn a_quorum_that_cannot_see_a_stored_entity_escalates_to_full() {
        // The roster fold draws an absence verdict, and an absence verdict from a
        // MAJORITY is not one: the same fast subset answers every boot, so the retain
        // never lifts and the cache freezes holding the only surviving copy of the
        // roster. Read again at Full before concluding anything is gone.
        let (bed, owner, _m) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Escalate", bed.relays.clone(), None).await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);

        let admin = Keys::generate();
        let rid = "e5".repeat(32);
        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN), 1).await;
        publish_grant(&bed.relay, &community, &owner.keys, &admin.public_key(), vec![rid.clone()], 1).await;

        // Bank a complete roster the honest way, so the entities are STORED and floored.
        follow_control(&bed.relay, &community).await.unwrap();
        assert!(crate::db::community::get_community_roles(&cid_hex).unwrap().is_admin(&admin.public_key().to_hex()));

        // A SECOND admin is granted. Its edition lands on the plane like every other,
        // below the cutoff — so a Quorum read cannot see it, and a client that concludes
        // from Quorum alone retains the old roster and never learns about them.
        let admin2 = Keys::generate();
        publish_grant(&bed.relay, &community, &owner.keys, &admin2.public_key(), vec![rid], 1).await;

        let slow = SlowMajority(&bed.relay, 5_000);
        follow_control(&slow, &community).await.unwrap();

        let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
        assert!(
            roster.is_admin(&admin.public_key().to_hex()),
            "the first admin survives — the retain is doing its job",
        );
        assert!(
            roster.is_admin(&admin2.public_key().to_hex()),
            "and the roster still ADVANCES: a Quorum read that could not account for a \
             stored entity must re-read at Full, or the cache freezes holding the only \
             surviving copy of the roster and no promotion ever lands again",
        );
    }

    #[tokio::test]
    async fn one_gapped_entity_does_not_freeze_the_rest_of_the_roster() {
        // `authority.gapped` is a global OR across every entity, but the spec makes a
        // gap fail closed FOR THAT ENTITY — suspend it, refetch it — not for the whole
        // community. Treating it as a veto froze live rosters that were otherwise
        // folding perfectly, and permanently once the plane is exhausted and no further
        // paging can resolve the hole.
        let (bed, owner, _m) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "OneGap", bed.relays.clone(), None).await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);

        // A healthy admin the plane fully describes.
        let admin = Keys::generate();
        let rid = "e5".repeat(32);
        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN), 1).await;
        publish_grant(&bed.relay, &community, &owner.keys, &admin.public_key(), vec![rid], 1).await;

        // And a second role the plane DOES serve, floored at a hash nothing chains to:
        // its editions are present but unanchored, which is the withholding shape that
        // fails closed and raises the gap. A floor on an entity absent from the window
        // would not — the fold only visits entities it sees.
        let rid2 = "c7".repeat(32);
        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid2, Permissions::BAN), 5).await;
        crate::db::community::set_edition_head_at_epoch(&cid_hex, &rid2, 3, &[9u8; 32], &[9u8; 32], &owner.keys.public_key().to_bytes(), community.root_epoch.0).unwrap();

        follow_control(&bed.relay, &community).await.unwrap();

        assert!(
            crate::db::community::get_community_roles(&cid_hex).unwrap().is_admin(&admin.public_key().to_hex()),
            "a hole in ONE entity must not withhold every other entity's authority — that is \
             how a community that folds correctly still shows an empty roster",
        );
    }

    #[tokio::test]
    async fn follow_control_retains_the_roster_when_a_floored_role_ages_out() {
        let (bed, owner, _m) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Complete", bed.relays.clone(), None).await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let (a, b) = (Keys::generate().public_key(), Keys::generate().public_key());
        let rid = crate::simd::hex::bytes_to_hex_32(&[0x7c; 32]);

        // Full state on relay1: an Admin role + two grants → both fold + persist as admins.
        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::ADMIN_ALL), 1).await;
        publish_grant(&bed.relay, &community, &owner.keys, &a, vec![rid.clone()], 1).await;
        publish_grant(&bed.relay, &community, &owner.keys, &b, vec![rid.clone()], 1).await;
        follow_control(&bed.relay, &community).await.unwrap().updated;
        assert!(crate::db::community::get_community_roles(&cid_hex).unwrap().is_admin(&a.to_hex()), "seeded");

        // relay2 serves A's grant but NOT the role (aged out of the window): the fold
        // drops both admins yet raises no gap. The completeness gate must RETAIN the
        // stored roster rather than persist the lossy one.
        let relay2 = MemoryRelay::new();
        publish_grant(&relay2, &community, &owner.keys, &a, vec![rid.clone()], 1).await;
        follow_control(&relay2, &community).await.unwrap().updated;
        let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
        assert!(roster.is_admin(&a.to_hex()) && roster.is_admin(&b.to_hex()), "a floored-but-unfetched role retains the stored roster");
    }

    #[tokio::test]
    async fn an_uncited_metadata_or_banlist_edition_is_dropped() {
        // CORD-04 §5 covers EVERY control entity, not just the delegation chain.
        // Vector already gated roles and grants in-fold; metadata, channels and
        // the banlist resolved on permission alone, so a client one sweep behind
        // honored an edit from an admin whose demotion it had not read yet.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Base", vec!["wss://r".into()], None).await.unwrap();
        let admin = Keys::generate();
        let rid = "a7".repeat(32);
        publish_role(&relay, &community, &owner, &admin_role(&rid, Permissions::MANAGE_METADATA | Permissions::BAN), 1).await;
        publish_grant(&relay, &community, &owner, &admin.public_key(), vec![rid], 1).await;

        // The admin acts WITHOUT citing (what every pre-citation client emitted).
        let group = control::ControlPlane::of(&community).write_group().unwrap();
        let meta = control::CommunityMetadata { name: "Uncited Rename".into(), ..Default::default() };
        let rumor = control::build_edition_rumor(
            admin.public_key(), vsk::COMMUNITY_METADATA, &community.id().0, 2,
            head_hash_on_relay(&relay, &community, &community.id().0).await.as_ref(),
            &serde_json::to_string(&meta).unwrap(), 1_000, None,
        );
        let (wrap, _) = control::seal_control_edition(&rumor, &group, &admin, Timestamp::from_secs(1_000)).unwrap();
        relay.publish(&wrap, &community.relays).await.unwrap();

        let ban_eid = crate::community::v2::derive::banlist_locator(community.id());
        let victim = Keys::generate().public_key().to_hex();
        let ban_rumor = control::build_edition_rumor(
            admin.public_key(), vsk::BANLIST, &ban_eid, 1, None,
            &serde_json::to_string(&vec![victim.clone()]).unwrap(), 1_000, None,
        );
        let (ban_wrap, _) = control::seal_control_edition(&ban_rumor, &group, &admin, Timestamp::from_secs(1_000)).unwrap();
        relay.publish(&ban_wrap, &community.relays).await.unwrap();

        let updated = follow_control(&relay, &community).await.unwrap().updated;
        assert!(
            updated.as_ref().is_none_or(|c| c.name != "Uncited Rename"),
            "an uncited metadata edit must not be honored",
        );
        let authority = fetch_authority(&relay, &community).await;
        assert!(!authority.banned.contains(&victim), "an uncited banlist edition must not be honored");
        // The positive case (this same admin, citing, lands) is
        // `an_authorized_admin_edits_metadata_but_a_demoted_one_cannot` — its
        // helper cites, so it proves the gate is the CITATION and not the
        // permission. Re-proving it here would need a fresh chain anyway: a
        // cited edition chaining onto the rejected one above is gapped, not
        // refused.
    }

    #[tokio::test]
    async fn an_authorized_admin_edits_metadata_but_a_demoted_one_cannot() {
        // CORD-04 §5: an admin holding MANAGE_METADATA renames the community; once the
        // owner revokes the grant, the (now unauthorized) admin's further edit drops
        // and the name holds at the last authorized state.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Base", vec!["wss://r".into()], None).await.unwrap();
        let admin = Keys::generate();
        let rid = "a1".repeat(32);
        publish_role(&relay, &community, &owner, &admin_role(&rid, Permissions::MANAGE_METADATA), 1).await;
        publish_grant(&relay, &community, &owner, &admin.public_key(), vec![rid.clone()], 1).await;
        publish_community_meta(&relay, &community, &admin, "Admin Rename", 2).await;

        let updated = follow_control(&relay, &community).await.unwrap().updated.expect("admin edit authorized");
        assert_eq!(updated.name, "Admin Rename", "an admin with MANAGE_METADATA renames");

        publish_grant(&relay, &community, &owner, &admin.public_key(), vec![], 2).await; // revoke
        publish_community_meta(&relay, &community, &admin, "Demoted Rename", 3).await;
        let _ = follow_control(&relay, &community).await.unwrap().updated;
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        assert_eq!(held.name, "Admin Rename", "a demoted admin's edit is dropped; the name holds");
    }

    #[tokio::test]
    async fn a_roleless_member_cannot_edit_metadata() {
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Guarded", vec!["wss://r".into()], None).await.unwrap();
        let stranger = Keys::generate();
        publish_community_meta(&relay, &community, &stranger, "Hijacked", 2).await;
        assert!(
            follow_control(&relay, &community).await.unwrap().updated.is_none(),
            "a roleless member's metadata edit never folds"
        );
    }

    #[tokio::test]
    async fn a_self_signed_grant_is_not_authority() {
        // The self-promotion defense: a member self-signs both a role and a grant of
        // it to themselves. authorize_delegation drops both (their signer never traces
        // to the owner), so their metadata edit stays unauthorized.
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "NoSelfPromo", vec!["wss://r".into()], None).await.unwrap();
        let rogue = Keys::generate();
        let rid = "b2".repeat(32);
        publish_role(&relay, &community, &rogue, &admin_role(&rid, Permissions::ADMIN_ALL), 1).await;
        publish_grant(&relay, &community, &rogue, &rogue.public_key(), vec![rid.clone()], 1).await;
        publish_community_meta(&relay, &community, &rogue, "Seized", 2).await;
        assert!(
            follow_control(&relay, &community).await.unwrap().updated.is_none(),
            "a self-signed grant confers no authority"
        );
    }

    #[tokio::test]
    async fn the_banlist_is_enforced_only_from_a_ban_holder() {
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Bans", vec!["wss://r".into()], None).await.unwrap();
        let target = "cc".repeat(32);

        // A non-BAN-holder's banlist edition is folded but NOT enforced.
        let rogue = Keys::generate();
        publish_banlist(&relay, &community, &rogue, &[target.clone()], 1).await;
        let floors = load_floors(&community);
        let editions = fetch_control(&relay, &community).await;
        let authority = fold_authority(&community, &editions, &floors);
        assert!(authority.banned.is_empty(), "a non-owner (no BAN) banlist is not enforced");

        // The owner (supreme, holds BAN) bans the target: now enforced.
        publish_banlist(&relay, &community, &owner, &[target.clone()], 2).await;
        let editions = fetch_control(&relay, &community).await;
        let authority = fold_authority(&community, &editions, &floors);
        assert!(authority.banned.contains(&target), "the owner's banlist is enforced");
    }

    #[tokio::test]
    async fn a_malformed_banlist_edition_unbans_nobody() {
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "BadList", vec!["wss://r".into()], None).await.unwrap();
        let target = "cc".repeat(32);
        publish_banlist(&relay, &community, &owner, &[target.clone()], 1).await;
        let group = control::ControlPlane::of(&community).write_group().unwrap();
        let eid = crate::community::v2::derive::banlist_locator(community.id());
        let prev = head_hash_on_relay(&relay, &community, &eid).await;
        let rumor = control::build_edition_rumor(owner.public_key(), vsk::BANLIST, &eid, 2, prev.as_ref(), r#"{"not":"a list"}"#, 1_000, None);
        let (wrap, _) = control::seal_control_edition(&rumor, &group, &owner, Timestamp::from_secs(1_000)).unwrap();
        relay.publish(&wrap, &community.relays).await.unwrap();
        let authority = fold_authority(&community, &fetch_control(&relay, &community).await, &load_floors(&community));
        assert!(authority.banned.contains(&target), "an edition that isn't a list is no Banlist edition");
    }

    #[tokio::test]
    async fn every_invite_list_copy_merges_and_an_unreadable_one_is_never_written_over() {
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Lists", vec!["wss://r".into()], None).await.unwrap();
        let entry = |t: &str| invite::InviteEntry { token: t.into(), signer_sk: "11".repeat(32), community_id: "22".repeat(32), url: format!("https://v/{t}"), label: None, created_at: 1, expires_at: None, epoch: Some(0), extra: Default::default() };
        let signer = crate::signer::active_signer().unwrap();
        for (t, at) in [("aa", 1_000u64), ("bb", 2_000)] {
            let list = invite::InviteList { entries: vec![entry(t)], ..Default::default() };
            let ev = invite::build_invite_list_event_at(&signer, owner.public_key(), &list, at).await.unwrap();
            relay.publish(&ev, &[format!("wss://copy{at}")]).await.unwrap();
        }
        let relays = vec!["wss://copy1000".to_string(), "wss://copy2000".to_string()];
        let (merged, newest) = read_invite_list(&relay, &relays).await.unwrap().unwrap();
        let mut tokens: Vec<_> = merged.entries.iter().map(|e| e.token.as_str()).collect();
        tokens.sort();
        assert_eq!((tokens, newest), (vec!["aa", "bb"], 2_000), "every copy counts, not only the newest");

        use nostr_sdk::prelude::FinalizeEvent;
        let junk = nostr_sdk::prelude::EventBuilder::new(nostr_sdk::prelude::Kind::Custom(crate::community::v2::kind::INVITE_LIST), "not a ciphertext").finalize(&owner).unwrap();
        relay.publish(&junk, &["wss://copy1000".to_string()]).await.unwrap();
        assert!(read_invite_list(&relay, &relays).await.is_err(), "a copy that won't open blocks the write");

        // Someone else's list, served by a relay, is no copy of mine.
        let other = Keys::generate();
        let foreign = nostr_sdk::prelude::EventBuilder::new(nostr_sdk::prelude::Kind::Custom(crate::community::v2::kind::INVITE_LIST), "whatever").finalize(&other).unwrap();
        relay.publish(&foreign, &["wss://copy3000".to_string()]).await.unwrap();
        let only_foreign = vec!["wss://copy3000".to_string()];
        assert!(read_invite_list(&relay, &only_foreign).await.unwrap().is_none(), "another account's event is ignored, not a wedge");
        let _ = community;
    }

    #[tokio::test]
    async fn a_banned_admin_loses_all_authority() {
        // CORD-04 §4: a banned npub vanishes — even holding an un-stripped grant, a
        // banned admin's authority is dropped and their edits refused.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "BanAuth", vec!["wss://r".into()], None).await.unwrap();
        let admin = Keys::generate();
        let rid = "e5".repeat(32);
        publish_role(&relay, &community, &owner, &admin_role(&rid, Permissions::MANAGE_METADATA), 1).await;
        publish_grant(&relay, &community, &owner, &admin.public_key(), vec![rid.clone()], 1).await;
        publish_banlist(&relay, &community, &owner, &[admin.public_key().to_hex()], 1).await; // ban, grant left intact
        publish_community_meta(&relay, &community, &admin, "Banned Rename", 2).await;

        assert!(
            follow_control(&relay, &community).await.unwrap().updated.is_none(),
            "a banned admin's edit is dropped even with an unstripped grant"
        );
        let authority = fold_authority(&community, &fetch_control(&relay, &community).await, &load_floors(&community));
        assert!(authority.banned.contains(&admin.public_key().to_hex()));
        assert!(
            !authority.roles.is_authorized(&admin.public_key().to_hex(), Some(&owner.public_key().to_hex()), Permissions::MANAGE_METADATA),
            "a banned admin holds no bit"
        );
    }

    #[tokio::test]
    async fn a_ban_holder_cannot_ban_a_superior_or_the_owner() {
        // CORD-04 §3/§5: BAN needs the bit AND a strict outrank of the target. A mod
        // (pos 2, holds BAN) can ban a lower member but NOT a superior admin (pos 1)
        // and NOT the owner (supreme, unbannable).
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Ranks", vec!["wss://r".into()], None).await.unwrap();
        let admin = Keys::generate();
        let moder = Keys::generate();
        let stranger = Keys::generate();
        let (admin_rid, mod_rid) = ("a1".repeat(32), "b2".repeat(32));
        publish_role(&relay, &community, &owner, &Role { role_id: admin_rid.clone(), name: "Admin".into(), position: 1, permissions: Permissions(Permissions::ADMIN_ALL), scope: RoleScope::Server, color: 0, rank: None, display: false, mentionable: false, extra: Default::default() }, 1).await;
        publish_role(&relay, &community, &owner, &Role { role_id: mod_rid.clone(), name: "Mod".into(), position: 2, permissions: Permissions(Permissions::BAN), scope: RoleScope::Server, color: 0, rank: None, display: false, mentionable: false, extra: Default::default() }, 1).await;
        publish_grant(&relay, &community, &owner, &admin.public_key(), vec![admin_rid], 1).await;
        publish_grant(&relay, &community, &owner, &moder.public_key(), vec![mod_rid], 1).await;
        publish_banlist(&relay, &community, &moder, &[admin.public_key().to_hex(), owner.public_key().to_hex(), stranger.public_key().to_hex()], 1).await;

        let authority = fold_authority(&community, &fetch_control(&relay, &community).await, &load_floors(&community));
        assert!(!authority.banned.contains(&admin.public_key().to_hex()), "a mod cannot ban a superior admin");
        assert!(!authority.banned.contains(&owner.public_key().to_hex()), "nobody can ban the owner");
        assert!(authority.banned.contains(&stranger.public_key().to_hex()), "the mod CAN ban a lower-ranked member");
    }

    #[tokio::test]
    async fn an_unauthorized_higher_banlist_cannot_unban() {
        // CORD-04 §4 anti-roster fail-CLOSED: a rogue's higher-version empty banlist
        // must not erase the owner's ban (author-aware head selection + persisted
        // banlist retention).
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "NoUnban", vec!["wss://r".into()], None).await.unwrap();
        let target = "cc".repeat(32);
        publish_banlist(&relay, &community, &owner, &[target.clone()], 1).await;
        follow_control(&relay, &community).await.unwrap().updated; // persists the ban

        let rogue = Keys::generate();
        publish_banlist(&relay, &community, &rogue, &[], 2).await; // unauthorized higher, empty
        let authority = fold_authority(&community, &fetch_control(&relay, &community).await, &load_floors(&community));
        assert!(authority.banned.contains(&target), "an unauthorized higher banlist cannot un-ban");
    }

    #[tokio::test]
    async fn the_community_list_syncs_a_membership_to_a_fresh_device() {
        // CORD-02 §8: create publishes the 13302; a fresh device (community dropped
        // locally, the 13302 + genesis still on the relay) rehydrates it on sync.
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let relays = vec!["wss://r".to_string()];
        let community = create_community(&relay, "Synced", relays.clone(), None).await.unwrap();
        crate::db::community::delete_community(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap();
        assert!(crate::db::community::load_community_v2(community.id()).unwrap().is_none());

        let rehydrated = sync_community_list(&relay, &relays).await.unwrap().joined;
        assert_eq!(rehydrated.len(), 1, "the left-behind membership rehydrates");
        assert_eq!(rehydrated[0].id().0, community.id().0);
        assert!(crate::db::community::load_community_v2(community.id()).unwrap().is_some(), "and is now held locally");
    }

    #[tokio::test]
    async fn a_retried_leave_tombstone_cannot_bury_a_rejoin_made_meanwhile() {
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let relays = vec!["wss://r".to_string()];
        let community = create_community(&relay, "Left", relays.clone(), None).await.unwrap();
        let cid = crate::simd::hex::bytes_to_hex_32(&community.id().0);

        // The leave stamps its own removal time, and its publish fails.
        let left_at = now_ms() - 1000;
        tombstone_community_list(&relay, community.id(), &relays, left_at, true).await.unwrap();
        // The user rejoins before the retry gets through.
        republish_community_list(&relay, Some(community.id())).await.unwrap();
        assert!(fetch_fragments(&relay, &relays).await.unwrap().unwrap().list.is_live(&cid));

        // The retry lands late, carrying the ORIGINAL stamp — which the rejoin outranks.
        tombstone_community_list(&relay, community.id(), &relays, left_at, true).await.unwrap();
        let set = fetch_fragments(&relay, &relays).await.unwrap().unwrap();
        assert!(set.list.is_live(&cid), "a retry re-stamping `now` would have buried the rejoin");
    }

    #[tokio::test]
    async fn a_boot_with_no_fragments_seeds_the_list_from_local_state() {
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let relays = vec!["wss://r".to_string()];
        let community = create_community(&relay, "Seeded", relays.clone(), None).await.unwrap();

        // An account arriving from the retired single-event list: held locally, nothing
        // at the fragment coordinate. Boot alone has to write it — no membership changes.
        let bare = MemoryRelay::new();
        sync_community_list(&bare, &relays).await.unwrap();
        let set = fetch_fragments(&bare, &relays).await.unwrap().expect("boot seeded the List");
        let live = set.list.live_entries();
        assert_eq!(live.len(), 1);
        assert_eq!(live[0].community_id, crate::simd::hex::bytes_to_hex_32(&community.id().0));

        // Latched: a LATER empty read is a relay that lost the fragments, not a fresh
        // account, and republishing local state there would bury a sibling's tombstones.
        let empty = MemoryRelay::new();
        sync_community_list(&empty, &relays).await.unwrap();
        assert_eq!(empty.stored_count(), 0, "the seed runs once");
    }

    #[tokio::test]
    async fn a_dissolved_invite_retires_on_accept_and_tombstones_the_list() {
        // The invite to a dissolved community is the one join failure with no
        // retry: the refusal is an owner-signed grave. The boundary must retire
        // the parked row AND write the §8 tombstone siblings purge on.
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Grave", bed.relays.clone(), None).await.unwrap();
        let bundle = serde_json::to_string(&bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None)).unwrap();
        dissolve_community(&bed.relay, &community).await.unwrap();

        bed.swap_to(&member);
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        crate::db::community::save_pending_invite(&cid_hex, &bundle, "inviter", i64::MAX).unwrap();
        let err = accept_parked_invite(&bed.relay, &bundle, None).await.unwrap_err();
        assert_eq!(err, ERR_DISSOLVED, "the grave refusal is the sentinel the boundary matches");

        retire_dead_invite(&bed.relay, &cid_hex, &bed.relays).await;
        assert!(crate::db::community::get_pending_invite(&cid_hex).unwrap().is_none(), "the dead invite leaves this device");
        let set = fetch_fragments(&bed.relay, &bed.relays).await.unwrap().expect("the tombstone published");
        assert!(set.list.tombstones.iter().any(|t| t.community_id == cid_hex), "and siblings get the §8 tombstone");
        assert!(!set.list.is_live(&cid_hex));
    }

    #[tokio::test]
    async fn an_owner_dissolve_tombstones_the_list_for_sibling_devices() {
        // Dissolving IS leaving. The grave alone reaches every MEMBER, but only a §8
        // tombstone reaches the owner's own sibling devices — without it they keep the
        // membership LIVE in the List, fold the grave, and show a sealed husk the owner
        // already deleted, on every device, until each is cleaned up by hand.
        let (bed, owner, _member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Doomed", bed.relays.clone(), None).await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let before = fetch_fragments(&bed.relay, &bed.relays).await.unwrap().expect("create published the List");
        assert!(before.list.is_live(&cid_hex), "the membership is live before the dissolve");

        dissolve_community(&bed.relay, &community).await.unwrap();

        let set = fetch_fragments(&bed.relay, &bed.relays).await.unwrap().expect("the List outlives the dissolve");
        assert!(
            set.list.tombstones.iter().any(|t| t.community_id == cid_hex),
            "the dissolve published the §8 tombstone alongside the grave"
        );
        assert!(!set.list.is_live(&cid_hex), "sibling devices tear the husk down on their next list sync");
    }

    #[tokio::test]
    async fn a_sibling_devices_list_tombstone_purges_the_parked_invite() {
        // Device A declined (or retired a dead invite): its §8 tombstone must
        // clear device B's parked copy on the next list sync — and ONLY when the
        // removal post-dates the invite, so a fresh re-invite survives an old leave.
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let relays = vec!["wss://r".to_string()];
        let cid = crate::community::CommunityId([0x5A; 32]);
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&cid.0);

        // An OLD tombstone (a past leave) must not kill an invite received after it.
        tombstone_community_list(&relay, &cid, &relays, now_ms() - 600_000, true).await.unwrap();
        crate::db::community::save_pending_invite(&cid_hex, "{}", "inviter", i64::MAX).unwrap();
        sync_community_list(&relay, &relays).await.unwrap();
        assert!(crate::db::community::get_pending_invite(&cid_hex).unwrap().is_some(), "a re-invite supersedes a past leave");

        // A tombstone NEWER than the invite is a verdict on it: purged on sync.
        tombstone_community_list(&relay, &cid, &relays, now_ms() + 10_000, true).await.unwrap();
        sync_community_list(&relay, &relays).await.unwrap();
        assert!(crate::db::community::get_pending_invite(&cid_hex).unwrap().is_none(), "the sibling's removal clears the parked copy");
    }

    #[tokio::test]
    async fn a_removal_answers_every_invite_no_newer_than_it() {
        let (_tmp, _guard, me) = init_test_db();
        let relay = MemoryRelay::new();
        let relays = vec!["wss://r".to_string()];
        let sibling = "5b".repeat(32);
        let ours = crate::community::CommunityId([0x5C; 32]);
        let ours_hex = crate::simd::hex::bytes_to_hex_32(&ours.0);

        publish_remote_tombstone(&relay, &me, &relays, &sibling, 5_000_000).await;
        assert!(!tombstone_suppresses(&sibling, 1), "unknown until a sync reads it");
        sync_community_list(&relay, &relays).await.unwrap();
        assert!(tombstone_suppresses(&sibling, 5_000), "a same-time re-delivery");
        assert!(tombstone_suppresses(&sibling, 4_999));
        assert!(tombstone_suppresses(&sibling.to_ascii_uppercase(), 4_999));
        assert!(!tombstone_suppresses(&sibling, 5_001), "a newer re-invite resurfaces");
        assert!(!tombstone_suppresses(&ours_hex, 1));

        // Our own removal counts before it lands, and after it has.
        add_pending_tombstone(&ours, 7_000_000);
        assert!(tombstone_suppresses(&ours_hex, 7_000));
        let landed = super::super::list::Tombstone { community_id: ours_hex.clone(), removed_at: 7_000_000, extra: Default::default() };
        settle_pending(&super::super::list::CommunityList { tombstones: vec![landed], ..Default::default() });
        assert!(load_pending().tombstones.is_empty());
        assert!(tombstone_suppresses(&ours_hex, 7_000));

        mirror_tombstones([(sibling.as_str(), 1_000)]);
        assert!(tombstone_suppresses(&sibling, 5_000), "an older removal never lowers the bar");

        let kicked = "5f".repeat(32);
        note_local_removal(&kicked, 8_000_000);
        assert!(tombstone_suppresses(&kicked, 8_000), "a kick answers the invites before it");

        let queued = "5e".repeat(32);
        edit_pending(|p| p.tombstones.push(PendingTombstone { community_id: queued.clone(), removed_at: 9_000_000 }));
        assert!(tombstone_suppresses(&queued, 9_000), "a leave queued before the mirror existed");

        crate::db::settings::set_sql_setting(LIST_TOMBSTONES_KEY.to_string(), "not json".into()).unwrap();
        assert!(!tombstone_suppresses(&sibling, 1));
        let aside = crate::db::settings::get_sql_setting(format!("{LIST_TOMBSTONES_KEY}_unread")).unwrap();
        assert_eq!(aside.as_deref(), Some("not json"), "an unreadable mirror is set aside, not overwritten");
    }

    #[tokio::test]
    async fn a_left_community_cannot_reinvite_with_an_older_wrap() {
        #[derive(Default)]
        struct Invites(std::sync::Mutex<Vec<String>>);
        impl crate::InboundEventHandler for Invites {
            fn on_community_invite(&self, community_id: &str) {
                self.0.lock().unwrap().push(community_id.to_string());
            }
        }
        let (_tmp, _guard, _me) = init_test_db();
        let cid = crate::community::CommunityId([0x5D; 32]);
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&cid.0);
        let now = now_ms() / 1000;
        let invite = |sent_at: u64, wrap: u8| crate::event_handler::PreparedEvent::CommunityInviteV2 {
            bundle_json: "{}".into(),
            community_id: cid_hex.clone(),
            inviter: Keys::generate().public_key().to_hex(),
            is_mine: false,
            wrapper_event_id_bytes: [wrap; 32],
            wrapper_created_at: sent_at,
            rumor_created_at: sent_at,
            expires_at: 0,
        };
        add_pending_tombstone(&cid, now * 1000);
        let parked = Invites::default();

        crate::event_handler::commit_prepared_event(invite(now - 60, 1), true, &parked).await;
        assert!(parked.0.lock().unwrap().is_empty(), "the leave already answered it");
        assert!(crate::db::community::get_pending_invite(&cid_hex).unwrap().is_none());

        crate::event_handler::commit_prepared_event(invite(now + 1, 2), true, &parked).await;
        assert_eq!(*parked.0.lock().unwrap(), vec![cid_hex.clone()], "a re-invite after the leave parks");
    }

    #[tokio::test]
    async fn an_unchanged_republish_rewrites_no_fragment() {
        // Nothing changed since the last write: the rebuilt fragment serializes to
        // the bytes already on the relay, so the write must not touch the wire —
        // a bumped created_at on identical content is pure churn.
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let relays = vec!["wss://r".to_string()];
        create_community(&relay, "Stable", relays.clone(), None).await.unwrap();
        let before = fetch_fragments(&relay, &relays).await.unwrap().unwrap().created_at;

        republish_community_list(&relay, None).await.unwrap();
        let after = fetch_fragments(&relay, &relays).await.unwrap().unwrap().created_at;
        assert_eq!(before, after, "a byte-identical fragment must not republish");
    }

    #[tokio::test]
    async fn a_frags_tie_at_equal_age_resolves_to_the_larger_count() {
        // A torn repack's worst case: two fragments at the SAME created_at
        // disagreeing on the total. The larger count must govern (CORD-02 §8) —
        // the smaller would push index 2 out of range and its memberships dormant.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let relays = vec!["wss://r".to_string()];
        let at = now_ms() / 1000;
        let two = super::super::list_frag::FragList { frags: 2, entries: vec![], tombstones: vec![], extra: Default::default() };
        let three = super::super::list_frag::FragList { frags: 3, entries: vec![], tombstones: vec![], extra: Default::default() };
        // The larger count sits at the LOWER index: an age-only rule that keeps
        // the last fragment seen would pick 2 here, not 3.
        for (frag, index) in [(&three, 0usize), (&two, 1usize)] {
            let e = super::super::list_frag::build_fragment_event_keys(&owner, frag, index, at).unwrap();
            relay.publish(&e, &relays).await.unwrap();
        }
        let set = fetch_fragments(&relay, &relays).await.unwrap().unwrap();
        assert_eq!(set.declared, 3, "an age tie resolves to the larger frags");
        assert!(!set.is_complete(), "index 2 is unread, so the set refuses to write");
    }

    fn ext(pairs: serde_json::Value) -> serde_json::Map<String, serde_json::Value> {
        pairs.as_object().expect("an object").clone()
    }

    #[tokio::test]
    async fn fragment_level_unknowns_resolve_to_the_lowest_index_whatever_their_ages() {
        // CORD-02 §8: fragment-level unknowns belong to the List, and where two
        // fragments carry one key the LOWEST index wins. Age decides which copy of an
        // index speaks, never which index outranks another.
        let (_tmp, _guard, owner) = init_test_db();
        let relays = vec!["wss://r".to_string()];
        let at = now_ms() / 1000;
        let frag = |v: &str| super::super::list_frag::FragList { frags: 2, entries: vec![], tombstones: vec![], extra: ext(serde_json::json!({ "x-ext": v })) };
        // Both age orders: the higher index newer, then older.
        for (age0, age1) in [(at, at + 5), (at + 5, at)] {
            let relay = MemoryRelay::new();
            for (index, value, age) in [(0usize, "zero", age0), (1usize, "one", age1)] {
                let e = super::super::list_frag::build_fragment_event_keys(&owner, &frag(value), index, age).unwrap();
                relay.publish(&e, &relays).await.unwrap();
            }
            let set = fetch_fragments(&relay, &relays).await.unwrap().unwrap();
            assert_eq!(
                set.list.extra.get("x-ext"),
                Some(&serde_json::json!("zero")),
                "index 0 wins at ages ({age0}, {age1})"
            );
        }
    }

    #[tokio::test]
    async fn a_newer_copy_of_a_fragment_edits_its_unknown_field() {
        // Within ONE index the newest copy is the fragment (relays resolve the
        // coordinate the same way), so an unknown field edited by its own client
        // sticks, whatever order the relay serves the copies in.
        let (_tmp, _guard, owner) = init_test_db();
        let at = now_ms() / 1000;
        let frag = |v: &str| super::super::list_frag::FragList { frags: 1, entries: vec![], tombstones: vec![], extra: ext(serde_json::json!({ "x-ext": v })) };
        // Two relays disagreeing on the copy — the shape every version-merge reads —
        // with the stale copy on each side in turn.
        let relays = vec!["wss://a".to_string(), "wss://b".to_string()];
        for stale_on_first in [true, false] {
            let relay = MemoryRelay::new();
            let (stale_at, fresh_at) = if stale_on_first { (&relays[0], &relays[1]) } else { (&relays[1], &relays[0]) };
            for (value, age, on) in [("old", at, stale_at), ("new", at + 5, fresh_at)] {
                let e = super::super::list_frag::build_fragment_event_keys(&owner, &frag(value), 0, age).unwrap();
                relay.publish(&e, std::slice::from_ref(on)).await.unwrap();
            }
            let set = fetch_fragments(&relay, &relays).await.unwrap().unwrap();
            assert_eq!(set.list.extra.get("x-ext"), Some(&serde_json::json!("new")), "the newest copy speaks for index 0");
        }
    }

    #[tokio::test]
    async fn a_republish_keeps_a_peer_clients_unknown_fields_when_a_known_field_changed() {
        // The List is the member's vault (CORD-02 §8): a republish rebuilds each
        // snapshot from local state, and if that rebuild sheds what another client
        // wrote — Armada's channel `priors` are retired keys — the material is gone on
        // every device. The trap is the same-epoch tiebreak: once a KNOWN field also
        // differs (a rename, a new key), the whole lower-sorting snapshot wins, and a
        // bare local rebuild that sorts lower takes nothing of the peer's with it.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let relays = vec!["wss://r".to_string()];
        let community = create_community(&relay, "Alpha", relays.clone(), None).await.unwrap();
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let ch = create_private_channel(&relay, &held, "alpha-ch").await.unwrap();
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let key = held.channel(&ch).and_then(|c| c.key).unwrap();
        let b64 = |b: &[u8; 32]| crate::simd::base64::URL_SAFE_NO_PAD.encode_to_string(b);

        // A peer client's write of fragment 0: this channel listed under its own
        // label, and its own fields at every level. Its channel name sorts ABOVE
        // ours, so our rebuild out-sorts its snapshot at the first key.
        let set = fetch_fragments(&relay, &relays).await.unwrap().unwrap();
        let mut frag = set.read_frags.get(&0).unwrap().clone();
        frag.extra.insert("frag-ext".into(), serde_json::json!(true));
        let entry = frag.entries.first_mut().unwrap();
        entry.extra.insert("entry-ext".into(), serde_json::json!(1));
        entry.current.extra.insert("zz-ext".into(), serde_json::json!({ "held": "root" }));
        entry.current.channels = vec![super::super::list_frag::FragChannel {
            id: b64(&ch.0),
            key: Some(b64(&key)),
            epoch: 1,
            name: "zeta-ch".into(),
            extra: ext(serde_json::json!({ "priors": [{ "epoch": 0, "key": "retired" }] })),
        }];
        // Everywhere the List lives: a stale copy left on any relay is a separate
        // hazard.
        let e = super::super::list_frag::build_fragment_event_keys(&owner, &frag, 0, set.created_at[&0] + 1).unwrap();
        relay.publish(&e, &list_read_relays(&[]).await).await.unwrap();

        republish_community_list(&relay, None).await.unwrap();
        let after = fetch_fragments(&relay, &relays).await.unwrap().unwrap().list;
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let entry = after.entries.iter().find(|e| e.community_id == cid_hex).unwrap();
        assert_eq!(entry.current.extra.get("zz-ext"), Some(&serde_json::json!({ "held": "root" })), "snapshot unknowns survive");
        let ch_hex = crate::simd::hex::bytes_to_hex_32(&ch.0);
        let kept = entry.current.channels.iter().find(|c| c.id == ch_hex).unwrap();
        assert_eq!(kept.name, "alpha-ch");
        assert_eq!(kept.extra.get("priors"), Some(&serde_json::json!([{ "epoch": 0, "key": "retired" }])), "channel unknowns survive");
        assert_eq!(entry.extra.get("entry-ext"), Some(&serde_json::json!(1)), "entry unknowns survive");
        assert_eq!(after.extra.get("frag-ext"), Some(&serde_json::json!(true)), "fragment unknowns survive");
    }

    fn snap(epoch: u64, rev: u64, channels: &[(u8, u64, Option<u8>)]) -> super::super::list::JoinMaterial {
        let hex = |b: u8| crate::simd::hex::bytes_to_hex_32(&[b; 32]);
        super::super::list::JoinMaterial {
            community_id: hex(0x01),
            owner: hex(0x02),
            owner_salt: hex(0x03),
            community_root: hex(0x04),
            root_epoch: epoch,
            control_pk: Some(hex(0x05)),
            control_root: None,
            channels: channels
                .iter()
                .map(|(id, ep, key)| super::super::list::ChannelKeyRef { id: hex(*id), key: key.map(hex), epoch: *ep, name: format!("ch{id}"), extra: Default::default() })
                .collect(),
            relays: vec!["wss://r".into()],
            name: "N".into(),
            rev,
            extra: Default::default(),
        }
    }

    fn list_entry_of(list: &super::super::list::CommunityList, community: &CommunityV2) -> super::super::list::CommunityListEntry {
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        list.entries.iter().find(|e| e.community_id == cid_hex).cloned().expect("the membership is listed")
    }

    #[test]
    fn a_rebuild_keeps_its_revision_when_nothing_changed_and_bumps_it_when_something_did() {
        let read = snap(2, 4, &[(0xA1, 1, Some(0xB1))]);
        let same = rebuild_snapshot(snap(2, 0, &[(0xA1, 1, Some(0xB1))]), Some(&read));
        assert_eq!(same.rev, 4, "an unchanged snapshot republishes byte-identical");
        let mut renamed = snap(2, 0, &[(0xA1, 1, Some(0xB1))]);
        renamed.name = "Renamed".into();
        assert_eq!(rebuild_snapshot(renamed, Some(&read)).rev, 5, "a change is one revision past what was read");
        let first = rebuild_snapshot(snap(2, 0, &[(0xA2, 1, Some(0xB2)), (0xA1, 1, Some(0xB1))]), None);
        assert_eq!(first.rev, 0, "a first write needs no revision");
        assert!(first.channels[0].id < first.channels[1].id, "and is written in the canonical order too");
    }

    #[test]
    fn two_devices_listing_channels_in_different_orders_agree_without_a_bump() {
        // Without one canonical order each device reads the other's copy as a
        // change and bumps, forever.
        let read = snap(2, 4, &[(0xA1, 1, Some(0xB1)), (0xA2, 1, Some(0xB2))]);
        let ours = rebuild_snapshot(snap(2, 0, &[(0xA2, 1, Some(0xB2)), (0xA1, 1, Some(0xB1))]), Some(&read));
        assert_eq!(ours.rev, 4, "the same channels in another order are no change");
        let ids: Vec<&str> = ours.channels.iter().map(|c| c.id.as_str()).collect();
        let mut sorted = ids.clone();
        sorted.sort();
        assert_eq!(ids, sorted, "written in one canonical order");
    }

    #[test]
    fn a_rebuild_keeps_what_it_read_but_does_not_hold_itself() {
        // A device behind its sibling — no key for a channel yet, an older key for
        // another — must not publish its smaller view one revision higher and erase
        // what the sibling recorded. Only the same epoch's snapshot is merged: across
        // a Refounding the read copy is a different snapshot.
        let read = snap(2, 6, &[(0xA1, 3, Some(0xC3)), (0xA2, 1, Some(0xB2))]);
        let ours = rebuild_snapshot(snap(2, 0, &[(0xA1, 2, Some(0xC2))]), Some(&read));
        let a1 = ours.channels.iter().find(|c| c.id.starts_with("a1")).expect("still listed");
        assert_eq!((a1.epoch, a1.key.as_deref().map(|k| &k[..2])), (3, Some("c3")), "the sibling's newer channel key stays");
        assert!(ours.channels.iter().any(|c| c.id.starts_with("a2")), "a key only the sibling holds stays");
        assert_eq!(ours.rev, 6, "nothing we know is news, so nothing to revise");

        let mut staff = snap(2, 6, &[]);
        staff.control_root = Some("e".repeat(64));
        assert_eq!(rebuild_snapshot(snap(2, 0, &[]), Some(&staff)).control_root, staff.control_root, "the staff key stays too");

        let other_epoch = rebuild_snapshot(snap(3, 0, &[]), Some(&read));
        assert!(other_epoch.channels.is_empty(), "a Refounding's snapshot is not merged with the epoch before it");
    }

    #[tokio::test]
    async fn a_first_private_channel_key_reaches_the_list_past_a_stale_copy() {
        // The creation write still sits on the fallback relays with no channels, and
        // "channels":[] sorts below "channels":[{ — so without revisions the stale
        // copy out-sorted the key forever, and a fresh device never received it.
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let relays = vec!["wss://r".to_string()];
        let community = create_community(&relay, "Keyed", relays.clone(), None).await.unwrap();
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let ch = create_private_channel(&relay, &held, "inner").await.unwrap();
        republish_community_list(&relay, None).await.unwrap();

        let read_from = list_read_relays(&[]).await;
        let entry = list_entry_of(&fetch_fragments(&relay, &read_from).await.unwrap().unwrap().list, &community);
        let ch_hex = crate::simd::hex::bytes_to_hex_32(&ch.0);
        assert!(
            entry.current.channels.iter().any(|c| c.id == ch_hex && c.key.is_some()),
            "the new key is in the List every device reads"
        );
        assert!(entry.current.rev >= 1, "it landed as a revision");

        // And it stays put: an unchanged republish moves nothing.
        let before = fetch_fragments(&relay, &read_from).await.unwrap().unwrap();
        republish_community_list(&relay, None).await.unwrap();
        let after = fetch_fragments(&relay, &read_from).await.unwrap().unwrap();
        assert_eq!(list_entry_of(&after.list, &community).current.rev, entry.current.rev, "no change, no revision");
        assert_eq!(after.created_at, before.created_at, "and no fragment rewritten");
    }

    #[tokio::test]
    async fn a_rename_at_the_same_epoch_reaches_the_list() {
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Alpha", vec!["wss://r".into()], None).await.unwrap();
        let mut held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        held.name = "Zulu".into();
        crate::db::community::save_community_v2(&held).unwrap();
        republish_community_list(&relay, None).await.unwrap();
        let entry = list_entry_of(&fetch_fragments(&relay, &list_read_relays(&[]).await).await.unwrap().unwrap().list, &community);
        assert_eq!(entry.current.name, "Zulu", "a rename that sorts later still lands");
    }

    #[tokio::test]
    async fn a_device_behind_never_erases_a_key_its_sibling_recorded() {
        // The sibling holds a private-channel key this device has not received yet,
        // and recorded it at rev 2. Our republish — prompted by anything — must keep it.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let relays = vec!["wss://r".to_string()];
        let community = create_community(&relay, "Behind", relays.clone(), None).await.unwrap();
        let set = fetch_fragments(&relay, &relays).await.unwrap().unwrap();
        let mut frag = set.read_frags.get(&0).unwrap().clone();
        let b64 = |b: &[u8; 32]| crate::simd::base64::URL_SAFE_NO_PAD.encode_to_string(b);
        let entry = frag.entries.first_mut().unwrap();
        entry.current.channels.push(super::super::list_frag::FragChannel {
            id: b64(&[0x5A; 32]),
            key: Some(b64(&[0x6B; 32])),
            epoch: 1,
            name: "siblings".into(),
            extra: Default::default(),
        });
        entry.current.rev = 2;
        let e = super::super::list_frag::build_fragment_event_keys(&owner, &frag, 0, set.created_at[&0] + 1).unwrap();
        relay.publish(&e, &list_read_relays(&[]).await).await.unwrap();

        republish_community_list(&relay, None).await.unwrap();
        let entry = list_entry_of(&fetch_fragments(&relay, &list_read_relays(&[]).await).await.unwrap().unwrap().list, &community);
        let sibling = crate::simd::hex::bytes_to_hex_32(&[0x5A; 32]);
        assert!(entry.current.channels.iter().any(|c| c.id == sibling && c.key.is_some()), "the sibling's key survives our republish");
    }

    /// Aggregate fetches answer from the healthy relay; asked alone, the dead
    /// relay errors — the partial-failure shape a boot read can't see through.
    struct HalfDeaf<'a>(&'a MemoryRelay, String);
    #[async_trait::async_trait]
    impl Transport for HalfDeaf<'_> {
        async fn publish(&self, e: &Event, r: &[String]) -> Result<(), String> {
            self.0.publish(e, r).await
        }
        async fn fetch(&self, query: &Query, relays: &[String]) -> Result<Vec<Event>, String> {
            if relays.len() == 1 && relays[0] == self.1 {
                return Err("relay did not answer the fetch".to_string());
            }
            self.0.fetch(query, relays).await
        }
        async fn fetch_plane(&self, plane: &Keys, query: &Query, relays: &[String]) -> Result<crate::community::transport::PlaneFetch, String> {
            self.0.fetch_plane(plane, query, relays).await
        }
        async fn publish_durable(&self, e: &Event, r: &[String]) -> Result<(), String> {
            self.0.publish_durable(e, r).await
        }
    }

    /// A relay too slow for an aggregate read (it answers after the rest have), and
    /// silent when asked alone; it still takes writes.
    struct Slow<'a>(&'a MemoryRelay, &'static str);
    #[async_trait::async_trait]
    impl Transport for Slow<'_> {
        async fn publish(&self, e: &Event, r: &[String]) -> Result<(), String> {
            self.0.publish(e, r).await
        }
        async fn fetch(&self, query: &Query, relays: &[String]) -> Result<Vec<Event>, String> {
            let quick: Vec<String> = relays.iter().filter(|r| *r != self.1).cloned().collect();
            if quick.is_empty() {
                return Err("relay did not answer the fetch".to_string());
            }
            self.0.fetch(query, &quick).await
        }
        async fn fetch_plane(&self, plane: &Keys, query: &Query, relays: &[String]) -> Result<crate::community::transport::PlaneFetch, String> {
            self.0.fetch_plane(plane, query, relays).await
        }
        async fn publish_durable(&self, e: &Event, r: &[String]) -> Result<(), String> {
            self.0.publish_durable(e, r).await
        }
    }

    /// Publishes reach only `to`, as when the other relays drop the write.
    struct WritesOnly<'a>(&'a MemoryRelay, &'static str);
    #[async_trait::async_trait]
    impl Transport for WritesOnly<'_> {
        async fn publish(&self, e: &Event, _r: &[String]) -> Result<(), String> {
            self.0.publish(e, &[self.1.to_string()]).await
        }
        async fn fetch(&self, query: &Query, relays: &[String]) -> Result<Vec<Event>, String> {
            self.0.fetch(query, relays).await
        }
        async fn fetch_plane(&self, plane: &Keys, query: &Query, relays: &[String]) -> Result<crate::community::transport::PlaneFetch, String> {
            self.0.fetch_plane(plane, query, relays).await
        }
        async fn publish_durable(&self, e: &Event, _r: &[String]) -> Result<(), String> {
            self.0.publish_durable(e, &[self.1.to_string()]).await
        }
    }

    #[tokio::test]
    async fn an_unlanded_leave_is_kept_for_the_next_boot() {
        let (_tmp, _guard, _owner) = init_test_db();
        let id = crate::community::CommunityId([7; 32]);
        tombstone_community_list_durable(id, vec!["wss://r".into()], 2_000);
        tombstone_community_list_durable(id, vec!["wss://r".into()], 1_000);
        let pending = load_pending();
        assert_eq!(pending.tombstones.len(), 1, "one pending removal per community");
        assert_eq!(pending.tombstones[0].removed_at, 2_000, "an older retry never replaces a newer removal");
        republish_community_list_durable(Some(id));
        assert_eq!(load_pending().joins.len(), 1, "a join waits for a client rather than being dropped");
    }

    #[tokio::test]
    async fn a_leave_still_on_its_way_is_not_undone_by_the_next_sync() {
        // The leave's tombstone never reached the relays (the app closed mid-retry), so
        // the List still lists the community live. The next sync must not re-adopt it.
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let relays = vec!["wss://r".to_string()];
        let community = create_community(&relay, "Leaving", relays.clone(), None).await.unwrap();
        let hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        tombstone_community_list_durable(*community.id(), relays.clone(), now_ms());
        crate::db::community::delete_community(&hex).unwrap();
        assert!(fetch_fragments(&relay, &relays).await.unwrap().unwrap().list.is_live(&hex), "the relays never heard");

        let outcome = sync_community_list(&relay, &relays).await.unwrap();
        assert!(outcome.joined.is_empty(), "a pending leave is not re-adopted");
        assert!(!crate::db::community::community_exists(community.id()).unwrap());
    }

    /// Yields mid-read, so overlapping writes really interleave as they do on a network.
    struct Yielding<'a>(&'a MemoryRelay);
    #[async_trait::async_trait]
    impl Transport for Yielding<'_> {
        async fn publish(&self, e: &Event, r: &[String]) -> Result<(), String> {
            tokio::task::yield_now().await;
            self.0.publish(e, r).await
        }
        async fn fetch(&self, query: &Query, relays: &[String]) -> Result<Vec<Event>, String> {
            tokio::task::yield_now().await;
            self.0.fetch(query, relays).await
        }
        async fn fetch_plane(&self, plane: &Keys, query: &Query, relays: &[String]) -> Result<crate::community::transport::PlaneFetch, String> {
            self.0.fetch_plane(plane, query, relays).await
        }
        async fn publish_durable(&self, e: &Event, r: &[String]) -> Result<(), String> {
            self.0.publish_durable(e, r).await
        }
    }

    #[tokio::test]
    async fn ten_leaves_at_once_all_land() {
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let relays = vec!["wss://r".to_string()];
        let mut held = Vec::new();
        for i in 0..10 {
            held.push(create_community(&relay, &format!("C{i}"), relays.clone(), None).await.unwrap());
        }
        let net = Yielding(&relay);
        let started = std::time::Instant::now();
        for left in futures_util::future::join_all(held.iter().map(|c| leave_community(&net, c))).await {
            left.unwrap();
        }
        assert!(started.elapsed() < std::time::Duration::from_secs(2), "no leave waits behind another");
        // One background write carries every leave still pending.
        if let Some(t) = load_pending().tombstones.first().cloned() {
            let id = crate::community::CommunityId(crate::simd::hex::hex_to_bytes_32(&t.community_id));
            tombstone_community_list(&net, &id, &relays, t.removed_at, true).await.unwrap();
        }
        assert!(load_pending().tombstones.is_empty(), "the first queued write landed them all");
        let list = fetch_fragments(&relay, &relays).await.unwrap().unwrap().list;
        for c in &held {
            assert!(!list.is_live(&crate::simd::hex::bytes_to_hex_32(&c.id().0)), "every leave landed");
        }
    }

    #[tokio::test]
    async fn rapid_leaves_and_joins_all_land() {
        // Overlapping writes read the same version and publish in the same second; a relay
        // keeps one per coordinate, so unserialized, all but one change is lost.
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let relays = vec!["wss://r".to_string()];
        let a = create_community(&relay, "A", relays.clone(), None).await.unwrap();
        let b = create_community(&relay, "B", relays.clone(), None).await.unwrap();
        let c = create_community(&relay, "C", relays.clone(), None).await.unwrap();
        let net = Yielding(&relay);
        let (left_a, left_b, d) = tokio::join!(
            leave_community(&net, &a),
            leave_community(&net, &b),
            create_community(&net, "D", relays.clone(), None),
        );
        left_a.unwrap();
        left_b.unwrap();
        let d = d.unwrap();
        // What the background queue does: each pending write, waiting its turn.
        for t in load_pending().tombstones {
            let id = crate::community::CommunityId(crate::simd::hex::hex_to_bytes_32(&t.community_id));
            if load_pending().tombstones.iter().any(|p| p.community_id == t.community_id) {
                tombstone_community_list(&net, &id, &relays, t.removed_at, true).await.unwrap();
            }
        }
        for j in load_pending().joins {
            let id = crate::community::CommunityId(crate::simd::hex::hex_to_bytes_32(&j.community_id));
            assert!(republish_community_list_at(&net, Some((&id, j.joined_at)), true).await.unwrap());
        }
        assert!(load_pending().tombstones.is_empty() && load_pending().joins.is_empty(), "everything landed");
        let list = fetch_fragments(&relay, &relays).await.unwrap().unwrap().list;
        let hex = |c: &CommunityV2| crate::simd::hex::bytes_to_hex_32(&c.id().0);
        assert!(!list.is_live(&hex(&a)), "A's leave landed");
        assert!(!list.is_live(&hex(&b)), "B's leave landed");
        assert!(list.is_live(&hex(&c)), "C untouched");
        assert!(list.is_live(&hex(&d)), "D's join landed");
    }

    #[tokio::test]
    async fn a_write_never_replaces_a_copy_it_did_not_read() {
        // A sibling's leave lives only on a relay too slow to answer this device's read,
        // which sees an older copy elsewhere. Writing that stale view back out with a newer
        // created_at would replace the tombstone on every relay and revive the community.
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let relays = vec!["wss://own".to_string(), "wss://slow".to_string()];
        let left = create_community(&relay, "Left", relays.clone(), None).await.unwrap();
        let left_hex = crate::simd::hex::bytes_to_hex_32(&left.id().0);
        leave_community(&WritesOnly(&relay, "wss://slow"), &left).await.unwrap();
        let slow = vec!["wss://slow".to_string()];
        assert!(!fetch_fragments(&relay, &slow).await.unwrap().unwrap().list.is_live(&left_hex), "the leave reached the slow relay");

        create_community(&Slow(&relay, "wss://slow"), "Other", relays.clone(), None).await.unwrap();
        let after = fetch_fragments(&relay, &slow).await.unwrap().unwrap().list;
        assert!(!after.is_live(&left_hex), "the unread tombstone survives this device's write");

        // A read that does reach every relay merges both copies: the leave wins.
        let all = fetch_fragments(&relay, &relays).await.unwrap().unwrap().list;
        assert!(!all.is_live(&left_hex), "a full read keeps the newest removal");
    }

    #[tokio::test]
    async fn an_unconfirmed_empty_read_never_seeds() {
        // One of the account's relays never answers. The aggregate read comes back
        // empty (the healthy relay has nothing), which is indistinguishable from a
        // fresh account — but the dead relay may hold a sibling's tombstones, so
        // seeding here would bury them. The seed must defer, unlatched, and land
        // once every relay confirms empty.
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let relays = vec!["wss://r".to_string(), "wss://dead".to_string()];
        let community = create_community(&relay, "Gated", relays.clone(), None).await.unwrap();
        let cid = crate::simd::hex::bytes_to_hex_32(&community.id().0);

        let bare = MemoryRelay::new();
        let half_deaf = HalfDeaf(&bare, "wss://dead".to_string());
        sync_community_list(&half_deaf, &relays).await.unwrap();
        assert_eq!(bare.stored_count(), 0, "a failed read must never seed");
        assert!(
            crate::db::settings::get_sql_setting(LIST_SEEDED_KEY.to_string()).unwrap().is_none(),
            "a deferred seed must not latch"
        );

        // The relay comes back: every relay now confirms empty, and the seed lands.
        sync_community_list(&bare, &relays).await.unwrap();
        let set = fetch_fragments(&bare, &relays).await.unwrap().expect("the confirmed-empty boot seeds");
        assert!(set.list.is_live(&cid));
        assert!(crate::db::settings::get_sql_setting(LIST_SEEDED_KEY.to_string()).unwrap().is_some());
    }

    #[tokio::test]
    async fn a_leave_tombstones_the_membership_so_sync_does_not_rejoin() {
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let relays = vec!["wss://r".to_string()];
        let community = create_community(&relay, "Left", relays.clone(), None).await.unwrap();
        leave_community(&relay, &community).await.unwrap(); // tombstones the 13302 + deletes

        let rehydrated = sync_community_list(&relay, &relays).await.unwrap().joined;
        assert!(rehydrated.is_empty(), "a tombstoned membership is not rejoined on sync");
    }

    #[tokio::test]
    async fn accepting_the_same_bundle_twice_is_idempotent() {
        // A bot restart or a duplicate invite delivery: accepting the SAME bundle
        // again must upsert cleanly — same community_id, no duplicate channels, no
        // corruption, the keys unchanged.
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Idem", bed.relays.clone(), None).await.unwrap();
        create_public_channel(&bed.relay, &community, "extra").await.unwrap();
        let community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let bundle = serde_json::to_string(&bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None)).unwrap();

        bed.swap_to(&member);
        let first = accept_parked_invite(&bed.relay, &bundle, None).await.unwrap();
        let channels_after_first = first.channels.len();
        let root_after_first = first.community_root;

        // Accept the identical bundle again (restart / redelivery).
        let second = accept_parked_invite(&bed.relay, &bundle, None).await.unwrap();
        assert_eq!(second.id().0, first.id().0, "same community_id");
        assert_eq!(second.channels.len(), channels_after_first, "no duplicate channels on re-accept");
        assert_eq!(second.community_root, root_after_first, "root unchanged");

        // The persisted state is a single clean community with the expected channels.
        let reloaded = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        assert_eq!(reloaded.channels.len(), channels_after_first, "the DB holds one clean channel set");
        assert_eq!(crate::db::community::list_community_ids().unwrap().iter().filter(|id| id.0 == community.id().0).count(), 1, "exactly one community row");
    }

    #[tokio::test]
    async fn a_fresh_joiner_can_authorize_a_moderators_hide_before_any_follow() {
        // The join walk reads the control plane to genesis anyway, and it already
        // folds the full roster for the ban gate. Throwing that roster away left
        // the fresh member's stored roles EMPTY until the follow worker's queued
        // re-walk — and the hide gate reads the stored roster, so every message a
        // moderator had hidden rendered to exactly the person who should never
        // see it: someone who just walked in.
        let (bed, owner, member) = TestBed::new();
        let admin = Keys::generate();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Moderated", bed.relays.clone(), None).await.unwrap();
        grant_admin(&bed.relay, &community, &admin.public_key()).await.unwrap();
        send_direct_invite(&bed.relay, &community, &member.keys.public_key(), None, None).await.unwrap();

        // A FRESH account accepts. No follow_control runs in this test — what the
        // join itself persisted is all the joiner has.
        bed.swap_to(&member);
        let invite = fetch_direct_invite(&bed.relay, &bed.relays, &member.keys.public_key()).await;
        let joined = accept_direct_invite(&bed.relay, &invite).await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&joined.id().0);

        let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
        assert!(!roster.grants.is_empty(), "the join persisted the roster it already folded");
        let owner_hex = joined.owner().unwrap().to_hex();
        let victim = Keys::generate().public_key().to_hex();
        assert!(
            crate::community::moderation::can_hide(Some(&owner_hex), &roster, &admin.public_key().to_hex(), &victim),
            "the admin's hides are honorable on the FIRST history ingest, not after a follow"
        );
        // And the grant's refuse-downgrade floor is seeded, so the citation gate
        // (`actor_authority_pinned`) can resolve the same grant.
        let grant_hex = crate::simd::hex::bytes_to_hex_32(&crate::community::v2::derive::grant_locator(
            joined.id(),
            &admin.public_key().to_bytes(),
        ));
        assert!(
            crate::db::community::get_edition_head(&cid_hex, &grant_hex).unwrap().is_some(),
            "the admin-signed grant head survived the join"
        );
    }

    #[tokio::test]
    async fn a_severed_member_can_be_unbanned_and_re_admitted() {
        // The full moderation HEAL lifecycle: ban (banlist + grant strip + refound)
        // severs a member; the owner then unbans + sends a FRESH invite carrying the
        // NEW root; the member rejoins at the new epoch and converses again. Proves
        // a ban is reversible end-to-end, not a one-way door.
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let mut community = create_community(&bed.relay, "Redeemable", bed.relays.clone(), None).await.unwrap();
        let general = community.channels[0].id;
        send_direct_invite(&bed.relay, &community, &member.keys.public_key(), None, None).await.unwrap();
        send_message(&bed.relay, &community, &general, "owner: welcome").await.unwrap();

        bed.swap_to(&member);
        let invite = fetch_direct_invite(&bed.relay, &bed.relays, &member.keys.public_key()).await;
        let joined = accept_direct_invite(&bed.relay, &invite).await.unwrap();
        assert!(texts_in(&bed.relay, &joined, &general).await.contains(&"owner: welcome".to_string()));

        // Owner bans the member (CORD-04 §6 three-removal) → refound severs them.
        bed.swap_to(&owner);
        set_banlist(&bed.relay, &community, &[member.keys.public_key().to_hex()]).await.unwrap();
        grant_roles(&bed.relay, &community, &member.keys.public_key(), vec![]).await.unwrap();
        community = refound_community(&bed.relay, &community, &[member.keys.public_key()]).await.unwrap();
        assert_eq!(community.root_epoch, Epoch(1));
        send_message(&bed.relay, &community, &general, "owner: after the ban").await.unwrap();

        // The member's follow concludes severance (no blob at the new epoch).
        bed.swap_to(&member);
        let session = crate::db::current_session();
        assert!(follow_rekeys(&bed.relay, &joined, &session).await.unwrap().self_removed, "the member is cryptographically severed");

        // Owner unbans + re-invites: build the fresh epoch-1 bundle (accept it
        // directly, so the test picks the NEW invite unambiguously rather than an
        // arbitrary one of the two pending 3313s).
        bed.swap_to(&owner);
        set_banlist(&bed.relay, &community, &[]).await.unwrap();
        community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        assert_eq!(community.root_epoch, Epoch(1), "the owner's bundle carries epoch 1");
        let fresh_bundle = serde_json::to_string(&bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None)).unwrap();

        // Member accepts the fresh invite → rejoins at epoch 1, reads current + posts.
        bed.swap_to(&member);
        let rejoined = accept_parked_invite(&bed.relay, &fresh_bundle, None).await.unwrap();
        assert_eq!(rejoined.root_epoch, Epoch(1), "rejoined at the current epoch");
        assert_eq!(rejoined.community_root, community.community_root, "holds the NEW root");
        let seen = texts_in(&bed.relay, &rejoined, &general).await;
        assert!(seen.contains(&"owner: after the ban".to_string()), "reads post-ban history with the new root");
        send_message(&bed.relay, &rejoined, &general, "member: i am back").await.unwrap();

        bed.swap_to(&owner);
        community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        assert!(
            texts_in(&bed.relay, &community, &general).await.contains(&"member: i am back".to_string()),
            "the re-admitted member converses again at the new epoch"
        );
        // And they're back in the memberlist.
        let members = memberlist(&bed.relay, &community).await.unwrap();
        assert!(members.contains(&member.keys.public_key()), "the re-admitted member is in the list");
    }

    #[tokio::test]
    async fn dissolution_blocks_a_join() {
        // CORD-02 §9: the owner dissolves; a would-be joiner resolves the grave and
        // refuses to join.
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Doomed", bed.relays.clone(), None).await.unwrap();
        let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
        let bundle_json = serde_json::to_string(&bundle).unwrap();
        dissolve_community(&bed.relay, &community).await.unwrap();
        assert!(crate::db::community::load_community_v2(community.id()).unwrap().unwrap().dissolved, "the owner's local hold is sealed");

        bed.swap_to(&member);
        let err = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap_err();
        assert!(err.contains("dissolved"), "a join refuses a dissolved community: {err}");
    }

    #[tokio::test]
    async fn dissolution_seals_writes_but_not_reads() {
        // CORD-02 §9: sealed means NO further activity, ever. Reads must survive —
        // the history stays browsable, and only explicit user intent deletes it.
        let (bed, owner, _member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Doomed", bed.relays.clone(), None).await.unwrap();
        let general = community.channels[0].id;
        send_message(&bed.relay, &community, &general, "before the end").await.unwrap();

        dissolve_community(&bed.relay, &community).await.unwrap();
        let sealed = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();

        for err in [
            send_message(&bed.relay, &sealed, &general, "after the end").await.unwrap_err(),
            send_reaction(&bed.relay, &sealed, &general, &"a".repeat(64), &"b".repeat(64), crate::community::v2::kind::MESSAGE, "+", None)
                .await
                .unwrap_err(),
            send_edit(&bed.relay, &sealed, &general, &"a".repeat(64), "revised", &[]).await.unwrap_err(),
        ] {
            assert!(err.contains("dissolved"), "every write is refused, got: {err}");
        }
        assert!(
            texts_in(&bed.relay, &sealed, &general).await.contains(&"before the end".to_string()),
            "but the history still reads"
        );
    }

    #[tokio::test]
    async fn only_the_owner_can_dissolve() {
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Mine", bed.relays.clone(), None).await.unwrap();
        bed.swap_to(&member);
        assert!(dissolve_community(&bed.relay, &community).await.is_err(), "only the owner can dissolve");
        assert!(!is_dissolved(&bed.relay, &community).await, "and no tombstone was published");
    }

    #[tokio::test]
    async fn a_foreign_tombstone_is_not_death() {
        // A non-owner sealing the dissolved plane is noise (verify_dissolved is
        // owner-gated), so the community is not treated as dead.
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Safe", vec!["wss://r".into()], None).await.unwrap();
        let rogue = Keys::generate();
        let rumor = crate::community::v2::dissolution::dissolved_tombstone_rumor(rogue.public_key(), community.id(), 1_000);
        let wrap = crate::community::v2::dissolution::seal_dissolved(&rumor, community.id(), &rogue, Timestamp::from_secs(1_000)).unwrap();
        relay.publish(&wrap, &community.relays).await.unwrap();
        assert!(!is_dissolved(&relay, &community).await, "a foreign-signed tombstone is not death");
    }

    #[tokio::test]
    async fn a_public_channel_reads_history_across_a_refounding() {
        // CORD-03 §3: after a Refounding rolls the base root, a Public channel's
        // pre-rotation messages stay readable (the prior epoch's root is archived and
        // the read fans out across held epochs).
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "History", vec!["wss://r".into()], None).await.unwrap();
        let general = community.channels[0].id;
        send_message(&relay, &community, &general, "before the refounding").await.unwrap();

        let refounded = refound_community(&relay, &community, &[]).await.unwrap();
        assert_eq!(refounded.root_epoch, Epoch(1), "the epoch advanced");
        send_message(&relay, &refounded, &general, "after the refounding").await.unwrap();

        let open = texts_in(&relay, &refounded, &general).await;
        assert!(open.contains(&"after the refounding".to_string()), "opening reads the live epoch");
        assert!(
            !open.contains(&"before the refounding".to_string()),
            "and NOT the rotated-past one — that plane is the back-paging cursor's job"
        );
        let paged = all_texts_in(&relay, &refounded, &general).await;
        assert!(paged.contains(&"before the refounding".to_string()), "the epoch-0 message stays reachable by paging");
        assert!(paged.contains(&"after the refounding".to_string()), "alongside the epoch-1 one");
    }

    #[tokio::test]
    async fn refounding_aborts_when_control_state_is_withheld() {
        // B1 coverage gate (CORD-06 §3): a relay serving none of the committed control
        // heads must ABORT the Refounding — never silently drop state (e.g. unban a
        // member at the new epoch a fresh joiner bootstraps).
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Withheld", vec!["wss://good".into()], None).await.unwrap();
        publish_banlist(&relay, &community, &owner, &["cc".repeat(32)], 1).await;
        follow_control(&relay, &community).await.unwrap().updated; // seed the banlist floor

        // Re-point the held community to an EMPTY relay + save, so the Refounding (which
        // reloads fresh state) fetches none of the committed heads.
        let mut moved = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        moved.relays = vec!["wss://empty".into()];
        crate::db::community::save_community_v2(&moved).unwrap();

        let err = refound_community(&relay, &moved, &[]).await.unwrap_err();
        assert!(err.contains("was not served"), "a withheld control head aborts the refounding: {err}");
        assert_eq!(
            crate::db::community::load_community_v2(community.id()).unwrap().unwrap().root_epoch,
            Epoch(0),
            "the epoch did NOT advance (zero published state)"
        );
    }

    #[tokio::test]
    async fn refounding_rolls_the_root_and_severs_a_removed_member() {
        // CORD-06 §3: the owner re-founds, removing a member. The base root rolls, the
        // epoch advances, and the removed member's rekey-follow concludes they're cut.
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Refound", bed.relays.clone(), None).await.unwrap();
        let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
        let bundle_json = serde_json::to_string(&bundle).unwrap();
        bed.swap_to(&member);
        let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();

        bed.swap_to(&owner);
        let refounded = refound_community(&bed.relay, &community, &[member.keys.public_key()]).await.unwrap();
        assert_eq!(refounded.root_epoch, Epoch(1), "the epoch advanced");
        assert_ne!(refounded.community_root, community.community_root, "the base root rolled");
        // The owner still reads the compacted control plane at the new epoch.
        assert_eq!(
            crate::db::community::load_community_v2(community.id()).unwrap().unwrap().root_epoch,
            Epoch(1),
            "the owner committed the new epoch"
        );

        // The removed member, following rekeys, is severed (no blob in the rotation).
        // Guard captured AFTER the swap: it must belong to the ACTING account (the harness
        // swap now bumps the generation exactly like a production swap_session).
        bed.swap_to(&member);
        let session = crate::db::current_session();
        let follow = follow_rekeys(&bed.relay, &joined, &session).await.unwrap();
        assert!(follow.self_removed, "the removed member is cut by the re-founding");
    }

    #[tokio::test]
    async fn a_ban_holding_admin_can_re_found_but_not_evict_a_superior() {
        // CORD-06 §Authority: a Refounding requires BAN, not owner-identity. A
        // non-owner admin granted BAN CAN re-found (and every member follows it —
        // see the receive-side test), but the "strictly outrank every removed
        // target" rule still holds: they can't use it to evict the owner.
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Guarded", bed.relays.clone(), None).await.unwrap();
        let rid = "b0".repeat(32);
        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN), 1).await;
        publish_grant(&bed.relay, &community, &owner.keys, &member.keys.public_key(), vec![rid], 1).await;
        let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
        let bundle_json = serde_json::to_string(&bundle).unwrap();
        bed.swap_to(&member);
        let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
        // Fold the roster so this member's own DB reflects their BAN grant (the
        // authority check reads the folded Roster, not the bundle).
        let _ = follow_control(&bed.relay, &joined).await;
        let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
        // Can't evict the owner (no one outranks the owner).
        assert!(refound_community(&bed.relay, &joined, &[owner.keys.public_key()]).await.is_err(), "a BAN-holder can't re-found to evict the owner");
        // But CAN re-found removing a plain member they outrank (here, nobody).
        assert!(refound_community(&bed.relay, &joined, &[]).await.is_ok(), "a BAN-holding admin can re-found");
    }

    #[tokio::test]
    async fn follow_rekeys_adopts_an_authorized_non_owner_base_rotation() {
        // A BAN-holding ADMIN (not the owner) re-founds, and every member must
        // follow it — owner-only receive silently strands members whose community
        // was refounded by an admin (CORD-06 §Authority: "a Refounding requires
        // BAN", checked against the folded Roster).
        let (bed, owner, me) = TestBed::new();
        let admin = Keys::generate();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "AdminRefound", bed.relays.clone(), None).await.unwrap();
        let rid = "b0".repeat(32);
        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN), 1).await;
        publish_grant(&bed.relay, &community, &owner.keys, &admin.public_key(), vec![rid], 1).await;

        // I (a plain member) join, then fold the roster so I know the admin holds BAN.
        let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
        let bundle_json = serde_json::to_string(&bundle).unwrap();
        bed.swap_to(&me);
        let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
        let _ = follow_control(&bed.relay, &joined).await;
        let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();

        // The admin re-founds keeping the owner + me — the owner must always be a
        // recipient of a non-owner Refounding.
        let new_root = [0xC7; 32];
        publish_base_rotation(&bed.relay, &joined, &admin, &[owner.keys.public_key(), me.keys.public_key()], &new_root, &joined.community_root).await;

        let updated = follow_rekeys(&bed.relay, &joined, &crate::db::current_session()).await.unwrap().updated
            .expect("an authorized admin's Refounding is adopted");
        assert_eq!(updated.root_epoch, Epoch(1), "advanced past the admin's rotation");
        assert_eq!(updated.community_root, new_root, "adopted the admin's fresh root");
    }

    #[tokio::test]
    async fn the_adopted_rotations_minter_owns_the_epochs_snapshot_not_the_owner() {
        // CORD-02 §5: a snapshot is honored "only from the npub whose Refounding
        // minted that epoch". The minter must come from the rotation this device
        // verified and adopted, and once an admin minted the epoch the OWNER holds no
        // snapshot power over it — or the owner could re-seed members the admin cut.
        let (bed, owner, me) = TestBed::new();
        let admin = Keys::generate();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Minter", bed.relays.clone(), None).await.unwrap();
        let rid = "b7".repeat(32);
        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN), 1).await;
        publish_grant(&bed.relay, &community, &owner.keys, &admin.public_key(), vec![rid], 1).await;
        let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
        let bundle_json = serde_json::to_string(&bundle).unwrap();
        bed.swap_to(&me);
        let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
        let _ = follow_control(&bed.relay, &joined).await;
        let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
        publish_base_rotation(&bed.relay, &joined, &admin, &[owner.keys.public_key(), me.keys.public_key()], &[0xC8; 32], &joined.community_root).await;
        let at_1 = follow_rekeys(&bed.relay, &joined, &crate::db::current_session()).await.unwrap().updated.expect("adopted");
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        assert_eq!(
            epoch_minters(&cid_hex).get(&1).map(String::as_str),
            Some(admin.public_key().to_hex().as_str()),
            "adoption records the verified rotator as the epoch's minter"
        );

        // A member the admin's containment cut, and the owner trying to re-seed them.
        let cut = Keys::generate().public_key();
        let survivors = vec![owner.keys.public_key(), me.keys.public_key()];
        let snapshot = |by: PublicKey, members: Vec<PublicKey>, id: u8, at_ms: u64| guestbook::GuestbookEvent {
            epoch: Some(1), observed_at: None, rumor_id: [id; 32],
            entry: guestbook::GuestbookEntry::Snapshot { refounder: by, members, snapshot_id: [id; 32], chunk: (1, 1), at_ms },
        };
        let events = vec![
            guestbook::GuestbookEvent {
                epoch: Some(0), observed_at: None, rumor_id: [0x61; 32],
                entry: guestbook::GuestbookEntry::Join { member: cut, invited_by: None, at_ms: 1_000 },
            },
            snapshot(admin.public_key(), survivors, 0x62, 5_000),
            snapshot(owner.keys.public_key(), vec![cut], 0x63, 6_000),
        ];
        crate::db::community::set_guestbook(&cid_hex, &events, 6).unwrap();
        let members = stored_memberlist(&at_1).unwrap();
        assert!(!members.contains(&cut), "the owner's snapshot holds no power over an epoch the admin minted");
        assert!(members.contains(&me.keys.public_key()), "the minter's survivors stay members");
    }

    #[tokio::test]
    async fn adopting_a_severing_rotation_revokes_my_own_links_instead_of_refreshing_them() {
        // The inverse of the sibling test: a SEVERING refound flips the stable-URL
        // contract. A raid arrives through the door, so every creator's client
        // buries its own links on adopt rather than carrying them into the new
        // epoch — which is the only way the OWNER's link dies when a bot admin ran
        // the containment (only the creator holds a link's signer secret).
        let (bed, owner, me) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "SeverHeal", bed.relays.clone(), None).await.unwrap();
        let rid = "b1".repeat(32);
        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN | Permissions::CREATE_INVITE), 1).await;
        publish_grant(&bed.relay, &community, &owner.keys, &me.keys.public_key(), vec![rid], 1).await;

        let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
        let bundle_json = serde_json::to_string(&bundle).unwrap();
        bed.swap_to(&me);
        let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
        let _ = follow_control(&bed.relay, &joined).await;
        let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();

        let minted = mint_public_link(&bed.relay, &joined, "https://x", None, None).await.unwrap();
        assert!(fetch_public_bundle(&bed.relay, &minted.url).await.is_ok(), "my link is live before the raid");

        // The owner runs a SEVERING refound (the raid lane).
        let new_root = [0xD5; 32];
        publish_severing_base_rotation(&bed.relay, &joined, &owner.keys, &[owner.keys.public_key(), me.keys.public_key()], &new_root, &joined.community_root).await;

        let updated = follow_rekeys(&bed.relay, &joined, &crate::db::current_session()).await.unwrap().updated
            .expect("the owner's severing Refounding is adopted");
        assert_eq!(updated.root_epoch, Epoch(1), "I still advance to the new epoch");

        let err = fetch_public_bundle(&bed.relay, &minted.url).await.unwrap_err();
        assert!(err.contains("revoked"), "my link must be a grave, not a refreshed door: {err}");
        assert!(
            crate::db::community::list_public_invites(&crate::simd::hex::bytes_to_hex_32(&updated.id().0)).unwrap().is_empty(),
            "and the local record goes with it",
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn a_severing_adopt_never_deadlocks_the_last_link_creator() {
        // The severance runs INSIDE the follow, which holds `follow_lock` for the
        // whole call. `revoke_public_link`'s last-live-link escalation re-founds —
        // taking that same non-reentrant lock — so routing severance through it
        // would wedge this community's follow forever, for the very client whose
        // revocation empties the registry (typically the owner). The escalation-free
        // path is the fix; this test is its guard.
        let (bed, owner, me) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "NoDeadlock", bed.relays.clone(), None).await.unwrap();
        let rid = "b2".repeat(32);
        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN | Permissions::CREATE_INVITE), 1).await;
        publish_grant(&bed.relay, &community, &owner.keys, &me.keys.public_key(), vec![rid], 1).await;
        let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
        let bundle_json = serde_json::to_string(&bundle).unwrap();
        bed.swap_to(&me);
        let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
        let _ = follow_control(&bed.relay, &joined).await;
        let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
        // My link is the ONLY one in the registry — revoking it empties the
        // aggregate, which is exactly the escalation's trigger condition.
        let minted = mint_public_link(&bed.relay, &joined, "https://x", None, None).await.unwrap();
        assert!(fetch_public_bundle(&bed.relay, &minted.url).await.is_ok());

        let new_root = [0xD6; 32];
        publish_severing_base_rotation(&bed.relay, &joined, &owner.keys, &[owner.keys.public_key(), me.keys.public_key()], &new_root, &joined.community_root).await;

        let followed = crate::rt::time::timeout(
            std::time::Duration::from_secs(20),
            follow_rekeys(&bed.relay, &joined, &crate::db::current_session()),
        )
        .await
        .expect("the severing follow must not deadlock on follow_lock")
        .unwrap();
        assert_eq!(followed.updated.expect("adopted").root_epoch, Epoch(1));
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn a_severing_adopt_spares_a_link_minted_after_the_raid() {
        // Severance is bounded by the rotation's own wire stamp, not "now". A
        // second device that adopts late must not eat the fresh link the owner
        // minted to re-open the community after the raid was over.
        let (bed, owner, me) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "FreshDoor", bed.relays.clone(), None).await.unwrap();
        let rid = "b3".repeat(32);
        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN | Permissions::CREATE_INVITE), 1).await;
        publish_grant(&bed.relay, &community, &owner.keys, &me.keys.public_key(), vec![rid], 1).await;
        let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
        let bundle_json = serde_json::to_string(&bundle).unwrap();
        bed.swap_to(&me);
        let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
        let _ = follow_control(&bed.relay, &joined).await;
        let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
        let raid_era = mint_public_link(&bed.relay, &joined, "https://old", None, None).await.unwrap();

        let new_root = [0xD7; 32];
        publish_severing_base_rotation(&bed.relay, &joined, &owner.keys, &[owner.keys.public_key(), me.keys.public_key()], &new_root, &joined.community_root).await;
        let updated = follow_rekeys(&bed.relay, &joined, &crate::db::current_session()).await.unwrap().updated.expect("adopted");
        assert!(
            fetch_public_bundle(&bed.relay, &raid_era.url).await.unwrap_err().contains("revoked"),
            "the raid-era link is buried",
        );

        // The raid is over and the owner deliberately re-opens the community. The
        // pending-severance retry runs on every follow, so a door minted after the
        // containment must survive them all — otherwise no one could ever re-open.
        let fresh = mint_public_link(&bed.relay, &updated, "https://new", None, None).await.unwrap();
        let _ = follow_rekeys(&bed.relay, &updated, &crate::db::current_session()).await.unwrap();
        assert!(
            fetch_public_bundle(&bed.relay, &fresh.url).await.is_ok(),
            "a link minted after the containment survives later follow passes",
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn an_unauthorized_severing_rotation_never_touches_my_links() {
        // The sever tag grants no authority of its own: it rides a rotation the
        // adopt gate has already verified. A plain member's forged severing
        // rotation is refused whole, so the tag is never even read.
        let (bed, owner, me) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "NoForge", bed.relays.clone(), None).await.unwrap();
        let rid = "b4".repeat(32);
        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::CREATE_INVITE), 1).await;
        publish_grant(&bed.relay, &community, &owner.keys, &me.keys.public_key(), vec![rid], 1).await;
        let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
        let bundle_json = serde_json::to_string(&bundle).unwrap();
        bed.swap_to(&me);
        let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
        let _ = follow_control(&bed.relay, &joined).await;
        let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
        let minted = mint_public_link(&bed.relay, &joined, "https://x", None, None).await.unwrap();

        // A stranger with no BAN mints a severing rotation.
        let stranger = Keys::generate();
        publish_severing_base_rotation(&bed.relay, &joined, &stranger, &[me.keys.public_key(), owner.keys.public_key()], &[0xD8; 32], &joined.community_root).await;

        let followed = follow_rekeys(&bed.relay, &joined, &crate::db::current_session()).await.unwrap();
        assert!(followed.updated.is_none(), "an unauthorized rotation is not adopted");
        assert!(fetch_public_bundle(&bed.relay, &minted.url).await.is_ok(), "and my link is untouched");
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn a_degraded_plane_read_is_not_evidence_of_absence() {
        // One honest relay is enough to RUN Concord — a sealed, signed rotation is
        // proof on its own. What one relay's silence is NOT enough for is concluding
        // a rotation does not exist. Those two cases used to be the same empty list,
        // so a client that could not reach anyone decided the community had simply
        // stopped rotating, and parked. Coverage is what separates them, and it is
        // measured against the REACHABLE set, so a single-relay community still gets
        // definitive answers.
        use crate::community::transport::adversarial::{AdversarialRelay, Fault, Match};
        let relay = AdversarialRelay::new();
        let (bed, owner, me) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(relay.relay(), "Coverage", bed.relays.clone(), None).await.unwrap();
        let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
        let bundle_json = serde_json::to_string(&bundle).unwrap();
        bed.swap_to(&me);
        let joined = accept_parked_invite(relay.relay(), &bundle_json, None).await.unwrap();
        let _ = follow_control(relay.relay(), &joined).await;
        let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();

        bed.swap_to(&owner);
        publish_base_rotation(relay.relay(), &joined, &owner.keys, &[owner.keys.public_key(), me.keys.public_key()], &[0xE9; 32], &joined.community_root).await;
        bed.swap_to(&me);

        // The plane cannot be reached at all: an Err, not an empty answer.
        let plane = base_rekey_group_key(&joined.community_root, joined.id(), Epoch(1));
        relay.on(Match::author(&plane.pk_hex()), Fault::FailFetch("relay down".into()));
        let _ = follow_rekeys(&relay, &joined, &crate::db::current_session()).await;
        let during = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
        assert_eq!(
            during.root_epoch, joined.root_epoch,
            "an unreachable plane must not advance anything — but it must also not be \
             mistaken for a community that stopped rotating",
        );

        // The relay comes back. The rotation was there the whole time.
        relay.heal();
        let _ = follow_rekeys(&relay, &during, &crate::db::current_session()).await;
        let after = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
        assert_eq!(
            after.root_epoch, Epoch(1),
            "once a relay answers, the rotation it was holding is adopted — the earlier \
             silence was never evidence",
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn a_short_rekey_page_ends_the_walk_only_when_every_relay_answered() {
        // A short page reads as "the plane ends here" — true only if nobody was left
        // out. With a relay unheard, the rotation may sit just past the page, and
        // stopping there parks the member on a dead epoch.
        use crate::community::transport::adversarial::{AdversarialRelay, Fault, Match};
        let (bed, owner, _m) = TestBed::new();
        bed.swap_to(&owner);
        for (fault, expect_found) in [(Fault::ShortUnconfirmed(3), true), (Fault::ShortPage(3), false)] {
            let relay = AdversarialRelay::new();
            let community = create_community(relay.relay(), "Pager", bed.relays.clone(), None).await.unwrap();
            // The genuine rotation, OLDER than everything served on the first page.
            publish_base_rotation(relay.relay(), &community, &owner.keys, &[owner.keys.public_key()], &[0xA1; 32], &community.community_root).await;
            let plane = base_rekey_group_key(&community.community_root, community.id(), Epoch(1));
            for ts in 2_001..=2_005u64 {
                let rumor = stream::build_rumor_secs(1, owner.keys.public_key(), "noise", vec![], ts);
                let seal = stream::build_seal(&rumor, stream::SealForm::Encrypted, &plane, &owner.keys).unwrap();
                let (wrap, _) = stream::wrap_seal(&seal, &plane, stream::KIND_WRAP, Timestamp::from_secs(ts)).unwrap();
                relay.relay().publish(&wrap, &community.relays).await.unwrap();
            }
            let label = format!("{fault:?}");
            relay.on(Match::author(&plane.pk_hex()).nth(1), fault);
            let wraps = plane_wraps_paged(&relay, &community.relays, &plane).await.unwrap();
            let found = wraps.iter().filter_map(|w| stream::open_wrap(w, &plane).ok()).filter_map(|o| rekey::parse_rekey_chunk(&o).ok()).any(|c| c.rotator == owner.keys.public_key());
            assert_eq!(found, expect_found, "{label}: the walk {} past a short first page", if expect_found { "pages on" } else { "stops" });
            // Compared as sets, the shape of a page is nothing to go by.
            let chunks = fetch_rekey_chunks(&relay, &community, &plane).await.unwrap();
            assert!(chunks.iter().any(|c| c.rotator == owner.keys.public_key()), "{label}: through the wraps held");
        }
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn an_older_banlist_edition_can_never_un_ban() {
        // Un-banning is the fail-open direction: the un-banned party's rotations and
        // messages start being honored again. So a stale edition arriving late — a
        // slow relay, a replay, a re-fold under a narrowed window — must never
        // overwrite a newer list. Enforced at the storage layer so no future folding
        // change can reintroduce it.
        let (bed, owner, _me) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "BanMonotonic", bed.relays.clone(), None).await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let villain_keys = Keys::generate();
        let villain = villain_keys.public_key().to_hex();

        crate::db::community::set_community_banlist(&cid_hex, &[villain.clone()], 5).unwrap();
        assert!(crate::db::community::get_community_banlist(&cid_hex).unwrap().contains(&villain));

        // An OLDER edition (version 3) tries to replace it with an empty list.
        crate::db::community::set_community_banlist(&cid_hex, &[], 3).unwrap();
        assert!(
            crate::db::community::get_community_banlist(&cid_hex).unwrap().contains(&villain),
            "a lower-versioned edition must not un-ban",
        );
        assert!(
            crate::db::community::is_author_banned(&cid_hex, &villain_keys.public_key()),
            "and the hot cache must not hold the list we declined to persist",
        );

        // A NEWER edition legitimately un-bans.
        crate::db::community::set_community_banlist(&cid_hex, &[], 6).unwrap();
        assert!(
            !crate::db::community::is_author_banned(&cid_hex, &villain_keys.public_key()),
            "a newer edition still lifts a ban — monotonic, not frozen",
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn a_withholding_relay_cannot_wipe_the_banlist_or_the_roster() {
        // Absence is not evidence. A relay that serves NO control editions folds an
        // empty aggregate, and an empty fold raises no gap flag — nothing is missing
        // from a window that contains nothing. Persisting that would un-ban every
        // banned member and strip every admin, locally, on one bad fetch. Un-banning
        // is the fail-OPEN direction: the un-banned party's rotations start being
        // honored again, which is how one client ends up on a branch minted by
        // someone everyone else has evicted.
        use crate::community::transport::adversarial::{AdversarialRelay, Fault, Match};
        let relay = AdversarialRelay::new();
        let (bed, owner, _me) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(relay.relay(), "WitholdWipe", bed.relays.clone(), None).await.unwrap();
        let rid = "c4".repeat(32);
        let admin = Keys::generate();
        publish_role(relay.relay(), &community, &owner.keys, &admin_role(&rid, Permissions::BAN), 1).await;
        publish_grant(relay.relay(), &community, &owner.keys, &admin.public_key(), vec![rid], 1).await;
        let villain = Keys::generate();
        set_banlist(relay.relay(), &community, &[villain.public_key().to_hex()]).await.unwrap();
        let _ = follow_control(&relay, &community).await;

        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        assert!(
            crate::db::community::get_community_banlist(&cid_hex).unwrap().contains(&villain.public_key().to_hex()),
            "the ban folded",
        );
        let roster_before = crate::db::community::get_community_roles(&cid_hex).unwrap();
        assert!(!roster_before.grants.is_empty(), "the admin's grant folded");

        // Now the control plane serves nothing at all.
        let control_pk = control::ControlPlane::of(&community).pk_hex();
        relay.on(Match::author(&control_pk), Fault::Empty);
        let _ = follow_control(&relay, &community).await;

        assert!(
            crate::db::community::get_community_banlist(&cid_hex).unwrap().contains(&villain.public_key().to_hex()),
            "an empty control window must NEVER un-ban — that is the fail-open direction",
        );
        let roster_after = crate::db::community::get_community_roles(&cid_hex).unwrap();
        assert_eq!(
            roster_after.grants.len(), roster_before.grants.len(),
            "and must never strip standing: an empty fold is absence, not a demotion",
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn a_banned_rotators_refounding_is_never_honored() {
        // Holding a key is never authority (CORD-06 §Authority). A member banned
        // moments ago still holds the current root, so they can mint a perfectly
        // shaped Refounding — right prev_commit, right epoch, real blobs. If a
        // client honors it, the banned party has just re-keyed the community around
        // itself and split every member who folded the ban from every member who
        // did not. The banlist has to be consulted at ADOPT time, not only at send.
        let (bed, owner, me) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "BannedRotator", bed.relays.clone(), None).await.unwrap();
        let rid = "a9".repeat(32);
        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN), 1).await;
        let rogue = Keys::generate();
        publish_grant(&bed.relay, &community, &owner.keys, &rogue.public_key(), vec![rid], 1).await;
        let _ = follow_control(&bed.relay, &community).await;

        let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
        let bundle_json = serde_json::to_string(&bundle).unwrap();
        bed.swap_to(&me);
        let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
        let _ = follow_control(&bed.relay, &joined).await;
        let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();

        // The rogue admin is banned, and we fold that ban.
        bed.swap_to(&owner);
        set_banlist(&bed.relay, &community, &[rogue.public_key().to_hex()]).await.unwrap();
        bed.swap_to(&me);
        let _ = follow_control(&bed.relay, &joined).await;
        let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&joined.id().0);
        assert!(
            crate::db::community::get_community_banlist(&cid_hex).unwrap().contains(&rogue.public_key().to_hex()),
            "the ban folded before the rotation arrives",
        );

        // Still holding the root, the banned admin mints a Refounding anyway.
        bed.swap_to(&owner);
        publish_base_rotation(
            &bed.relay, &joined, &rogue,
            &[owner.keys.public_key(), me.keys.public_key(), rogue.public_key()],
            &[0xBA; 32], &joined.community_root,
        ).await;

        bed.swap_to(&me);
        let held_before = joined.root_epoch;
        let follow = follow_rekeys(&bed.relay, &joined, &crate::db::current_session()).await.unwrap();
        assert!(!follow.self_removed, "a banned rotator can never remove anyone");
        let after = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
        assert_eq!(
            after.root_epoch, held_before,
            "a banned member's rotation must not move the epoch — honoring it hands the community to the party just evicted",
        );
        assert_eq!(after.community_root, joined.community_root, "and must not move the root");
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn a_rekey_exclusion_keeps_my_epoch_keys() {
        // Being removed must not cost me the ability to scrub my own history. The
        // epoch keys open no FUTURE epoch — post-removal keys are never delivered —
        // so retaining them leaks nothing; they are only what lets me author a 3305
        // self-delete of messages I already sent, each sealed under the epoch it was
        // sent at. Every other self-removal path retains them. The rekey-exclusion
        // path silently did not, so an eviction (or a false positive) destroyed that.
        let (bed, owner, me) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "ExclusionKeys", bed.relays.clone(), None).await.unwrap();
        let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
        let bundle_json = serde_json::to_string(&bundle).unwrap();
        bed.swap_to(&me);
        let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
        let _ = follow_control(&bed.relay, &joined).await;
        let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&joined.id().0);
        assert!(
            !crate::db::community::held_epoch_keys(&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX).unwrap().is_empty(),
            "the joiner archived its epoch key",
        );

        // The owner rotates and leaves me out — a genuine, authorized removal.
        bed.swap_to(&owner);
        publish_base_rotation(&bed.relay, &joined, &owner.keys, &[owner.keys.public_key()], &[0xD1; 32], &joined.community_root).await;

        bed.swap_to(&me);
        let follow = follow_rekeys(&bed.relay, &joined, &crate::db::current_session()).await.unwrap();
        assert!(follow.self_removed, "an authorized rotation that excluded me IS a removal");
        // Dated by the rotation, not by when this device noticed it: a rejoin made in between
        // must not be out-dated by a late notice.
        assert_eq!(follow.removed_at, Some(2_000_000), "the rotation's own time (the helper sends it at 2 000 s)");

        // The teardown the caller performs on self_removed.
        crate::db::community::delete_community_retain_keys(&cid_hex).unwrap();
        assert!(
            crate::db::community::load_community_v2(joined.id()).unwrap().is_none(),
            "the community is gone",
        );
        assert!(
            !crate::db::community::held_epoch_keys(&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX).unwrap().is_empty(),
            "but my epoch keys survive, so I can still self-delete what I wrote",
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn a_client_that_adopted_the_losing_fork_converges_down_onto_the_canonical_one() {
        // Two authorized rotators mint the same epoch concurrently. The tiebreak is
        // deterministic — lowest new base key wins — but it only ever ran across
        // rotations seen in ONE fetch. A client that saw only the higher sibling
        // adopted it and then looked exclusively for its successor, so the canonical
        // branch became permanently unreachable: two halves of a community at the
        // same epoch number, different keys, unable to read each other, with nobody
        // misbehaving. Convergence has to be re-checked, not decided once.
        let (bed, owner, me) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "ForkHeal", bed.relays.clone(), None).await.unwrap();
        let rid = "f1".repeat(32);
        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN), 1).await;
        publish_grant(&bed.relay, &community, &owner.keys, &me.keys.public_key(), vec![rid], 1).await;
        let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
        let bundle_json = serde_json::to_string(&bundle).unwrap();
        bed.swap_to(&me);
        let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
        let _ = follow_control(&bed.relay, &joined).await;
        let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();

        // TWO rotators, which is what a real fork requires: rotations correlate on
        // (rotator, scope, epoch, prevcommit), so one rotator minting twice would
        // merge into a single rotation rather than fork — and `mint_or_reuse` stops
        // an honest rotator doing that anyway. A second BAN-holder is the genuine
        // concurrent-refound case. Low wins the spec's tiebreak.
        let rival = Keys::generate();
        bed.swap_to(&owner);
        publish_grant(&bed.relay, &community, &owner.keys, &rival.public_key(), vec!["f1".repeat(32)], 1).await;
        // The owner's client must fold the grant before minting the rival's rotation:
        // a non-owner rotation carries a `vac` citing the Grant it acts under, and an
        // uncited one is inadmissible by design.
        let _ = follow_control(&bed.relay, &community).await;
        bed.swap_to(&me);
        let _ = follow_control(&bed.relay, &joined).await;
        let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();

        let low = [0x11u8; 32];
        let high = [0xF1u8; 32];
        let recipients = [owner.keys.public_key(), me.keys.public_key(), rival.public_key()];
        bed.swap_to(&owner);
        publish_base_rotation(&bed.relay, &joined, &owner.keys, &recipients, &high, &joined.community_root).await;

        // We see ONLY the high sibling first and adopt it — the fork is now set.
        bed.swap_to(&me);
        let session = crate::db::current_session();
        let _ = follow_rekeys(&bed.relay, &joined, &session).await.unwrap();
        let forked = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
        assert_eq!(forked.root_epoch, Epoch(1), "adopted the sibling we could see");
        assert_eq!(forked.community_root, high, "and it is the LOSING branch");

        // The rival BAN-holder's sibling surfaces afterwards — a separate rotation,
        // and the one the deterministic tiebreak says everyone must land on.
        bed.swap_to(&owner);
        publish_base_rotation(&bed.relay, &joined, &rival, &recipients, &low, &joined.community_root).await;

        bed.swap_to(&me);
        let _ = follow_rekeys(&bed.relay, &forked, &session).await.unwrap();
        let healed = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
        assert_eq!(
            healed.community_root, low,
            "a settled epoch MUST converge down onto the canonical sibling, or the community stays split",
        );
        assert_eq!(healed.root_epoch, Epoch(1), "same epoch — this is a sideways step, not an advance");

        // Down-only: re-running must not bounce back up to the higher sibling, or two
        // clients seeing the pair in different orders would oscillate forever.
        let _ = follow_rekeys(&bed.relay, &healed, &session).await.unwrap();
        let settled = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
        assert_eq!(settled.community_root, low, "convergence is down-only and stable");
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn a_deep_catch_up_never_loses_ground_and_lands_on_the_head() {
        // The scenario this program exists for: a member returns after a community
        // rotated hard while they were away, on a link that keeps dropping.
        //
        // This asserts MONOTONICITY and CONVERGENCE — the epoch never moves
        // backward across passes, and the client ends exactly on the head, not one
        // short and not overshooting. Retention of a partial walk is a different
        // property with its own test (see the interrupted-mid-walk case, which fails
        // without per-hop banking); this one would still pass without banking, and
        // is not claiming otherwise.
        use crate::community::transport::adversarial::{AdversarialRelay, Fault, Match};
        const HOPS: u64 = 12;

        let relay = AdversarialRelay::new();
        let (bed, owner, me) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(relay.relay(), "DeepStorm", bed.relays.clone(), None).await.unwrap();
        let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
        let bundle_json = serde_json::to_string(&bundle).unwrap();
        bed.swap_to(&me);
        let joined = accept_parked_invite(relay.relay(), &bundle_json, None).await.unwrap();
        let _ = follow_control(relay.relay(), &joined).await;
        let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();

        // The community rotates HOPS times while we are offline. Owner-signed, so
        // authority is never the variable under test here — reachability is.
        bed.swap_to(&owner);
        let recipients = [owner.keys.public_key(), me.keys.public_key()];
        let mut cur = community.clone();
        let mut planes: Vec<String> = Vec::new();
        for i in 1..=HOPS {
            let root = [(0x40 + i) as u8; 32];
            planes.push(base_rekey_group_key(&cur.community_root, cur.id(), Epoch(i)).pk_hex());
            publish_base_rotation(relay.relay(), &cur, &owner.keys, &recipients, &root, &cur.community_root).await;
            cur.community_root = root;
            cur.root_epoch = Epoch(i);
        }

        // Come back into a storm. The failures are placed MID-WALK on purpose: each
        // pass gets several hops in before dying, so a walk that does not bank as it
        // goes loses a batch of work every time and can never get past the first
        // barrier. Failing only the first ask of each barrier means the link is
        // genuinely recovering, so the only question is whether progress survives.
        bed.swap_to(&me);
        for barrier in [5usize, 9] {
            relay.on(Match::author(&planes[barrier - 1]).nth(1), Fault::FailFetch("flaky link".into()));
        }

        let session = crate::db::current_session();
        let mut last = 0u64;
        // Bounded retries — the point is that each pass strictly advances, so a
        // finite number of them suffices however unlucky the link is.
        for pass in 0..(HOPS * 3) {
            let held = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
            let now = held.root_epoch.0;
            assert!(
                now >= last,
                "pass {pass}: epoch went BACKWARD ({last} -> {now}); a catch-up must never lose ground",
            );
            last = now;
            if now == HOPS {
                break;
            }
            let _ = follow_rekeys(&relay, &held, &session).await;
        }

        let healed = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
        assert_eq!(
            healed.root_epoch, Epoch(HOPS),
            "a deep backlog on a failing link must still converge on the head; stuck at {}",
            healed.root_epoch.0,
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn a_missing_chunk_does_not_block_adopting_the_key_i_already_hold() {
        // Completeness gates ADOPTION today, not just removal. A 1,000-member
        // rotation spans thirteen chunks, so one unreachable chunk parks every
        // member of the community — including everyone whose key is sitting in a
        // chunk they already fetched and can open right now. Requiring the whole set
        // to adopt makes a large community's rotation as fragile as its worst chunk,
        // and the walk is sequential, so the strand blocks every epoch above it too.
        //
        // Completeness is required to conclude REMOVAL, which is destructive and
        // must stay conservative. Adoption is the safe direction: the blob is bound
        // to (scope, epoch) inside its ciphertext, so a key that opens is the key
        // for this rotation whatever else is missing.
        let (bed, owner, me) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "PartialChunks", bed.relays.clone(), None).await.unwrap();
        let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
        let bundle_json = serde_json::to_string(&bundle).unwrap();
        bed.swap_to(&me);
        let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
        let _ = follow_control(&bed.relay, &joined).await;
        let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();

        // A two-chunk rotation where only the chunk carrying MY blob is published.
        bed.swap_to(&owner);
        let new_root = [0xC7u8; 32];
        let new_epoch = Epoch(joined.root_epoch.0 + 1);
        let prev_commit = super::super::derive::epoch_key_commitment(joined.root_epoch, &joined.community_root);
        let group = base_rekey_group_key(&joined.community_root, joined.id(), new_epoch);
        let my_blob = rekey::build_blob_local(
            owner.keys.secret_key(), &owner.keys.public_key().to_bytes(),
            &me.keys.public_key(), RekeyScope::Root, new_epoch, &new_root,
        ).unwrap();
        // Declares 2 chunks; only chunk 1 ever reaches the relay.
        let rumor = rekey::build_rekey_rumor(
            owner.keys.public_key(), RekeyScope::Root, new_epoch, joined.root_epoch,
            &prev_commit, &[my_blob], 1, 2, 2_000,
            my_authority_citation(&joined, &owner.keys.public_key()).as_ref(), false,
        ).unwrap();
        let (wrap, _) = rekey::seal_rekey_chunk(&rumor, &group, &owner.keys, Timestamp::from_secs(2_000)).unwrap();
        bed.relay.publish(&wrap, &bed.relays).await.unwrap();

        bed.swap_to(&me);
        let follow = follow_rekeys(&bed.relay, &joined, &crate::db::current_session()).await.unwrap();
        assert!(!follow.self_removed, "a missing chunk is never a removal");
        let after = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
        assert_eq!(
            after.root_epoch, new_epoch,
            "my blob was present and opened — the missing sibling chunk says nothing about MY key, \
             and parking here strands the whole community behind its least reachable chunk",
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn an_empty_rotation_is_never_a_mass_removal() {
        // `is_complete` is satisfied by a single chunk declaring n=1 — including one
        // carrying ZERO blobs, which the builders emit verbatim for an empty
        // recipient set. Read literally that is "a complete, authorized rotation
        // containing no blob for me", i.e. removal — and the removal path DELETES the
        // community locally, keys and all. From the owner, one such rotation would
        // evict every member of the community at once, irreversibly.
        //
        // Nobody can be removed by a rotation that removed everybody.
        let (bed, owner, me) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "EmptyRotation", bed.relays.clone(), None).await.unwrap();
        let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
        let bundle_json = serde_json::to_string(&bundle).unwrap();
        bed.swap_to(&me);
        let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
        let _ = follow_control(&bed.relay, &joined).await;
        let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();

        // The owner publishes a complete rotation with no recipients at all.
        bed.swap_to(&owner);
        publish_base_rotation(&bed.relay, &joined, &owner.keys, &[], &[0xB0; 32], &joined.community_root).await;

        bed.swap_to(&me);
        let follow = follow_rekeys(&bed.relay, &joined, &crate::db::current_session()).await.unwrap();
        assert!(
            !follow.self_removed,
            "an all-empty rotation must NEVER read as my removal — that path deletes the community",
        );
        assert!(
            crate::db::community::load_community_v2(joined.id()).unwrap().is_some(),
            "and the community must still be held",
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn a_catch_up_interrupted_mid_walk_keeps_the_hops_it_already_took() {
        // A client back from a week offline walks many epochs in one pass. Today the
        // community row is written ONCE, after the loop, so a fetch failure on the
        // last hop discards every hop already walked — the next attempt starts from
        // zero, costs the same again, and on a flaky link may never converge at all.
        // Progress must be banked per hop.
        use crate::community::transport::adversarial::{AdversarialRelay, Fault, Match};
        // The bed supplies isolated per-account DBs; the adversarial relay replaces
        // its transport so a fault plan governs what the client can read back.
        let relay = AdversarialRelay::new();
        let (bed, owner, me) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(relay.relay(), "DeepCatchUp", bed.relays.clone(), None).await.unwrap();

        let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
        let bundle_json = serde_json::to_string(&bundle).unwrap();
        bed.swap_to(&me);
        let joined = accept_parked_invite(relay.relay(), &bundle_json, None).await.unwrap();
        let _ = follow_control(relay.relay(), &joined).await;
        let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();

        // Owner rotates three times while we are away. Owner rotations need no roster.
        bed.swap_to(&owner);
        let mut cur = community.clone();
        let roots = [[0xA1u8; 32], [0xA2; 32], [0xA3; 32]];
        let recipients = [owner.keys.public_key(), me.keys.public_key()];
        for (i, root) in roots.iter().enumerate() {
            publish_base_rotation(relay.relay(), &cur, &owner.keys, &recipients, root, &cur.community_root).await;
            cur.community_root = *root;
            cur.root_epoch = Epoch(i as u64 + 1);
        }

        // Come back, but the plane for the LAST hop is unreachable.
        bed.swap_to(&me);
        let third_hop = base_rekey_group_key(&roots[1], joined.id(), Epoch(3));
        relay.on(Match::author(&third_hop.pk_hex()), Fault::FailFetch("relay dropped".into()));

        let _ = follow_rekeys(&relay, &joined, &crate::db::current_session()).await;

        let after = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
        assert!(
            after.root_epoch.0 >= 2,
            "hops 1 and 2 succeeded and MUST be banked; an interrupted walk that reverts to epoch {} \
             restarts from scratch every attempt and may never converge on a flaky link",
            after.root_epoch.0,
        );

        // Faults cease: the walk resumes from where it banked and reaches the head.
        relay.heal();
        let _ = follow_rekeys(&relay, &after, &crate::db::current_session()).await;
        let healed = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
        assert_eq!(healed.root_epoch, Epoch(3), "once faults cease the walk converges on the head");
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn a_promote_is_reported_as_an_authority_change() {
        // The single line whose absence was the fork. A promote moves the ROSTER,
        // which lives in its own column and never appears in the returned document —
        // so a caller keying its retry off `updated` alone sees "nothing happened",
        // skips the re-walk, and leaves the rekey pass that just refused this admin's
        // rotation to never reconsider it. Asserted at the unit level deliberately:
        // an integration drill can pass for the wrong reason (a roster cached on some
        // earlier pass), and this codebase has been bitten by exactly that before.
        let (bed, owner, admin) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "PromoteReports", bed.relays.clone(), None).await.unwrap();
        follow_control(&bed.relay, &community).await.unwrap(); // settle the baseline

        let rid = "e1".repeat(32);
        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN), 1).await;
        publish_grant(&bed.relay, &community, &owner.keys, &admin.keys.public_key(), vec![rid], 1).await;

        let control = follow_control(&bed.relay, &community).await.unwrap();
        assert!(
            control.authority_changed,
            "a promote MUST report an authority change — this is what re-runs the rekey walk",
        );
        assert!(control.moved(), "and therefore counts as movement");
        assert!(
            control.updated.is_none(),
            "while moving no document at all — which is precisely why `updated` alone was blind",
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn a_seeded_roster_never_vetoes_a_coherent_control_fold() {
        // `merge_local_roster` seeds an optimistic roster at `roles_at = 0` so a
        // just-created role works before its edition folds. That seed names entities
        // the plane may never head, which made `stored_complete` false FOREVER — the
        // roster could never be replaced, and a roster that never updates cannot
        // authorize anyone, so the client silently refused every rotation that admin
        // published. It landed on owners, who seed the most.
        let (bed, owner, admin) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "SeedVeto", bed.relays.clone(), None).await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let rid = "c1".repeat(32);
        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN), 1).await;
        publish_grant(&bed.relay, &community, &owner.keys, &admin.keys.public_key(), vec![rid], 1).await;

        // A seed naming an entity the plane will never head, with NO provenance —
        // exactly what creating a private channel leaves behind.
        let ghost = "d4".repeat(32);
        let mut seeded = crate::community::roles::CommunityRoles::default();
        seeded.roles.push(admin_role(&ghost, Permissions::MANAGE_CHANNELS));
        seeded.grants.push(crate::community::roles::MemberGrant {
            member: owner.keys.public_key().to_hex(),
            role_ids: vec![ghost.clone()],
        });
        crate::db::community::set_community_roles(&cid_hex, &seeded, 0).unwrap();
        // A floor for the ghost is what turns `stored_complete` false.
        crate::db::community::set_edition_head_at_epoch(&cid_hex, &ghost, 1, &[0u8; 32], &[0u8; 32], &[0u8; 32], community.root_epoch.0).unwrap();

        follow_control(&bed.relay, &community).await.unwrap().updated;

        let folded = crate::db::community::get_community_roles(&cid_hex).unwrap();
        assert!(
            folded.grants.iter().any(|g| g.member == admin.keys.public_key().to_hex()),
            "a coherent fold must replace a provenance-less seed, or the client is deaf to this admin forever",
        );
        assert_ne!(
            crate::db::community::get_community_roles_at(&cid_hex).unwrap(),
            0,
            "and the replacement carries the plane's provenance",
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn a_pending_severance_heals_on_a_quiet_follow_pass() {
        // The retry must run on passes that adopt NOTHING. A one-shot transport
        // blip during the original severance otherwise has no healing trigger
        // until some future rotation happens to be adopted — and until then the
        // community reads Public, which silently strips the refound from every
        // ordinary ban.
        let (bed, owner, me) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "QuietHeal", bed.relays.clone(), None).await.unwrap();
        let rid = "b5".repeat(32);
        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN | Permissions::CREATE_INVITE), 1).await;
        publish_grant(&bed.relay, &community, &owner.keys, &me.keys.public_key(), vec![rid], 1).await;
        let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
        let bundle_json = serde_json::to_string(&bundle).unwrap();
        bed.swap_to(&me);
        let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
        let _ = follow_control(&bed.relay, &joined).await;
        let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
        let minted = mint_public_link(&bed.relay, &joined, "https://x", None, None).await.unwrap();

        // A containment was adopted but its revoke was interrupted: the mark is
        // down, the epoch-0 link still stands.
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&joined.id().0);
        add_sever_mark(&cid_hex, 1, 5_000);
        assert!(fetch_public_bundle(&bed.relay, &minted.url).await.is_ok());

        // A QUIET follow — no rotation anywhere — must finish the burial.
        let followed = follow_rekeys(&bed.relay, &joined, &crate::db::current_session()).await.unwrap();
        assert!(followed.updated.is_none(), "nothing to adopt");
        assert!(
            fetch_public_bundle(&bed.relay, &minted.url).await.unwrap_err().contains("revoked"),
            "the interrupted severance healed with no rotation to carry it",
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn a_sever_survives_a_later_ordinary_rotation_in_the_same_walk() {
        // Sticky severance: a client catching up walks EVERY missed rotation in
        // one pass. If the containment hop is followed by an ordinary one,
        // last-hop-wins semantics would refresh the links right back open — the
        // door the raid came through, re-armed with the newest root.
        let (bed, owner, me) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "StickySever", bed.relays.clone(), None).await.unwrap();
        let rid = "b6".repeat(32);
        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN | Permissions::CREATE_INVITE), 1).await;
        publish_grant(&bed.relay, &community, &owner.keys, &me.keys.public_key(), vec![rid], 1).await;
        let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
        let bundle_json = serde_json::to_string(&bundle).unwrap();
        bed.swap_to(&me);
        let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
        let _ = follow_control(&bed.relay, &joined).await;
        let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
        let minted = mint_public_link(&bed.relay, &joined, "https://x", None, None).await.unwrap();

        // Hop 1: the containment. Hop 2: an ordinary rotation on top of it.
        let root1 = [0xE1; 32];
        publish_severing_base_rotation(&bed.relay, &joined, &owner.keys, &[owner.keys.public_key(), me.keys.public_key()], &root1, &joined.community_root).await;
        let mut stepped = joined.clone();
        stepped.community_root = root1;
        stepped.root_epoch = Epoch(1);
        let root2 = [0xE2; 32];
        publish_base_rotation(&bed.relay, &stepped, &owner.keys, &[owner.keys.public_key(), me.keys.public_key()], &root2, &root1).await;

        let updated = follow_rekeys(&bed.relay, &joined, &crate::db::current_session()).await.unwrap().updated.expect("both hops adopt");
        assert_eq!(updated.root_epoch, Epoch(2), "the walk reached the ordinary head");
        assert!(
            fetch_public_bundle(&bed.relay, &minted.url).await.unwrap_err().contains("revoked"),
            "the containment's burial survived the ordinary hop behind it",
        );
    }

    /// Did the severing refound vend `who` a key? Opens the base rotation and looks
    /// for a blob at their locator.
    async fn vended_to(bed: &TestBed, before: &CommunityV2, who: &Keys) -> bool {
        let next = Epoch(before.root_epoch.0 + 1);
        let group = base_rekey_group_key(&before.community_root, before.id(), next);
        let chunks = fetch_rekey_chunks(&bed.relay, &before, &group).await.unwrap();
        rekey::collect_rotations(&chunks).iter().any(|r| {
            rekey::find_my_blobs(
                &r.blobs,
                &r.rotator.to_bytes(),
                &who.public_key().to_bytes(),
                RekeyScope::Root,
                next,
            )
            .next()
            .is_some()
        })
    }

    /// Local guestbook row for `who`, claiming `at_ms` but OBSERVED at `seen`.
    fn local_join_observed(who: &Keys, at_ms: u64, seen: u64, epoch: u64, tag: u8) -> guestbook::GuestbookEvent {
        guestbook::GuestbookEvent {
            rumor_id: [tag; 32],
            entry: guestbook::GuestbookEntry::Join { member: who.public_key(), invited_by: None, at_ms },
            epoch: Some(epoch),
            observed_at: Some(seen),
        }
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn a_backdated_join_cannot_slide_under_the_window_when_we_watched_it_arrive() {
        // `at_ms` is author-claimed, so a raider can put it a year in the past and pass
        // any window computed from the claim alone. What this client WATCHED arrive is
        // not theirs to write.
        let (bed, owner, _o) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Backdate", bed.relays.clone(), None).await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let liar = Keys::generate();

        // Claims it joined long before the window; we saw it arrive INSIDE the window.
        let gb = super::super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
        let join = guestbook::build_join_rumor(liar.public_key(), None, 1_000);
        let (wrap, _) = guestbook::seal_guestbook_rumor(&join, &gb, &liar, Timestamp::from_secs(1)).unwrap();
        bed.relay.publish(&wrap, &bed.relays).await.unwrap();
        crate::db::community::set_guestbook(&cid_hex, &[local_join_observed(&liar, 1_000, 9_000, community.root_epoch.0, 3)], 0).unwrap();
        // We were following well before the window opened.
        crate::db::settings::set_sql_setting(format!("gb_observed_since:{cid_hex}"), "100".into()).unwrap();

        refound_community_severing(&bed.relay, &community, &[], 5_000).await.unwrap();

        assert!(
            !vended_to(&bed, &community, &liar).await,
            "a backdated Join must not beat the arrival we watched with our own clock",
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn a_client_that_started_watching_late_evicts_nobody() {
        // Same row, same claim, same observation — but this client only began following
        // the guestbook AFTER the window opened, so everything looks new to it. Its
        // observations prove nothing, and acting on them would evict the community.
        let (bed, owner, _o) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "LateWatcher", bed.relays.clone(), None).await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let quiet = Keys::generate();

        let gb = super::super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
        let join = guestbook::build_join_rumor(quiet.public_key(), None, 1_000);
        let (wrap, _) = guestbook::seal_guestbook_rumor(&join, &gb, &quiet, Timestamp::from_secs(1)).unwrap();
        bed.relay.publish(&wrap, &bed.relays).await.unwrap();
        crate::db::community::set_guestbook(&cid_hex, &[local_join_observed(&quiet, 1_000, 9_000, community.root_epoch.0, 4)], 0).unwrap();
        // Coverage begins INSIDE the window — we were not here before it.
        crate::db::settings::set_sql_setting(format!("gb_observed_since:{cid_hex}"), "7000".into()).unwrap();

        refound_community_severing(&bed.relay, &community, &[], 5_000).await.unwrap();

        assert!(
            vended_to(&bed, &community, &quiet).await,
            "without coverage predating the window our observations prove nothing — an \
             old member must not be evicted for having been noticed late",
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn a_purge_vends_only_to_the_retain_list_however_late_a_stranger_arrives() {
        // The Admin Terminal hands over a RETAIN list. Internally that used to become a
        // removal list computed from the memberlist at one instant, while the refound
        // fetched its own later — so an account appearing in between was on neither
        // list and got a key by DEFAULT, implicitly retained by the purge meant to be
        // exhaustive. An allow-list closes it with no window and nothing to backdate.
        let (bed, owner, _o) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Purge", bed.relays.clone(), None).await.unwrap();
        let kept = Keys::generate();
        let stranger = Keys::generate();
        let gb = super::super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
        // The stranger even BACKDATES their Join — an allow-list does not care.
        for (who, at_ms) in [(&kept, 2_000_000u64), (&stranger, 1_000u64)] {
            let join = guestbook::build_join_rumor(who.public_key(), None, at_ms);
            let (wrap, _) = guestbook::seal_guestbook_rumor(&join, &gb, who, Timestamp::from_secs(at_ms / 1000)).unwrap();
            bed.relay.publish(&wrap, &bed.relays).await.unwrap();
        }

        // The operator selected exactly one member. Nobody named the stranger.
        refound_community_retaining(&bed.relay, &community, &[], &[kept.public_key()]).await.unwrap();

        assert!(
            vended_to(&bed, &community, &kept).await,
            "the selected member keeps their key",
        );
        assert!(
            !vended_to(&bed, &community, &stranger).await,
            "an account not on the retain list is vended NO key, no matter when it \
             appeared or what Join time it claims",
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn a_raid_window_joiner_is_vended_no_key_even_if_nobody_named_them() {
        // The recipient set is a LIVE fetch taken AFTER the cut was computed, and
        // re-taken on every retry. A bot arriving in that gap is in the memberlist and
        // absent from the cut — and was handed a working key for the very epoch meant
        // to evict it. Testing join TIME catches it with nobody naming it.
        let (bed, owner, _o) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "RaceCut", bed.relays.clone(), None).await.unwrap();
        let established = Keys::generate();
        let late = Keys::generate();
        let gb = super::super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
        for (who, at_ms) in [(&established, 2_000_000u64), (&late, 9_000_000)] {
            let join = guestbook::build_join_rumor(who.public_key(), None, at_ms);
            let (wrap, _) = guestbook::seal_guestbook_rumor(&join, &gb, who, Timestamp::from_secs(at_ms / 1000)).unwrap();
            bed.relay.publish(&wrap, &bed.relays).await.unwrap();
        }

        // Window opens at 5_000s. `late` is named by NOBODY — the cut is empty.
        refound_community_severing(&bed.relay, &community, &[], 5_000).await.unwrap();

        assert!(
            !vended_to(&bed, &community, &late).await,
            "a raid-window joiner must be vended NO key, even when nobody named them",
        );
        assert!(
            vended_to(&bed, &community, &established).await,
            "and the member who was already here keeps theirs",
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn a_member_whose_join_is_not_on_the_plane_is_never_read_as_a_late_joiner() {
        // THE regression that matters. A quiet member's Join lives on a buried epoch,
        // so the reachable guestbook has no trace of them at all. Absence must read as
        // OLD, never as new — reading it the other way shed 39 real members across five
        // rotations. Here the Join exists ONLY locally, exactly as a buried one does.
        let (bed, owner, _o) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Buried", bed.relays.clone(), None).await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let quiet = Keys::generate();
        let local_join = guestbook::GuestbookEvent {
            rumor_id: [7u8; 32],
            entry: guestbook::GuestbookEntry::Join { member: quiet.public_key(), invited_by: None, at_ms: 9_900_000 },
            epoch: Some(community.root_epoch.0),
            observed_at: None,
        };
        crate::db::community::set_guestbook(&cid_hex, &[local_join], 0).unwrap();

        // Even stamped INSIDE the window, a Join the plane does not serve must not evict.
        refound_community_severing(&bed.relay, &community, &[], 5_000).await.unwrap();

        assert!(
            vended_to(&bed, &community, &quiet).await,
            "no Join on the reachable plane means OLD — absence of evidence must never evict",
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn a_member_who_rejoined_inside_the_window_is_not_cut() {
        let (bed, owner, _other) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Rejoin", bed.relays.clone(), None).await.unwrap();
        mint_public_link(&bed.relay, &community, "https://x", None, None).await.unwrap();
        let veteran = Keys::generate();
        let raider = Keys::generate();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        // The veteran's first Join, from an earlier epoch: held locally, gone from the plane.
        let old = guestbook::GuestbookEvent {
            epoch: Some(0),
            observed_at: None,
            rumor_id: [7u8; 32],
            entry: guestbook::GuestbookEntry::Join { member: veteran.public_key(), invited_by: None, at_ms: 1_000_000 },
        };
        crate::db::community::store_guestbook_events(&cid_hex, &[old], 0).unwrap();
        let gb = super::super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
        for (who, at_ms) in [(&veteran, 9_000_000u64), (&raider, 9_500_000)] {
            let join = guestbook::build_join_rumor(who.public_key(), None, at_ms);
            let (wrap, _) = guestbook::seal_guestbook_rumor(&join, &gb, who, Timestamp::from_secs(at_ms / 1000)).unwrap();
            bed.relay.publish(&wrap, &bed.relays).await.unwrap();
        }

        let report = contain_raid(&bed.relay, community.id(), &[raider.public_key()], 5_000, &[]).await.unwrap();
        assert_eq!(report.window_cut, 0, "the veteran's re-Join is not their arrival");
        let updated = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let members = memberlist(&bed.relay, &updated).await.unwrap();
        assert!(members.contains(&veteran.public_key()), "the veteran rides into the new epoch");
        assert!(!members.contains(&raider.public_key()));
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn a_snapshot_a_raider_forged_does_not_date_their_arrival() {
        let (bed, owner, _other) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Forged", bed.relays.clone(), None).await.unwrap();
        mint_public_link(&bed.relay, &community, "https://x", None, None).await.unwrap();
        let raider = Keys::generate();
        let lurker = Keys::generate();
        let gb = super::super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
        for (who, at_ms) in [(&raider, 9_000_000u64), (&lurker, 9_500_000)] {
            let join = guestbook::build_join_rumor(who.public_key(), None, at_ms);
            let (wrap, _) = guestbook::seal_guestbook_rumor(&join, &gb, who, Timestamp::from_secs(at_ms / 1000)).unwrap();
            bed.relay.publish(&wrap, &bed.relays).await.unwrap();
        }
        // The lurker claims an ancient snapshot that already listed them.
        for rumor in guestbook::build_snapshot_rumors(lurker.public_key(), &[lurker.public_key()], [9u8; 32], 1_000_000) {
            let (wrap, _) = guestbook::seal_guestbook_rumor(&rumor, &gb, &lurker, Timestamp::from_secs(1_000)).unwrap();
            bed.relay.publish(&wrap, &bed.relays).await.unwrap();
        }

        let report = contain_raid(&bed.relay, community.id(), &[raider.public_key()], 5_000, &[]).await.unwrap();
        assert_eq!(report.window_cut, 1, "only someone who may rotate the base can vouch for an arrival");
        let updated = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        assert!(!memberlist(&bed.relay, &updated).await.unwrap().contains(&lurker.public_key()));
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn contain_raid_bans_cuts_and_severs_end_to_end() {
        let (bed, owner, _other) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Containment", bed.relays.clone(), None).await.unwrap();
        let minted = mint_public_link(&bed.relay, &community, "https://x", None, None).await.unwrap();

        // Three arrivals: an established member (before the window), a convicted
        // raider and a quiet lurker (both inside it).
        let established = Keys::generate();
        let raider = Keys::generate();
        let lurker = Keys::generate();
        let gb = super::super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
        for (who, at_ms) in [(&established, 2_000_000u64), (&raider, 9_000_000), (&lurker, 9_500_000)] {
            let join = guestbook::build_join_rumor(who.public_key(), None, at_ms);
            let (wrap, _) = guestbook::seal_guestbook_rumor(&join, &gb, who, Timestamp::from_secs(at_ms / 1000)).unwrap();
            bed.relay.publish(&wrap, &bed.relays).await.unwrap();
        }

        let report = contain_raid(&bed.relay, community.id(), &[raider.public_key()], 5_000, &[]).await.unwrap();
        assert_eq!(report.banned, 1, "the convicted raider is banned");
        assert_eq!(report.window_cut, 1, "the lurker who joined inside the window is cut");
        assert!(report.refound_ok, "the severing refound landed: {:?}", report.warnings);
        assert_eq!((report.epoch_before, report.epoch_after), (0, 1), "the root rolled");
        assert_eq!(report.own_links_revoked, 1, "the door closed with it");

        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let banlist = crate::db::community::get_community_banlist(&cid_hex).unwrap();
        assert!(banlist.contains(&raider.public_key().to_hex()), "raider on the banlist");
        assert!(!banlist.contains(&lurker.public_key().to_hex()), "the lurker is cut, never banned — they can rejoin through a fresh link");
        assert!(!banlist.contains(&established.public_key().to_hex()));
        assert!(
            fetch_public_bundle(&bed.relay, &minted.url).await.unwrap_err().contains("revoked"),
            "the invite URL the raid used is a grave",
        );

        // The rotation's recipient set is the severance line: the established
        // member rides into the new epoch, the raider and the lurker do not.
        let updated = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        assert_eq!(updated.root_epoch, Epoch(1));
        let members = memberlist(&bed.relay, &updated).await.unwrap();
        assert!(members.contains(&established.public_key()), "established member survives");
        assert!(!members.contains(&raider.public_key()), "raider gone");
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn adopting_someone_elses_rotation_refreshes_my_own_live_links() {
        // CORD-05 §2: a link shared once keeps working across rotations, because
        // its bundle is re-posted behind the same URL. The Refounder can only
        // refresh the bundles they hold signer secrets for — their OWN — so
        // every other creator has to heal their links when they ADOPT the
        // rotation. Without that, an admin's links keep vending the superseded
        // root and drop new joiners onto a dead epoch, which is precisely the
        // stranding the stable-URL refresh exists to prevent.
        let (bed, owner, me) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "LinkHeal", bed.relays.clone(), None).await.unwrap();
        let rid = "b1".repeat(32);
        // CREATE_INVITE too: minting is offer-gated by the same bit readers use.
        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN | Permissions::CREATE_INVITE), 1).await;
        publish_grant(&bed.relay, &community, &owner.keys, &me.keys.public_key(), vec![rid], 1).await;

        let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
        let bundle_json = serde_json::to_string(&bundle).unwrap();
        bed.swap_to(&me);
        let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
        let _ = follow_control(&bed.relay, &joined).await;
        let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();

        // I mint a link of my own at the CURRENT epoch.
        let minted = mint_public_link(&bed.relay, &joined, "https://x", None, None).await.unwrap();
        let vended_before = fetch_public_bundle(&bed.relay, &minted.url).await.unwrap();
        assert_eq!(vended_before.root_epoch, 0, "my link vends the epoch I minted it at");

        // The OWNER re-founds. Their refresh can't touch my bundle: only I hold
        // its signer secret.
        let new_root = [0xD4; 32];
        publish_base_rotation(&bed.relay, &joined, &owner.keys, &[owner.keys.public_key(), me.keys.public_key()], &new_root, &joined.community_root).await;

        let updated = follow_rekeys(&bed.relay, &joined, &crate::db::current_session()).await.unwrap().updated
            .expect("the owner's Refounding is adopted");
        assert_eq!(updated.root_epoch, Epoch(1), "I advanced to the new epoch");

        let vended_after = fetch_public_bundle(&bed.relay, &minted.url).await.unwrap();
        assert_eq!(vended_after.root_epoch, 1, "my link must now vend the NEW epoch, not strand its joiners");
        assert_eq!(
            crate::simd::hex::hex_to_bytes_32(&vended_after.community_root),
            new_root,
            "and the new root behind the same URL",
        );
    }

    #[tokio::test]
    async fn follow_rekeys_refuses_a_refounding_that_excludes_the_owner() {
        // Authority escalation: a BAN-admin can't use a Refounding to evict the
        // OWNER (no one outranks the owner). Excluding them makes the rotation
        // inadmissible — members fork-reject it rather than migrate to the coup.
        let (bed, owner, me) = TestBed::new();
        let admin = Keys::generate();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "NoCoup", bed.relays.clone(), None).await.unwrap();
        let rid = "b0".repeat(32);
        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN), 1).await;
        publish_grant(&bed.relay, &community, &owner.keys, &admin.public_key(), vec![rid], 1).await;

        let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
        let bundle_json = serde_json::to_string(&bundle).unwrap();
        bed.swap_to(&me);
        let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
        let _ = follow_control(&bed.relay, &joined).await;
        let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();

        // The admin re-founds delivering to me but NOT the owner — a takeover.
        publish_base_rotation(&bed.relay, &joined, &admin, &[me.keys.public_key()], &[0xEE; 32], &joined.community_root).await;
        let follow = follow_rekeys(&bed.relay, &joined, &crate::db::current_session()).await.unwrap();
        assert!(follow.updated.is_none() && !follow.self_removed, "an owner-excluding Refounding is not adopted");
    }

    #[tokio::test]
    async fn follow_rekeys_refuses_a_refounding_that_excludes_a_peer_admin() {
        // Authority escalation: two equal-rank BAN-admins — neither strictly
        // outranks the other, so one can't Refound the other out. Excluding a
        // peer makes the rotation inadmissible.
        let (bed, owner, me) = TestBed::new();
        let admin_a = Keys::generate();
        let admin_b = Keys::generate(); // the peer admin the rotation excludes.
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Peers", bed.relays.clone(), None).await.unwrap();
        let rid = "b0".repeat(32);
        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN), 1).await;
        // Both A and B hold the SAME role (same position 1) → peers.
        publish_grant(&bed.relay, &community, &owner.keys, &admin_a.public_key(), vec![rid.clone()], 1).await;
        publish_grant(&bed.relay, &community, &owner.keys, &admin_b.public_key(), vec![rid], 1).await;

        let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
        let bundle_json = serde_json::to_string(&bundle).unwrap();
        bed.swap_to(&me);
        let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
        let _ = follow_control(&bed.relay, &joined).await;
        let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();

        // Admin A re-founds keeping the owner + me but EXCLUDING peer admin B.
        publish_base_rotation(&bed.relay, &joined, &admin_a, &[owner.keys.public_key(), me.keys.public_key()], &[0xDD; 32], &joined.community_root).await;

        let follow = follow_rekeys(&bed.relay, &joined, &crate::db::current_session()).await.unwrap();
        assert!(follow.updated.is_none() && !follow.self_removed, "excluding an equal-rank peer admin is inadmissible");
    }

    #[tokio::test]
    async fn a_retried_refounding_reuses_the_same_root() {
        // B1 idempotency: minting for the same (scope, epoch) twice yields the SAME
        // root, so a retried Refounding re-delivers one root — never a double-mint fork.
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Retry", vec!["wss://r".into()], None).await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let first = mint_or_reuse_rotation_key(&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX, 1).unwrap();
        let second = mint_or_reuse_rotation_key(&cid_hex, crate::community::SERVER_ROOT_SCOPE_HEX, 1).unwrap();
        assert_eq!(first, second, "a retry reuses the archived root, never double-mints");
    }

    fn role_at(id: &str, name: &str, position: u32, bits: u64) -> Role {
        Role { role_id: id.into(), name: name.into(), position, permissions: Permissions(bits), scope: RoleScope::Server, color: 0, rank: None, display: false, mentionable: false, extra: Default::default() }
    }

    #[tokio::test]
    async fn a_role_carrying_a_bit_its_author_lacks_never_folds_whatever_history_is_served() {
        // CORD-04 §3, strict: a role carries only bits its author holds through roles above
        // it, judged on the edition alone. Every reader reaches one verdict: the whole chain,
        // the compacted head alone, or a device whose floor sits on the refused head.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Subset", vec!["wss://r".into()], None).await.unwrap();
        let (mgr, banner) = (Keys::generate(), Keys::generate());
        let (rmgr, rban_mgr, rban_bits) = ("a2".repeat(32), "a3".repeat(32), "a4".repeat(32));
        publish_role(&relay, &community, &owner, &role_at(&rmgr, "Mgr", 2, Permissions::MANAGE_ROLES | Permissions::KICK), 1).await;
        // The banner's authority spans two roles: MANAGE_ROLES from one, BAN from the next.
        publish_role(&relay, &community, &owner, &role_at(&rban_mgr, "Bmgr", 3, Permissions::MANAGE_ROLES), 1).await;
        publish_role(&relay, &community, &owner, &role_at(&rban_bits, "Bbits", 4, Permissions::BAN), 1).await;
        publish_grant(&relay, &community, &owner, &mgr.public_key(), vec![rmgr.clone()], 1).await;
        publish_grant(&relay, &community, &owner, &banner.public_key(), vec![rban_mgr.clone(), rban_bits.clone()], 1).await;
        let (kick_id, ban_id, ping_id, banner_minted) = ("b1".repeat(32), "b2".repeat(32), "b3".repeat(32), "b4".repeat(32));
        publish_role(&relay, &community, &mgr, &role_at(&kick_id, "Kickers", 5, Permissions::KICK), 1).await;
        publish_role(&relay, &community, &mgr, &role_at(&ban_id, "Banners", 6, Permissions::BAN), 1).await;
        // A social bit the manager lacks: not every gated bit is a staff bit.
        publish_role(&relay, &community, &mgr, &role_at(&ping_id, "Pingers", 6, Permissions::MENTION_EVERYONE), 1).await;
        publish_role(&relay, &community, &banner, &role_at(&banner_minted, "Bans2", 6, Permissions::BAN), 1).await;
        // An owner-made role with BAN beneath everyone, renamed at v2 by each of them.
        let (renamed_by_mgr, renamed_by_banner) = ("c1".repeat(32), "c2".repeat(32));
        for (id, by) in [(&renamed_by_mgr, &mgr), (&renamed_by_banner, &banner)] {
            publish_role(&relay, &community, &owner, &role_at(id, "Original", 7, Permissions::BAN), 1).await;
            publish_role(&relay, &community, by, &role_at(id, "Renamed", 7, Permissions::BAN), 2).await;
        }

        let editions = fetch_control(&relay, &community).await;
        let full = fold_authority(&community, &editions, &load_floors(&community));
        assert!(full.roles.role(&kick_id).is_some(), "a role carrying only held bits folds");
        assert!(full.roles.role(&ban_id).is_none(), "a role carrying a bit its minter lacks never folds");
        assert!(full.roles.role(&ping_id).is_none(), "nor one carrying a social bit they lack");
        assert!(full.roles.role(&banner_minted).is_some(), "bits from every role above count, not just the highest");
        assert_eq!(full.roles.role(&renamed_by_mgr).unwrap().name, "Original", "a manager without BAN can't rename a role that bans");
        assert_eq!(full.roles.role(&renamed_by_banner).unwrap().name, "Renamed", "one holding BAN can");

        // A fresh joiner after a Refounding holds only the heads.
        let is_v1_of = |e: &ParsedEdition, ids: &[&String]| e.version == 1 && ids.contains(&&crate::simd::hex::bytes_to_hex_32(&e.entity_id));
        let heads_only: Vec<ParsedEdition> = editions.iter().filter(|e| !is_v1_of(e, &[&renamed_by_mgr, &renamed_by_banner])).cloned().collect();
        let fresh = fold_authority(&community, &heads_only, &load_floors(&community));
        assert_eq!(fresh.roles.role(&renamed_by_banner).map(|r| r.name.as_str()), Some("Renamed"), "the same verdict from the head alone");
        assert!(fresh.roles.role(&renamed_by_mgr).is_none(), "and the refused rename stays refused");

        // A device whose floor sits on the refused v2 folds what a reader without it folds.
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        follow_control(&relay, &community).await.unwrap();
        let refused = editions.iter().find(|e| e.version == 2 && crate::simd::hex::bytes_to_hex_32(&e.entity_id) == renamed_by_mgr).unwrap();
        crate::db::community::set_edition_head_at_epoch(&cid_hex, &renamed_by_mgr, 2, &refused.self_hash, &refused.inner_id, &mgr.public_key().to_bytes(), community.root_epoch.0).unwrap();
        let tracked = fold_authority(&community, &editions, &load_floors(&community));
        assert!(tracked.complete, "every floored head is served");
        assert_eq!(tracked.roles.role(&renamed_by_mgr).map(|r| r.name.as_str()), Some("Original"), "the floor yields to the newest admitted edition");
        let head = tracked.heads.iter().find(|h| h.entity_hex == renamed_by_mgr).unwrap();
        assert!(head.rebased && head.version == 1);
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        follow_control(&relay, &held).await.unwrap();
        assert_eq!(floor_of(&community, &crate::simd::hex::hex_to_bytes_32_checked(&renamed_by_mgr).unwrap()).0, 1, "and the floor moves down to it");
    }

    #[tokio::test]
    async fn the_fold_has_one_answer_whatever_else_a_reader_holds() {
        // A role that props up its own authority made the fixpoint oscillate, so the round
        // bound picked the phase and readers holding a different number of entities split.
        // Downward support breaks the loop: B's MANAGE_ROLES comes from a role beneath R2.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Fixpoint", vec!["wss://r".into()], None).await.unwrap();
        let (a, b) = (Keys::generate(), Keys::generate());
        let (ra, r2, rb, r3) = ("d1".repeat(32), "d2".repeat(32), "d3".repeat(32), "d4".repeat(32));
        publish_role(&relay, &community, &owner, &role_at(&ra, "RA", 3, Permissions::MANAGE_ROLES), 1).await;
        publish_role(&relay, &community, &owner, &role_at(&r2, "R2", 5, Permissions::KICK), 1).await;
        publish_role(&relay, &community, &owner, &role_at(&rb, "RB", 4, 0), 1).await;
        publish_grant(&relay, &community, &owner, &a.public_key(), vec![ra.clone(), r2.clone()], 1).await;
        publish_role(&relay, &community, &a, &role_at(&r3, "R3", 6, Permissions::MANAGE_ROLES | Permissions::KICK), 1).await;
        publish_grant(&relay, &community, &owner, &b.public_key(), vec![rb.clone(), r3.clone()], 1).await;
        publish_role(&relay, &community, &b, &role_at(&r2, "R2", 5, 0), 2).await;

        let editions = fetch_control(&relay, &community).await;
        let floors = load_floors(&community);
        let base = fold_authority(&community, &editions, &floors);
        assert!(base.converged, "the fold settles rather than running out its bound");
        assert!(base.roles.role(&r2).unwrap().permissions.contains(Permissions::KICK), "B can't strip R2 on authority from a role beneath it");
        assert!(base.roles.roles_of(&b.public_key().to_hex()).any(|r| r.role_id == r3), "and B keeps R3");
        // Unrelated extra entities change nothing about the rest.
        let mut extra = editions.clone();
        for (i, id) in ["d7", "d8", "d9"].iter().enumerate() {
            publish_role(&relay, &community, &owner, &role_at(&id.repeat(32), "Extra", 9 + i as u32, 0), 1).await;
        }
        extra.extend(fetch_control(&relay, &community).await.into_iter().filter(|e| !editions.iter().any(|x| x.self_hash == e.self_hash)));
        let more = fold_authority(&community, &extra, &floors);
        let mut trimmed = more.roles.clone();
        trimmed.roles.retain(|r| !["d7", "d8", "d9"].iter().any(|p| r.role_id == p.repeat(32)));
        let fp = |roles: &crate::community::roles::CommunityRoles| {
            let mut rs = roles.roles.clone();
            rs.sort_by(|x, y| x.role_id.cmp(&y.role_id));
            let mut gs = roles.grants.clone();
            gs.sort_by(|x, y| x.member.cmp(&y.member));
            serde_json::json!({ "roles": rs, "grants": gs }).to_string()
        };
        assert_eq!(fp(&trimmed), fp(&base.roles), "the roster is the same whatever else a reader holds");
    }

    #[tokio::test]
    async fn a_strip_is_judged_against_the_rank_the_member_stood_at() {
        // A grant edition acts on the member as the previous grant left them: a manager at 5
        // can't rewrite the grant of a member a senior role puts at 2.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Standing", vec!["wss://r".into()], None).await.unwrap();
        let (mgr, senior_member) = (Keys::generate(), Keys::generate().public_key());
        let (rsen, rmgr, rlow) = ("a1".repeat(32), "a5".repeat(32), "a9".repeat(32));
        publish_role(&relay, &community, &owner, &role_at(&rsen, "Senior", 2, 0), 1).await;
        publish_role(&relay, &community, &owner, &role_at(&rmgr, "Mgr", 5, Permissions::MANAGE_ROLES), 1).await;
        publish_role(&relay, &community, &owner, &role_at(&rlow, "Low", 9, 0), 1).await;
        publish_grant(&relay, &community, &owner, &senior_member, vec![rsen.clone()], 1).await;
        publish_grant(&relay, &community, &owner, &mgr.public_key(), vec![rmgr.clone()], 1).await;
        publish_grant(&relay, &community, &mgr, &senior_member, vec![rlow.clone()], 2).await;
        // And a manager re-granting themselves only a lower role is acting on their own standing.
        publish_grant(&relay, &community, &mgr, &mgr.public_key(), vec![rlow.clone()], 2).await;

        let a = fold_authority(&community, &fetch_control(&relay, &community).await, &load_floors(&community));
        assert!(a.converged);
        assert_eq!(a.roles.highest_position(&senior_member.to_hex()), Some(2), "the senior member keeps their rank");
        assert_eq!(a.roles.highest_position(&mgr.public_key().to_hex()), Some(5), "nobody rewrites their own standing");
    }

    #[tokio::test]
    async fn a_device_holding_a_floor_judges_its_head_with_the_full_chain_behind_it() {
        // The floored version is replayed after its predecessors, so a tracking device
        // judges it as a reader without the floor does.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Replay", vec!["wss://r".into()], None).await.unwrap();
        let (x, m) = (Keys::generate(), Keys::generate().public_key());
        let (rx, radm, rlow) = ("b1".repeat(32), "b2".repeat(32), "b6".repeat(32));
        publish_role(&relay, &community, &owner, &role_at(&rx, "X", 1, Permissions::MANAGE_ROLES), 1).await;
        publish_role(&relay, &community, &owner, &role_at(&radm, "Adm2", 2, 0), 1).await;
        publish_role(&relay, &community, &owner, &role_at(&rlow, "Low", 60, 0), 1).await;
        publish_grant(&relay, &community, &owner, &x.public_key(), vec![rx.clone()], 1).await;
        publish_grant(&relay, &community, &owner, &m, vec![radm.clone()], 1).await;
        publish_grant(&relay, &community, &x, &m, vec![rlow.clone()], 2).await;
        follow_control(&relay, &community).await.unwrap();
        let geid = crate::community::v2::derive::grant_locator(community.id(), &m.to_bytes());
        assert_eq!(floor_of(&community, &geid).0, 2, "everyone took X's v2 while X ranked at 1");

        // X drops to 10: X's v2 no longer outranks the member as v1 left them.
        publish_role(&relay, &community, &owner, &role_at(&rx, "X", 10, Permissions::MANAGE_ROLES), 2).await;
        let editions = fetch_control(&relay, &community).await;
        let cold = fold_authority(&community, &editions, &Default::default());
        let tracked = fold_authority(&community, &editions, &load_floors(&community));
        assert_eq!(cold.roles.highest_position(&m.to_hex()), Some(2), "a cold reader replays v1, then refuses v2");
        assert_eq!(tracked.roles.highest_position(&m.to_hex()), Some(2), "the tracking device agrees");
        assert!(tracked.heads.iter().any(|h| h.entity_hex == crate::simd::hex::bytes_to_hex_32(&geid) && h.rebased && h.version == 1));
    }

    #[tokio::test]
    async fn a_chain_refused_whole_on_complete_evidence_settles_and_locks_nothing() {
        // Everything an admin authored alone falls when they lose the bit. On a complete
        // fold that is a verdict, not a gap: the roster drops it, the cache moves on, and the
        // owner can still manage the member it touched.
        let (bed, owner, _m) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Settled", bed.relays.clone(), None).await.unwrap();
        let admin = Keys::generate();
        let member = Keys::generate().public_key();
        let (radm, rmade) = ("c1".repeat(32), "c2".repeat(32));
        publish_role(&bed.relay, &community, &owner.keys, &role_at(&radm, "Adm", 1, Permissions::MANAGE_ROLES), 1).await;
        publish_grant(&bed.relay, &community, &owner.keys, &admin.public_key(), vec![radm.clone()], 1).await;
        publish_role(&bed.relay, &community, &admin, &role_at(&rmade, "Made", 5, 0), 1).await;
        publish_grant(&bed.relay, &community, &admin, &member, vec![rmade.clone()], 1).await;
        follow_control(&bed.relay, &community).await.unwrap();
        let geid = crate::simd::hex::bytes_to_hex_32(&crate::community::v2::derive::grant_locator(community.id(), &member.to_bytes()));
        assert!(load_floors(&community).contains_key(&geid) && load_floors(&community).contains_key(&rmade));

        // The admin is stripped: the role and the grant they authored have nothing left.
        publish_grant(&bed.relay, &community, &owner.keys, &admin.public_key(), vec![], 2).await;
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        follow_control(&bed.relay, &held).await.unwrap();
        let a = fold_authority(&held, &fetch_control(&bed.relay, &held).await, &load_floors(&held));
        assert!(a.complete && a.refused.contains(&rmade) && a.refused.contains(&geid), "both settle as refused");
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let cached = crate::db::community::get_community_roles(&cid_hex).unwrap();
        assert!(cached.role(&rmade).is_none(), "the cached roster moves on");
        // The owner manages the member without a "could not be fetched" lockout.
        set_member_roles(&bed.relay, &held, &member, vec![radm.clone()]).await.expect("no lockout on a settled entity");
    }

    #[tokio::test]
    async fn siblings_are_judged_together_so_a_low_claim_cant_lean_on_its_own_acceptance() {
        // A version's siblings are judged at the strictest rank any of them claims. Judged
        // apart, the sibling claiming 50 leaned on a role that exists only because the
        // sibling claiming 4 was accepted, and the fixpoint cycled.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Siblings", vec!["wss://r".into()], None).await.unwrap();
        let (x, a, b, c) = (Keys::generate(), Keys::generate(), Keys::generate(), Keys::generate());
        let (xr, cos, admp, e, f) = ("d0".repeat(32), "d2".repeat(32), "d3".repeat(32), "de".repeat(32), "df".repeat(32));
        let mr = Permissions::MANAGE_ROLES;
        publish_role(&relay, &community, &owner, &role_at(&xr, "XR", 1, mr), 1).await;
        publish_grant(&relay, &community, &owner, &x.public_key(), vec![xr.clone()], 1).await;
        publish_role(&relay, &community, &x, &role_at(&cos, "COS", 2, 0), 1).await;
        publish_role(&relay, &community, &x, &role_at(&admp, "ADM'", 3, mr), 1).await;
        // E has two v1 siblings: A's at 4 and B's at 50, both carrying MR.
        let e_eid = crate::simd::hex::hex_to_bytes_32_checked(&e).unwrap();
        let role_json = |pos| crate::community::v2::roles::role_content_json(&role_at(&e, "E", pos, mr)).unwrap();
        publish_grant(&relay, &community, &x, &a.public_key(), vec![admp.clone()], 1).await;
        publish_role(&relay, &community, &c, &role_at(&f, "F", 20, mr), 1).await;
        publish_grant(&relay, &community, &x, &b.public_key(), vec![cos.clone(), f.clone()], 1).await;
        publish_grant(&relay, &community, &x, &c.public_key(), vec![e.clone()], 1).await;
        publish_fork(&[&relay], &community, &a, vsk::ROLE, &e_eid, 1, None, &role_json(4), None).await;
        publish_fork(&[&relay], &community, &b, vsk::ROLE, &e_eid, 1, None, &role_json(50), None).await;

        let editions = fetch_control(&relay, &community).await;
        let floors = load_floors(&community);
        let first = fold_authority(&community, &editions, &floors);
        assert!(first.converged, "the fold settles");
        assert_eq!(first.roles.role(&e).map(|r| r.position), Some(4), "A's sibling, the one authority above 4 supports");
        let reversed: Vec<ParsedEdition> = editions.iter().rev().cloned().collect();
        let again = fold_authority(&community, &reversed, &floors);
        assert_eq!(authority_fingerprint(&again), authority_fingerprint(&first), "in any order");
    }

    /// `mirror_control`, leaving out the editions `skip` names: a relay withholding them.
    async fn mirror_control_except(from: &MemoryRelay, to: &MemoryRelay, community: &CommunityV2, skip: &dyn Fn(&ParsedEdition) -> bool) {
        let group = control::ControlPlane::of(community).write_group().unwrap();
        let query = Query { kinds: vec![stream::KIND_WRAP], authors: vec![group.pk_hex()], limit: Some(500), ..Default::default() };
        for w in from.fetch(&query, &community.relays).await.unwrap() {
            if control::open_control_edition(&w, &group).is_ok_and(|(ed, _)| !skip(&ed)) {
                to.publish(&w, &community.relays).await.unwrap();
            }
        }
    }

    fn eid_of(id: &str) -> [u8; 32] {
        crate::simd::hex::hex_to_bytes_32_checked(id).unwrap()
    }

    #[tokio::test]
    async fn a_demotion_to_a_role_the_member_minted_settles() {
        // A grant is judged on the roles it names, never on whether they resolve, or demoting
        // A to a role only A's old rank supported makes each answer imply the other.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Demote", vec!["wss://r".into()], None).await.unwrap();
        let a = Keys::generate();
        let (r1, rmod) = ("f1".repeat(32), "f2".repeat(32));
        publish_role(&relay, &community, &owner, &role_at(&r1, "R1", 1, Permissions::MANAGE_ROLES), 1).await;
        publish_grant(&relay, &community, &owner, &a.public_key(), vec![r1.clone()], 1).await;
        publish_role(&relay, &community, &a, &role_at(&rmod, "Mod", 5, Permissions::MANAGE_ROLES), 1).await;
        let before = fold_authority(&community, &fetch_control(&relay, &community).await, &load_floors(&community));
        assert!(before.converged && before.roles.role(&rmod).is_some(), "Mod folds while A holds R1");
        follow_control(&relay, &community).await.unwrap();
        publish_grant(&relay, &community, &owner, &a.public_key(), vec![rmod.clone()], 2).await;

        let editions = fetch_control(&relay, &community).await;
        let geid = crate::simd::hex::bytes_to_hex_32(&crate::community::v2::derive::grant_locator(community.id(), &a.public_key().to_bytes()));
        let reversed: Vec<ParsedEdition> = editions.iter().rev().cloned().collect();
        for (eds, floors) in [(&editions, Floors::default()), (&editions, load_floors(&community)), (&reversed, load_floors(&community))] {
            let after = fold_authority(&community, eds, &floors);
            assert!(after.converged, "the fold settles");
            assert!(after.roles.role(&rmod).is_none(), "nothing above Mod supports it now");
            assert_eq!(after.roles.roles_of(&a.public_key().to_hex()).count(), 0, "so A holds what v2 confers: nothing");
            assert!(after.heads.iter().any(|h| h.entity_hex == geid && h.version == 2 && !h.rebased), "v2 is the head");
        }
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        follow_control(&relay, &held).await.unwrap();
        let cached = crate::db::community::get_community_roles(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap();
        assert!(cached.role(&rmod).is_none() && cached.roles_of(&a.public_key().to_hex()).count() == 0, "and the cache moves on");
    }

    #[tokio::test]
    async fn a_withheld_held_head_stops_what_would_be_judged_without_it() {
        // A device judges the next edition against what its held one left. Withholding the
        // held edition must not let a manager's edits be judged as if nothing stood there;
        // the owner, who acts whatever the rank, still moves the entity.
        let (_tmp, _guard, owner) = init_test_db();
        let full = MemoryRelay::new();
        let community = create_community(&full, "Withheld", vec!["wss://r".into()], None).await.unwrap();
        let mgr = Keys::generate();
        let senior = Keys::generate().public_key();
        let (rsen, radm, rmgr, rlow) = ("a1".repeat(32), "a3".repeat(32), "a5".repeat(32), "a9".repeat(32));
        publish_role(&full, &community, &owner, &role_at(&rsen, "Senior", 2, 0), 1).await;
        publish_role(&full, &community, &owner, &role_at(&radm, "Adm", 3, Permissions::MANAGE_ROLES), 1).await;
        publish_role(&full, &community, &owner, &role_at(&rmgr, "Mgr", 5, Permissions::MANAGE_ROLES), 1).await;
        publish_role(&full, &community, &owner, &role_at(&rlow, "Low", 9, 0), 1).await;
        publish_grant(&full, &community, &owner, &mgr.public_key(), vec![rmgr.clone()], 1).await;
        publish_grant(&full, &community, &owner, &senior, vec![rsen.clone()], 1).await;
        follow_control(&full, &community).await.unwrap();
        let geid = crate::community::v2::derive::grant_locator(community.id(), &senior.to_bytes());
        let geid_hex = crate::simd::hex::bytes_to_hex_32(&geid);
        let (g1, adm1) = (head_hash_on_relay(&full, &community, &geid).await.unwrap(), head_hash_on_relay(&full, &community, &eid_of(&radm)).await.unwrap());
        // The manager demotes the senior member and moves Adm beneath themselves.
        publish_grant(&full, &community, &mgr, &senior, vec![rlow.clone()], 2).await;
        publish_role(&full, &community, &mgr, &role_at(&radm, "Adm", 8, Permissions::MANAGE_ROLES), 2).await;
        let whole = fold_authority(&community, &fetch_control(&full, &community).await, &load_floors(&community));
        assert_eq!(whole.roles.highest_position(&senior.to_hex()), Some(2), "on the whole plane both edits are refused");
        assert_eq!(whole.roles.role(&radm).map(|r| r.position), Some(3));

        let thin = MemoryRelay::new();
        mirror_control_except(&full, &thin, &community, &|e| e.self_hash == g1 || e.self_hash == adm1).await;
        let a = fold_authority(&community, &fetch_control(&thin, &community).await, &load_floors(&community));
        assert_ne!(a.roles.highest_position(&senior.to_hex()), Some(9), "the demotion is not judged against nothing");
        assert!(a.roles.role(&radm).is_none_or(|r| r.position == 3), "nor the move");
        assert!(!a.heads.iter().any(|h| h.entity_hex == geid_hex || h.entity_hex == radm), "neither entity advances");
        assert!(a.gapped, "the device pages for the held editions");
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        follow_control(&thin, &held).await.unwrap();
        let cached = crate::db::community::get_community_roles(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap();
        assert_eq!(cached.highest_position(&senior.to_hex()), Some(2), "the cached roster keeps the senior member");
        assert_eq!(cached.role(&radm).map(|r| r.position), Some(3));
        assert_eq!((floor_of(&community, &geid).0, floor_of(&community, &eid_of(&radm)).0), (1, 1), "and the floors hold");

        // Stacking a second edit on the first proves nothing: the first was judged blind.
        publish_grant(&thin, &community, &mgr, &senior, vec![rlow.clone()], 3).await;
        let m = fold_authority(&community, &fetch_control(&thin, &community).await, &load_floors(&community));
        assert!(!m.heads.iter().any(|h| h.entity_hex == geid_hex), "the manager's second edit doesn't advance it either");
        // The owner's edit above the same withheld head moves it.
        publish_grant(&thin, &community, &owner, &senior, vec![rlow.clone()], 4).await;
        let o = fold_authority(&community, &fetch_control(&thin, &community).await, &load_floors(&community));
        assert!(o.heads.iter().any(|h| h.entity_hex == geid_hex && h.version == 4), "the owner acts regardless of rank");
        assert_eq!(o.roles.highest_position(&senior.to_hex()), Some(9));
    }

    #[tokio::test]
    async fn a_refused_held_head_falls_back_only_along_a_served_chain() {
        // A refused held head falls back to what it stood on, walked down its own links. A
        // relay withholding a link picks neither the target nor a verdict that it's gone.
        let (_tmp, _guard, owner) = init_test_db();
        let full = MemoryRelay::new();
        let community = create_community(&full, "Walk", vec!["wss://r".into()], None).await.unwrap();
        let (adm, member) = (Keys::generate(), Keys::generate().public_key());
        let (radm, rhigh, rmid, rlow) = ("b1".repeat(32), "b3".repeat(32), "b4".repeat(32), "b9".repeat(32));
        publish_role(&full, &community, &owner, &role_at(&radm, "Adm", 1, Permissions::MANAGE_ROLES), 1).await;
        publish_role(&full, &community, &owner, &role_at(&rhigh, "High", 3, 0), 1).await;
        publish_role(&full, &community, &owner, &role_at(&rmid, "Mid", 4, 0), 1).await;
        publish_role(&full, &community, &owner, &role_at(&rlow, "Low", 9, 0), 1).await;
        publish_grant(&full, &community, &owner, &adm.public_key(), vec![radm.clone()], 1).await;
        let geid = crate::community::v2::derive::grant_locator(community.id(), &member.to_bytes());
        let geid_hex = crate::simd::hex::bytes_to_hex_32(&geid);
        publish_grant(&full, &community, &owner, &member, vec![rlow.clone()], 1).await;
        let m1 = head_hash_on_relay(&full, &community, &geid).await.unwrap();
        publish_grant(&full, &community, &owner, &member, vec![rhigh.clone()], 2).await;
        let m2 = head_hash_on_relay(&full, &community, &geid).await.unwrap();
        publish_grant(&full, &community, &adm, &member, vec![rhigh.clone(), rmid.clone()], 3).await;
        follow_control(&full, &community).await.unwrap();
        assert_eq!(floor_of(&community, &geid).0, 3);
        // The admin is stripped, so their v3 no longer stands.
        publish_grant(&full, &community, &owner, &adm.public_key(), vec![], 2).await;

        let editions = fetch_control(&full, &community).await;
        let floors = load_floors(&community);
        let pick = |eds: Vec<ParsedEdition>| {
            let a = fold_authority(&community, &eds, &floors);
            (a.complete, a.heads.iter().find(|h| h.entity_hex == geid_hex).map(|h| (h.version, h.rebased)), a.refused.contains(&geid_hex))
        };
        let without = |hs: &[[u8; 32]]| editions.iter().filter(|e| !hs.contains(&e.self_hash)).cloned().collect::<Vec<_>>();
        assert_eq!(pick(editions.clone()), (true, Some((2, true)), false), "the whole chain falls back to v2");
        assert_eq!(pick(without(&[m2])), (true, Some((3, false)), false), "not past a withheld v2 to v1: v3 is kept");
        assert_eq!(pick(without(&[m1, m2])), (true, Some((3, false)), false), "nor to a verdict that the grant is gone");

        let thin = MemoryRelay::new();
        mirror_control_except(&full, &thin, &community, &|e| e.self_hash == m2).await;
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        forget_held(&held);
        follow_control(&thin, &held).await.unwrap();
        assert_eq!(floor_of(&community, &geid).0, 3, "the floor holds on the thin read");
        follow_control(&full, &held).await.unwrap();
        assert_eq!(floor_of(&community, &geid).0, 2, "and moves to v2 on the whole one");
        let cached = crate::db::community::get_community_roles(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap();
        assert_eq!(cached.highest_position(&member.to_hex()), Some(3));
    }

    #[tokio::test]
    async fn an_undecided_entity_is_carried_so_nothing_resting_on_it_moves() {
        // C's authority runs through role Y. With Y undecided the device keeps Y as it holds
        // it, so C's edit to X is judged as before rather than refused for Y's absence.
        let (_tmp, _guard, owner) = init_test_db();
        let full = MemoryRelay::new();
        let community = create_community(&full, "Cascade", vec!["wss://r".into()], None).await.unwrap();
        let (b, c) = (Keys::generate(), Keys::generate());
        let (rb, ry, rx) = ("c1".repeat(32), "c2".repeat(32), "c6".repeat(32));
        let mr = Permissions::MANAGE_ROLES;
        publish_role(&full, &community, &owner, &role_at(&rb, "B", 1, mr), 1).await;
        publish_role(&full, &community, &owner, &role_at(&ry, "Y", 2, mr), 1).await;
        let y1 = head_hash_on_relay(&full, &community, &eid_of(&ry)).await.unwrap();
        publish_role(&full, &community, &owner, &role_at(&rx, "X", 6, 0), 1).await;
        publish_grant(&full, &community, &owner, &b.public_key(), vec![rb.clone()], 1).await;
        publish_grant(&full, &community, &owner, &c.public_key(), vec![ry.clone()], 1).await;
        publish_role(&full, &community, &b, &role_at(&ry, "Y2", 2, mr), 2).await;
        publish_role(&full, &community, &c, &role_at(&rx, "X2", 6, 0), 2).await;
        follow_control(&full, &community).await.unwrap();
        publish_grant(&full, &community, &owner, &b.public_key(), vec![], 2).await;

        let editions = fetch_control(&full, &community).await;
        let floors = load_floors(&community);
        let x_head = |a: &AuthoritySet| a.heads.iter().find(|h| h.entity_hex == rx).map(|h| (h.version, h.rebased));
        let whole = fold_authority(&community, &editions, &floors);
        assert!(whole.heads.iter().any(|h| h.entity_hex == ry && h.version == 1 && h.rebased), "Y falls back to the owner's v1");
        assert_eq!(x_head(&whole), Some((2, false)), "so C keeps authority and X2 stands");
        let thin: Vec<ParsedEdition> = editions.iter().filter(|e| e.self_hash != y1).cloned().collect();
        let a = fold_authority(&community, &thin, &floors);
        assert!(a.complete && a.carried.contains(&ry), "Y's fallback is withheld on the thin read");
        assert!(a.heads.iter().any(|h| h.entity_hex == ry && h.version == 2 && !h.rebased) && a.roles.role(&ry).is_some_and(|r| r.name == "Y2"), "so it stays on its held head");
        assert_eq!(x_head(&a), Some((2, false)), "and X stands");
        // The rest of the roster still moves: B's strip reaches the cache.
        let relay_thin = MemoryRelay::new();
        mirror_control_except(&full, &relay_thin, &community, &|e| e.self_hash == y1).await;
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        forget_held(&held);
        follow_control(&relay_thin, &held).await.unwrap();
        let cached = crate::db::community::get_community_roles(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap();
        assert_eq!(cached.roles_of(&b.public_key().to_hex()).count(), 0, "B's strip is cached");
        assert!(cached.role(&ry).is_some_and(|r| r.name == "Y2"), "beside Y as this device holds it");
    }

    #[tokio::test]
    async fn a_refused_head_with_nothing_to_fall_back_to_is_kept_and_a_ban_still_drops_it() {
        // M's grant is all A's work, and A is demoted: the held head is refused and so is its
        // predecessor, which may be a copy, so the device keeps the grant as it holds it.
        // A ban is a verdict about M, and drops it.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Kept", vec!["wss://r".into()], None).await.unwrap();
        let a = Keys::generate();
        let m = Keys::generate().public_key();
        let (radm, rmod, rhelp) = ("a1".repeat(32), "a5".repeat(32), "a6".repeat(32));
        publish_role(&relay, &community, &owner, &role_at(&radm, "Adm", 1, Permissions::MANAGE_ROLES), 1).await;
        publish_role(&relay, &community, &owner, &role_at(&rmod, "Mod", 5, 0), 1).await;
        publish_role(&relay, &community, &owner, &role_at(&rhelp, "Helper", 6, 0), 1).await;
        publish_grant(&relay, &community, &owner, &a.public_key(), vec![radm.clone()], 1).await;
        publish_grant(&relay, &community, &a, &m, vec![rmod.clone()], 1).await;
        publish_grant(&relay, &community, &a, &m, vec![rmod.clone(), rhelp.clone()], 2).await;
        follow_control(&relay, &community).await.unwrap();
        publish_grant(&relay, &community, &owner, &a.public_key(), vec![], 2).await;

        let gm = crate::simd::hex::bytes_to_hex_32(&crate::community::v2::derive::grant_locator(community.id(), &m.to_bytes()));
        // A re-signed copy of the held edition, sorting first, is not the edition kept.
        let gm_eid = crate::community::v2::derive::grant_locator(community.id(), &m.to_bytes());
        let (held_content, held_prev, held_id) = content_at(&fetch_control(&relay, &community).await, &gm_eid, 2, &a.public_key());
        publish_fork(&[&relay], &community, &Keys::generate(), vsk::GRANT, &gm_eid, 2, held_prev, &held_content, Some((std::cmp::Ordering::Less, held_id))).await;
        let f = fold_authority(&community, &fetch_control(&relay, &community).await, &load_floors(&community));
        assert!(f.complete && f.carried.contains(&gm), "refused, nothing to fall back to: kept");
        assert_eq!(f.heads.iter().find(|h| h.entity_hex == gm).map(|h| h.inner_id), Some(held_id), "the genuine edition, not the copy");
        assert_eq!(f.roles.roles_of(&m.to_hex()).count(), 2);
        assert!(f.heads.iter().any(|h| h.entity_hex == gm && h.version == 2 && !h.rebased), "on the held head");
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        follow_control(&relay, &held).await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let cached = crate::db::community::get_community_roles(&cid_hex).unwrap();
        assert!(!cached.is_admin(&a.public_key().to_hex()) && cached.roles_of(&m.to_hex()).count() == 2, "and the cache moves on with it");

        publish_banlist(&relay, &community, &owner, &[m.to_hex()], 1).await;
        let b = fold_authority(&community, &fetch_control(&relay, &community).await, &load_floors(&community));
        assert!(b.refused.contains(&gm) && b.roles.roles_of(&m.to_hex()).count() == 0, "a banned member's kept grant goes");
    }

    #[tokio::test]
    async fn a_fallback_target_must_stand_on_evidence_too() {
        // The floor steps down only to an admitted predecessor that was itself judged with its
        // own predecessor in hand: A2's v2 passes only when nobody can see the member stood
        // above A2. A refused link is never stepped past, since it may be a re-signed copy.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Target", vec!["wss://r".into()], None).await.unwrap();
        let (b, a2, member) = (Keys::generate(), Keys::generate(), Keys::generate().public_key());
        let (rb, rsen, ra2, rlow) = ("e1".repeat(32), "e2".repeat(32), "e3".repeat(32), "e9".repeat(32));
        let mr = Permissions::MANAGE_ROLES;
        publish_role(&relay, &community, &owner, &role_at(&rb, "B", 1, mr), 1).await;
        publish_role(&relay, &community, &owner, &role_at(&rsen, "Senior", 2, 0), 1).await;
        publish_role(&relay, &community, &owner, &role_at(&ra2, "A2", 3, mr), 1).await;
        publish_role(&relay, &community, &owner, &role_at(&rlow, "Low", 9, 0), 1).await;
        publish_grant(&relay, &community, &owner, &b.public_key(), vec![rb.clone()], 1).await;
        publish_grant(&relay, &community, &owner, &a2.public_key(), vec![ra2.clone()], 1).await;
        let geid = crate::community::v2::derive::grant_locator(community.id(), &member.to_bytes());
        let geid_hex = crate::simd::hex::bytes_to_hex_32(&geid);
        publish_grant(&relay, &community, &owner, &member, vec![rsen.clone()], 1).await;
        let m1 = head_hash_on_relay(&relay, &community, &geid).await.unwrap();
        publish_grant(&relay, &community, &a2, &member, vec![rlow.clone()], 2).await;
        publish_grant(&relay, &community, &b, &member, vec![rsen.clone()], 3).await;
        follow_control(&relay, &community).await.unwrap();
        assert_eq!(floor_of(&community, &geid).0, 3);
        publish_grant(&relay, &community, &owner, &b.public_key(), vec![], 2).await;

        let editions = fetch_control(&relay, &community).await;
        let floors = load_floors(&community);
        let head = |eds: &[ParsedEdition]| fold_authority(&community, eds, &floors).heads.into_iter().find(|h| h.entity_hex == geid_hex).map(|h| (h.version, h.rebased));
        assert_eq!(head(&editions), Some((3, false)), "A2's v2 is refused, and the floor never steps past a refused link: v3 is kept");
        let thin: Vec<ParsedEdition> = editions.iter().filter(|e| e.self_hash != m1).cloned().collect();
        assert_eq!(head(&thin), Some((3, false)), "without v1, A2's v2 is no target either");
    }

    /// The content of the edition `signer` published for `entity` at `version`.
    fn content_at(editions: &[ParsedEdition], entity: &[u8; 32], version: u64, signer: &PublicKey) -> (String, Option<[u8; 32]>, [u8; 32]) {
        let e = editions.iter().find(|e| e.entity_id == *entity && e.version == version && e.author == *signer).expect("the edition");
        (e.content.clone(), e.prev_hash, e.inner_id)
    }

    #[tokio::test]
    async fn a_re_signed_copy_never_stands_in_for_a_withheld_grant() {
        // A chain link names content, not a signer, so anyone writing the plane can serve a
        // copy of an edition under their own key. It must count for nothing in place of the
        // genuine one: neither a refused held head to fall back from, nor a predecessor's rank.
        let (_tmp, _guard, owner) = init_test_db();
        let full = MemoryRelay::new();
        let community = create_community(&full, "Copies", vec!["wss://r".into()], None).await.unwrap();
        let (a, mgr, senior) = (Keys::generate(), Keys::generate(), Keys::generate().public_key());
        let (radm, rsen, rmgr, rlow) = ("a1".repeat(32), "a2".repeat(32), "a5".repeat(32), "a9".repeat(32));
        publish_role(&full, &community, &owner, &role_at(&radm, "Adm", 1, Permissions::MANAGE_ROLES), 1).await;
        publish_role(&full, &community, &owner, &role_at(&rsen, "Senior", 2, 0), 1).await;
        publish_role(&full, &community, &owner, &role_at(&rmgr, "Mgr", 5, Permissions::MANAGE_ROLES), 1).await;
        publish_role(&full, &community, &owner, &role_at(&rlow, "Low", 9, 0), 1).await;
        publish_grant(&full, &community, &owner, &mgr.public_key(), vec![rmgr.clone()], 1).await;
        let (ga, gs) = (
            crate::community::v2::derive::grant_locator(community.id(), &a.public_key().to_bytes()),
            crate::community::v2::derive::grant_locator(community.id(), &senior.to_bytes()),
        );
        publish_grant(&full, &community, &owner, &a.public_key(), vec![radm.clone()], 1).await;
        publish_grant(&full, &community, &owner, &a.public_key(), vec![], 2).await;
        publish_grant(&full, &community, &owner, &senior, vec![rlow.clone()], 1).await;
        publish_grant(&full, &community, &owner, &senior, vec![rsen.clone()], 2).await;
        follow_control(&full, &community).await.unwrap();
        assert_eq!((floor_of(&community, &ga).0, floor_of(&community, &gs).0), (2, 2));

        // A re-signs the owner's strip of A; the manager re-signs the senior grant and builds
        // a demotion on it. Relays withhold both genuine editions.
        let editions = fetch_control(&full, &community).await;
        let (strip, strip_prev, strip_id) = content_at(&editions, &ga, 2, &owner.public_key());
        let (sen, sen_prev, sen_id) = content_at(&editions, &gs, 2, &owner.public_key());
        let thin = MemoryRelay::new();
        mirror_control_except(&full, &thin, &community, &|e| e.inner_id == strip_id || e.inner_id == sen_id).await;
        publish_fork(&[&thin], &community, &a, vsk::GRANT, &ga, 2, strip_prev, &strip, None).await;
        let copy = publish_fork(&[&thin], &community, &mgr, vsk::GRANT, &gs, 2, sen_prev, &sen, None).await;
        let copied = fetch_control(&thin, &community).await;
        let copy_hash = copied.iter().find(|e| e.inner_id == copy).unwrap().self_hash;
        assert_eq!(copy_hash, editions.iter().find(|e| e.inner_id == sen_id).unwrap().self_hash, "the copy is the same link");
        let demote = crate::community::v2::roles::grant_content_json(&MemberGrant { member: senior.to_hex(), role_ids: vec![rlow.clone()] }).unwrap();
        publish_fork(&[&thin], &community, &mgr, vsk::GRANT, &gs, 3, Some(copy_hash), &demote, None).await;

        let t = fold_authority(&community, &fetch_control(&thin, &community).await, &load_floors(&community));
        assert!(!t.roles.is_admin(&a.public_key().to_hex()), "the strip stands");
        assert_ne!(t.roles.highest_position(&senior.to_hex()), Some(9), "and the copy carries no demotion");
        assert!(!t.complete, "a copy is not the edition the device holds");
        let ga_hex = crate::simd::hex::bytes_to_hex_32(&ga);
        let gs_hex = crate::simd::hex::bytes_to_hex_32(&gs);
        assert!(!t.heads.iter().any(|h| h.entity_hex == ga_hex || h.entity_hex == gs_hex), "neither entity moves");
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        follow_control(&thin, &held).await.unwrap();
        assert_eq!((floor_of(&community, &ga).0, floor_of(&community, &gs).0), (2, 2), "the floors hold");
        let cached = crate::db::community::get_community_roles(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap();
        assert_eq!(cached.highest_position(&senior.to_hex()), Some(2), "and the cache keeps the senior member");
        assert!(!cached.is_admin(&a.public_key().to_hex()));
    }

    #[tokio::test]
    async fn a_re_signed_copy_never_stands_in_for_a_withheld_channel_edit() {
        let (_tmp, _guard, owner) = init_test_db();
        let full = MemoryRelay::new();
        let community = create_community(&full, "ChanCopy", vec!["wss://r".into()], None).await.unwrap();
        let ch = community.channels[0].id;
        let v1 = head_hash_on_relay(&full, &community, &ch.0).await;
        let real = publish_fork(&[&full], &community, &owner, vsk::CHANNEL_METADATA, &ch.0, 2, v1, &channel_meta_json("real"), None).await;
        follow_control(&full, &community).await.unwrap();
        let thin = MemoryRelay::new();
        mirror_control_except(&full, &thin, &community, &|e| e.inner_id == real).await;
        let stranger = Keys::generate();
        publish_fork(&[&thin], &community, &stranger, vsk::CHANNEL_METADATA, &ch.0, 2, v1, &channel_meta_json("real"), None).await;
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        follow_control(&thin, &held).await.unwrap();
        let after = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        assert_eq!(after.channel(&ch).unwrap().name, "real", "no rollback to the name before");
        assert_eq!(floor_of(&community, &ch.0).0, 2);
    }

    #[tokio::test]
    async fn a_sibling_that_fails_on_its_own_cannot_veto_the_version() {
        // Siblings are judged at the strictest rank among them, but only among siblings that
        // could stand: a stranger's sibling claiming the top rank must not refuse the rest.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Veto", vec!["wss://r".into()], None).await.unwrap();
        let (a, z, member) = (Keys::generate(), Keys::generate(), Keys::generate().public_key());
        let (rtop, radm, rmid, rlow) = ("b1".repeat(32), "b3".repeat(32), "b6".repeat(32), "b9".repeat(32));
        publish_role(&relay, &community, &owner, &role_at(&rtop, "Top", 1, 0), 1).await;
        publish_role(&relay, &community, &owner, &role_at(&radm, "Adm", 3, Permissions::MANAGE_ROLES), 1).await;
        publish_role(&relay, &community, &owner, &role_at(&rmid, "Mid", 6, 0), 1).await;
        publish_role(&relay, &community, &owner, &role_at(&rlow, "Low", 9, 0), 1).await;
        publish_grant(&relay, &community, &owner, &a.public_key(), vec![radm.clone()], 1).await;
        let geid = crate::community::v2::derive::grant_locator(community.id(), &member.to_bytes());
        publish_grant(&relay, &community, &owner, &member, vec![rlow.clone()], 1).await;
        let v1 = head_hash_on_relay(&relay, &community, &geid).await;
        publish_grant(&relay, &community, &a, &member, vec![rmid.clone()], 2).await;
        follow_control(&relay, &community).await.unwrap();
        let claim_top = crate::community::v2::roles::grant_content_json(&MemberGrant { member: member.to_hex(), role_ids: vec![rtop.clone()] }).unwrap();
        publish_fork(&[&relay], &community, &z, vsk::GRANT, &geid, 2, v1, &claim_top, None).await;

        let editions = fetch_control(&relay, &community).await;
        let gid = crate::simd::hex::bytes_to_hex_32(&geid);
        for floors in [Floors::default(), load_floors(&community)] {
            let f = fold_authority(&community, &editions, &floors);
            assert!(f.converged);
            assert_eq!(f.roles.highest_position(&member.to_hex()), Some(6), "A's edit stands");
            let head = f.heads.iter().find(|h| h.entity_hex == gid).unwrap();
            assert_eq!((head.version, head.author, head.rebased), (2, a.public_key().to_bytes(), false));
        }
    }

    #[tokio::test]
    async fn a_citation_settles_with_the_heads_it_reads() {
        // A citation is checked against the heads of the round before, so a round where only
        // a head moved isn't settled: A's role cites a re-issued grant whose content matches
        // the original, and the fold must run one more round to admit it.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Heads", vec!["wss://r".into()], None).await.unwrap();
        let (a, b, c) = (Keys::generate(), Keys::generate(), Keys::generate());
        let (rc, rb, radm, rr) = ("c1".repeat(32), "c2".repeat(32), "c3".repeat(32), "c5".repeat(32));
        let mr = Permissions::MANAGE_ROLES;
        publish_role(&relay, &community, &owner, &role_at(&rc, "C", 1, mr), 1).await;
        publish_grant(&relay, &community, &owner, &c.public_key(), vec![rc.clone()], 1).await;
        publish_role(&relay, &community, &c, &role_at(&rb, "B", 2, mr), 1).await;
        publish_grant(&relay, &community, &owner, &b.public_key(), vec![rb.clone()], 1).await;
        publish_role(&relay, &community, &owner, &role_at(&radm, "Adm", 3, mr), 1).await;
        publish_grant(&relay, &community, &owner, &a.public_key(), vec![radm.clone()], 1).await;
        publish_grant(&relay, &community, &b, &a.public_key(), vec![radm.clone()], 2).await;
        publish_role(&relay, &community, &a, &role_at(&rr, "R", 5, 0), 1).await;

        let editions = fetch_control(&relay, &community).await;
        let reversed: Vec<ParsedEdition> = editions.iter().rev().cloned().collect();
        for eds in [&editions, &reversed] {
            let f = fold_authority(&community, eds, &Floors::default());
            assert!(f.converged);
            assert!(f.roles.role(&rr).is_some(), "the role citing the re-issued grant folds");
        }
    }

    #[tokio::test]
    async fn an_admin_edit_advances_a_head_whose_history_is_gone() {
        // After a compaction the held head's predecessor is gone: the held edition is the
        // device's baseline, so an admin's next edit is judged against it and advances.
        let (_tmp, _guard, owner) = init_test_db();
        let full = MemoryRelay::new();
        let community = create_community(&full, "Baseline", vec!["wss://r".into()], None).await.unwrap();
        let a = Keys::generate();
        let (radm, rx) = ("d1".repeat(32), "d6".repeat(32));
        publish_role(&full, &community, &owner, &role_at(&radm, "Adm", 1, Permissions::MANAGE_ROLES), 1).await;
        publish_grant(&full, &community, &owner, &a.public_key(), vec![radm.clone()], 1).await;
        publish_role(&full, &community, &owner, &role_at(&rx, "X", 6, 0), 1).await;
        let x1 = head_hash_on_relay(&full, &community, &eid_of(&rx)).await.unwrap();
        publish_role(&full, &community, &a, &role_at(&rx, "X2", 6, 0), 2).await;
        follow_control(&full, &community).await.unwrap();
        let thin = MemoryRelay::new();
        mirror_control_except(&full, &thin, &community, &|e| e.self_hash == x1).await;
        publish_role(&thin, &community, &a, &role_at(&rx, "X3", 6, 0), 3).await;
        let f = fold_authority(&community, &fetch_control(&thin, &community).await, &load_floors(&community));
        assert_eq!(f.roles.role(&rx).map(|r| r.name.as_str()), Some("X3"));
        assert!(f.heads.iter().any(|h| h.entity_hex == rx && h.version == 3 && !h.rebased));
    }

    #[tokio::test]
    async fn an_uncited_strip_naming_a_made_up_role_is_still_a_strip() {
        // An uncited grant may add a Role, never take one away, and naming a Role nobody
        // published doesn't turn a strip into an addition.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Uncited", vec!["wss://r".into()], None).await.unwrap();
        let mgr = Keys::generate();
        let (m1, m2) = (Keys::generate().public_key(), Keys::generate().public_key());
        let (rmgr, rlow, rlower) = ("e5".repeat(32), "e9".repeat(32), "ea".repeat(32));
        publish_role(&relay, &community, &owner, &role_at(&rmgr, "Mgr", 5, Permissions::MANAGE_ROLES), 1).await;
        publish_role(&relay, &community, &owner, &role_at(&rlow, "Low", 9, 0), 1).await;
        publish_role(&relay, &community, &owner, &role_at(&rlower, "Lower", 10, 0), 1).await;
        publish_grant(&relay, &community, &owner, &mgr.public_key(), vec![rmgr.clone()], 1).await;
        publish_grant(&relay, &community, &owner, &m1, vec![rlow.clone()], 1).await;
        publish_grant(&relay, &community, &owner, &m2, vec![rlow.clone()], 1).await;
        publish_grant_citing(&relay, &community, &mgr, &m1, vec!["ff".repeat(32)], 2, None).await;
        publish_grant_citing(&relay, &community, &mgr, &m2, vec![rlow.clone(), rlower.clone()], 2, None).await;
        let f = fold_authority(&community, &fetch_control(&relay, &community).await, &load_floors(&community));
        assert_eq!(f.roles.highest_position(&m1.to_hex()), Some(9), "the made-up role strips nothing");
        assert_eq!(f.roles.roles_of(&m2.to_hex()).count(), 2, "an uncited addition stands");
    }

    #[tokio::test]
    async fn an_edition_off_the_floors_chain_waits_for_its_link() {
        // Above the floor only what the held edition's chain reaches folds: an edit naming a
        // predecessor nobody serves is a gap, even from the owner, and the device pages for it.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Reach", vec!["wss://r".into()], None).await.unwrap();
        let member = Keys::generate().public_key();
        let (rmid, rlow) = ("f6".repeat(32), "f9".repeat(32));
        publish_role(&relay, &community, &owner, &role_at(&rmid, "Mid", 6, 0), 1).await;
        publish_role(&relay, &community, &owner, &role_at(&rlow, "Low", 9, 0), 1).await;
        publish_grant(&relay, &community, &owner, &member, vec![rlow.clone()], 1).await;
        publish_grant(&relay, &community, &owner, &member, vec![rmid.clone()], 2).await;
        follow_control(&relay, &community).await.unwrap();
        let geid = crate::community::v2::derive::grant_locator(community.id(), &member.to_bytes());
        let off = crate::community::v2::roles::grant_content_json(&MemberGrant { member: member.to_hex(), role_ids: vec![rlow.clone()] }).unwrap();
        publish_fork(&[&relay], &community, &owner, vsk::GRANT, &geid, 3, Some([7u8; 32]), &off, None).await;
        let f = fold_authority(&community, &fetch_control(&relay, &community).await, &load_floors(&community));
        let gid = crate::simd::hex::bytes_to_hex_32(&geid);
        assert!(f.heads.iter().any(|h| h.entity_hex == gid && h.version == 2), "the held head stands");
        assert_eq!(f.roles.highest_position(&member.to_hex()), Some(6));
        assert!(f.gapped, "and the device pages for the missing link");
        // A link names the version directly beneath it: skipping versions reaches nothing.
        let skip = crate::community::v2::roles::grant_content_json(&MemberGrant { member: member.to_hex(), role_ids: vec![] }).unwrap();
        let held = floor_of(&community, &geid);
        assert_eq!(held.0, 2);
        let eds = fetch_control(&relay, &community).await;
        let h2 = eds.iter().find(|e| e.entity_id == geid && e.version == 2).unwrap().self_hash;
        publish_fork(&[&relay], &community, &owner, vsk::GRANT, &geid, 5, Some(h2), &skip, None).await;
        let g = fold_authority(&community, &fetch_control(&relay, &community).await, &load_floors(&community));
        assert!(g.heads.iter().any(|h| h.entity_hex == gid && h.version == 2), "a skipped version links nothing");
    }

    #[tokio::test]
    async fn a_refounding_carries_the_genuine_head_never_a_newer_copy() {
        // A copy re-signed under another key shares the head's hash and is served first.
        // Compaction must carry the edition the floor records, or fresh joiners judge
        // every head on the copier's authority.
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "CopyCompact", bed.relays.clone(), None).await.unwrap();
        let rid = crate::simd::hex::bytes_to_hex_32(&[0xa2; 32]);
        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::ADMIN_ALL), 1).await;
        publish_grant(&bed.relay, &community, &owner.keys, &member.keys.public_key(), vec![rid.clone()], 1).await;
        follow_control(&bed.relay, &community).await.unwrap();
        let copier = Keys::generate();
        for e in fetch_control(&bed.relay, &community).await {
            if e.vsk == vsk::ROLE || e.vsk == vsk::GRANT {
                publish_fork(&[&bed.relay], &community, &copier, &e.vsk, &e.entity_id, e.version, e.prev_hash, &e.content, None).await;
            }
        }
        let refounded = refound_community(&bed.relay, &community, &[]).await.unwrap();
        let fresh = fetch_control(&bed.relay, &refounded).await;
        assert!(fresh.iter().filter(|e| e.vsk == vsk::ROLE || e.vsk == vsk::GRANT).all(|e| e.author == owner.keys.public_key()), "only the owner's editions are carried");
        let joiner = fold_authority(&refounded, &fresh, &Floors::default());
        assert!(joiner.roles.is_admin(&member.keys.public_key().to_hex()), "a fresh joiner folds the roster");
    }

    #[tokio::test]
    async fn a_demoted_link_in_a_roles_chain_strands_no_device() {
        // A edits R, B edits on top, then A is demoted. Whatever version a device holds, and
        // a reader holding nothing, all land on B's edit.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Strand", vec!["wss://r".into()], None).await.unwrap();
        let (a, b) = (Keys::generate(), Keys::generate());
        let (ra, rb, rr) = ("b1".repeat(32), "b2".repeat(32), "b5".repeat(32));
        let mr = Permissions::MANAGE_ROLES;
        publish_role(&relay, &community, &owner, &role_at(&ra, "A", 1, mr), 1).await;
        publish_role(&relay, &community, &owner, &role_at(&rb, "B", 2, mr), 1).await;
        publish_grant(&relay, &community, &owner, &a.public_key(), vec![ra.clone()], 1).await;
        publish_grant(&relay, &community, &owner, &b.public_key(), vec![rb.clone()], 1).await;
        publish_role(&relay, &community, &owner, &role_at(&rr, "R", 5, 0), 1).await;
        publish_role(&relay, &community, &a, &role_at(&rr, "R2", 5, 0), 2).await;
        publish_role(&relay, &community, &b, &role_at(&rr, "R3", 5, 0), 3).await;
        follow_control(&relay, &community).await.unwrap();
        publish_grant(&relay, &community, &owner, &a.public_key(), vec![], 2).await;

        let editions = fetch_control(&relay, &community).await;
        let base = load_floors(&community);
        let at = |v: u64| {
            let e = editions.iter().find(|e| crate::simd::hex::bytes_to_hex_32(&e.entity_id) == rr && e.version == v).unwrap();
            let mut f = base.clone();
            f.insert(rr.clone(), (v, e.self_hash, Some(e.inner_id), Some(e.author.to_bytes()), None));
            f
        };
        for floors in [Floors::default(), at(1), at(2), at(3)] {
            let f = fold_authority(&community, &editions, &floors);
            assert_eq!(f.roles.role(&rr).map(|r| r.name.as_str()), Some("R3"), "every device lands on B's edit");
        }
    }

    #[tokio::test]
    async fn a_demoted_link_strands_no_channel_or_banlist() {
        // The same for entities judged on their author alone: a refused edition still links
        // what was built on it, so the floor reaches B's edit and nothing is left to page for.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "StrandChan", vec!["wss://r".into()], None).await.unwrap();
        let (a, b) = (Keys::generate(), Keys::generate());
        let (ra, rb) = ("c1".repeat(32), "c2".repeat(32));
        let staff = Permissions::MANAGE_CHANNELS | Permissions::BAN;
        publish_role(&relay, &community, &owner, &role_at(&ra, "A", 1, staff), 1).await;
        publish_role(&relay, &community, &owner, &role_at(&rb, "B", 2, staff), 1).await;
        publish_grant(&relay, &community, &owner, &a.public_key(), vec![ra.clone()], 1).await;
        publish_grant(&relay, &community, &owner, &b.public_key(), vec![rb.clone()], 1).await;
        let (x, y, z) = (Keys::generate().public_key().to_hex(), Keys::generate().public_key().to_hex(), Keys::generate().public_key().to_hex());
        publish_banlist(&relay, &community, &owner, &[x.clone()], 1).await;
        follow_control(&relay, &community).await.unwrap();
        let ch = community.channels[0].id;
        // The refused link sits above the version that links straight to the floor.
        let v1 = head_hash_on_relay(&relay, &community, &ch.0).await;
        let hash_of = |id: [u8; 32], eds: Vec<ParsedEdition>| eds.into_iter().find(|e| e.inner_id == id).unwrap().self_hash;
        let i2 = publish_fork(&[&relay], &community, &owner, vsk::CHANNEL_METADATA, &ch.0, 2, v1, &channel_meta_json("by-owner"), None).await;
        let h2 = hash_of(i2, fetch_control(&relay, &community).await);
        let i3 = publish_fork(&[&relay], &community, &a, vsk::CHANNEL_METADATA, &ch.0, 3, Some(h2), &channel_meta_json("by-a"), None).await;
        let h3 = hash_of(i3, fetch_control(&relay, &community).await);
        publish_fork(&[&relay], &community, &b, vsk::CHANNEL_METADATA, &ch.0, 4, Some(h3), &channel_meta_json("by-b"), None).await;
        publish_banlist(&relay, &community, &a, &[x.clone(), y.clone()], 2).await;
        publish_banlist(&relay, &community, &b, &[x.clone(), y.clone(), z.clone()], 3).await;
        publish_grant(&relay, &community, &owner, &a.public_key(), vec![], 2).await;
        // An unlinked edition above everything, from someone without the bit, is no gap.
        publish_fork(&[&relay], &community, &Keys::generate(), vsk::CHANNEL_METADATA, &ch.0, 9, Some([9u8; 32]), &channel_meta_json("junk"), None).await;

        let editions = fetch_control(&relay, &community).await;
        let floors = load_floors(&community);
        assert_eq!(floors[&crate::simd::hex::bytes_to_hex_32(&ch.0)].0, 1, "the device holds the channel at v1");
        let authority = fold_authority(&community, &editions, &floors);
        assert!(authority.banned.contains(&z), "the banlist reaches B's edit");
        let fold = apply_control_fold(&community, &editions, &floors, &authority);
        assert_eq!(fold.updated.as_ref().and_then(|c| c.channel(&ch)).map(|c| c.name.as_str()), Some("by-b"));
        assert!(!fold.gapped && !authority.gapped, "and nothing is left to page for");
    }

    #[tokio::test]
    async fn a_future_stamp_never_freezes_the_roster_cache() {
        // Signers pick their own `created_at`: the cache stamps from authorized heads only,
        // clamped, and a stamp past any clock (an older build's) doesn't hold the cache back.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Stamp", vec!["wss://r".into()], None).await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let r1 = "d1".repeat(32);
        publish_role(&relay, &community, &owner, &role_at(&r1, "R1", 3, 0), 1).await;
        let year_2100 = 4_102_444_800u64;
        publish_role_at(&relay, &community, &Keys::generate(), &role_at(&"d2".repeat(32), "Junk", 4, 0), 1, year_2100).await;
        let soon = now_ms() / 1000 + 300;
        publish_role_at(&relay, &community, &Keys::generate(), &role_at(&"d4".repeat(32), "Junk soon", 4, 0), 1, soon).await;
        follow_control(&relay, &community).await.unwrap();
        assert_eq!(crate::db::community::get_community_roles_at(&cid_hex).unwrap(), 1_000, "only authorized heads set the stamp");

        let stored = crate::db::community::get_community_roles(&cid_hex).unwrap();
        crate::db::community::set_community_roles(&cid_hex, &stored, year_2100 as i64).unwrap();
        let r2 = "d3".repeat(32);
        publish_role(&relay, &community, &owner, &role_at(&r2, "R2", 5, 0), 1).await;
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        follow_control(&relay, &held).await.unwrap();
        assert!(crate::db::community::get_community_roles(&cid_hex).unwrap().role(&r2).is_some(), "the cache moves past it");
        // An authorized head dated far ahead is clamped too.
        publish_role_at(&relay, &community, &owner, &role_at(&"d5".repeat(32), "Ahead", 6, 0), 1, year_2100).await;
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        follow_control(&relay, &held).await.unwrap();
        assert!(crate::db::community::get_community_roles_at(&cid_hex).unwrap() <= (now_ms() / 1000) as i64 + 600);
    }

    #[tokio::test]
    async fn a_floor_without_its_signers_id_never_falls_back_from_a_copy() {
        // A floor recorded before rumor ids were can't tell its edition from a copy, so a
        // refused copy standing in for it never moves the entity down.
        let (_tmp, _guard, owner) = init_test_db();
        let full = MemoryRelay::new();
        let community = create_community(&full, "Legacy", vec!["wss://r".into()], None).await.unwrap();
        let member = Keys::generate().public_key();
        let (rsen, rlow) = ("a2".repeat(32), "a9".repeat(32));
        publish_role(&full, &community, &owner, &role_at(&rsen, "Senior", 2, 0), 1).await;
        publish_role(&full, &community, &owner, &role_at(&rlow, "Low", 9, 0), 1).await;
        let gm = crate::community::v2::derive::grant_locator(community.id(), &member.to_bytes());
        publish_grant(&full, &community, &owner, &member, vec![rlow.clone()], 1).await;
        publish_grant(&full, &community, &owner, &member, vec![rsen.clone()], 2).await;
        let ch = community.channels[0].id;
        let v1 = head_hash_on_relay(&full, &community, &ch.0).await;
        publish_fork(&[&full], &community, &owner, vsk::CHANNEL_METADATA, &ch.0, 2, v1, &channel_meta_json("real"), None).await;
        follow_control(&full, &community).await.unwrap();
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();

        let editions = fetch_control(&full, &community).await;
        let (g2, ch2) = (
            editions.iter().find(|e| e.entity_id == gm && e.version == 2).unwrap().clone(),
            editions.iter().find(|e| e.entity_id == ch.0 && e.version == 2).unwrap().clone(),
        );
        let stranger = Keys::generate();
        let thin = MemoryRelay::new();
        mirror_control_except(&full, &thin, &community, &|e| e.inner_id == g2.inner_id || e.inner_id == ch2.inner_id).await;
        publish_fork(&[&thin], &community, &stranger, vsk::GRANT, &gm, 2, g2.prev_hash, &g2.content, None).await;
        publish_fork(&[&thin], &community, &stranger, vsk::CHANNEL_METADATA, &ch.0, 2, ch2.prev_hash, &ch2.content, None).await;
        let mut floors = load_floors(&community);
        for e in [&g2, &ch2] {
            floors.insert(crate::simd::hex::bytes_to_hex_32(&e.entity_id), (2, e.self_hash, None, None, None));
        }
        let thin_eds = fetch_control(&thin, &community).await;
        let a = fold_authority(&held, &thin_eds, &floors);
        assert!(a.complete);
        assert_eq!(a.roles.highest_position(&member.to_hex()), Some(2), "no step down to v1");
        let fold = apply_control_fold(&held, &thin_eds, &floors, &a);
        assert!(!fold.heads.iter().any(|h| h.entity_hex == crate::simd::hex::bytes_to_hex_32(&ch.0) && h.rebased), "nor for the channel");
        assert_eq!(fold.updated.as_ref().unwrap_or(&held).channel(&ch).unwrap().name, "real");
    }

    #[tokio::test]
    async fn a_side_branch_cannot_start_a_role_or_grant_over_from_nothing() {
        // An edition acts on what the newest admitted version left, not on what its own
        // `prev` names: a manager naming no predecessor at a high version is judged against
        // the role and the member as they stand.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Branch", vec!["wss://r".into()], None).await.unwrap();
        let w = Keys::generate();
        let senior = Keys::generate().public_key();
        let (radm, rsen, rw, rlow) = ("a2".repeat(32), "a3".repeat(32), "a8".repeat(32), "a9".repeat(32));
        let mr = Permissions::MANAGE_ROLES;
        publish_role(&relay, &community, &owner, &role_at(&radm, "Admin", 2, mr | Permissions::BAN), 1).await;
        publish_role(&relay, &community, &owner, &role_at(&rsen, "Senior", 3, 0), 1).await;
        publish_role(&relay, &community, &owner, &role_at(&rw, "W", 8, mr), 1).await;
        publish_role(&relay, &community, &owner, &role_at(&rlow, "Low", 9, 0), 1).await;
        publish_grant(&relay, &community, &owner, &w.public_key(), vec![rw.clone()], 1).await;
        publish_grant(&relay, &community, &owner, &senior, vec![rsen.clone()], 1).await;
        follow_control(&relay, &community).await.unwrap();
        let gs = crate::community::v2::derive::grant_locator(community.id(), &senior.to_bytes());
        let neutered = crate::community::v2::roles::role_content_json(&role_at(&radm, "Admin", 50, 0)).unwrap();
        publish_fork(&[&relay], &community, &w, vsk::ROLE, &eid_of(&radm), 1_000_000, None, &neutered, None).await;
        let strip = crate::community::v2::roles::grant_content_json(&MemberGrant { member: senior.to_hex(), role_ids: vec![rlow.clone()] }).unwrap();
        publish_fork(&[&relay], &community, &w, vsk::GRANT, &gs, 1_000_000, None, &strip, None).await;
        // On a tracker, a branch at the held version with a successor on top.
        let s_id = publish_fork(&[&relay], &community, &w, vsk::ROLE, &eid_of(&radm), 1, None, &neutered, None).await;
        let s_hash = fetch_control(&relay, &community).await.into_iter().find(|e| e.inner_id == s_id).unwrap().self_hash;
        publish_fork(&[&relay], &community, &w, vsk::ROLE, &eid_of(&radm), 2, Some(s_hash), &neutered, None).await;

        let editions = fetch_control(&relay, &community).await;
        for floors in [Floors::default(), load_floors(&community)] {
            let f = fold_authority(&community, &editions, &floors);
            assert_eq!(f.roles.role(&radm).map(|r| r.position), Some(2), "the Admin role stands");
            assert_eq!(f.roles.highest_position(&senior.to_hex()), Some(3), "and so does the senior member");
        }
    }

    #[tokio::test]
    async fn an_owner_edit_on_a_refused_channel_head_moves_it_on() {
        // A demoted admin's channel edit is the device's held head; the owner then edits on
        // top of it. The owner's edit is the head, with no step down and nothing to page for.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "OnTop", vec!["wss://r".into()], None).await.unwrap();
        let a = Keys::generate();
        let ra = "c1".repeat(32);
        publish_role(&relay, &community, &owner, &role_at(&ra, "A", 1, Permissions::MANAGE_CHANNELS), 1).await;
        publish_grant(&relay, &community, &owner, &a.public_key(), vec![ra.clone()], 1).await;
        let ch = community.channels[0].id;
        let v1 = head_hash_on_relay(&relay, &community, &ch.0).await;
        publish_fork(&[&relay], &community, &a, vsk::CHANNEL_METADATA, &ch.0, 2, v1, &channel_meta_json("by-a"), None).await;
        follow_control(&relay, &community).await.unwrap();
        assert_eq!(floor_of(&community, &ch.0).0, 2);
        publish_grant(&relay, &community, &owner, &a.public_key(), vec![], 2).await;
        let v2 = head_hash_on_relay(&relay, &community, &ch.0).await;
        publish_fork(&[&relay], &community, &owner, vsk::CHANNEL_METADATA, &ch.0, 3, v2, &channel_meta_json("by-owner"), None).await;

        let editions = fetch_control(&relay, &community).await;
        let floors = load_floors(&community);
        let authority = fold_authority(&community, &editions, &floors);
        assert!(authority.complete);
        let fold = apply_control_fold(&community, &editions, &floors, &authority);
        let head = fold.heads.iter().find(|h| h.entity_hex == crate::simd::hex::bytes_to_hex_32(&ch.0)).unwrap();
        assert_eq!((head.version, head.rebased), (3, false), "the owner's edit, not a step down");
        assert_eq!(fold.updated.as_ref().and_then(|c| c.channel(&ch)).map(|c| c.name.as_str()), Some("by-owner"));
        assert!(!fold.gapped);
    }

    #[tokio::test]
    async fn copies_of_compacted_history_never_veto_the_head() {
        // After a compaction the head's history is gone; copies of it re-signed by someone
        // else prove nothing, so they can't make the head stricter than it is on its own.
        let (_tmp, _guard, owner) = init_test_db();
        let full = MemoryRelay::new();
        let community = create_community(&full, "NoVeto", vec!["wss://r".into()], None).await.unwrap();
        let a = Keys::generate();
        let m = Keys::generate().public_key();
        let (radm, ra, rmod, rhelp) = ("d2".repeat(32), "d5".repeat(32), "da".repeat(32), "d7".repeat(32));
        publish_role(&full, &community, &owner, &role_at(&radm, "Admin", 2, 0), 1).await;
        publish_role(&full, &community, &owner, &role_at(&ra, "A", 5, Permissions::MANAGE_ROLES), 1).await;
        publish_role(&full, &community, &owner, &role_at(&rhelp, "Helper", 7, 0), 1).await;
        publish_role(&full, &community, &owner, &role_at(&rmod, "Mod", 10, 0), 1).await;
        publish_grant(&full, &community, &owner, &a.public_key(), vec![ra.clone()], 1).await;
        let gm = crate::community::v2::derive::grant_locator(community.id(), &m.to_bytes());
        publish_grant(&full, &community, &owner, &m, vec![radm.clone()], 1).await;
        publish_grant(&full, &community, &owner, &m, vec![rmod.clone()], 2).await;
        publish_grant(&full, &community, &a, &m, vec![rhelp.clone()], 3).await;
        let editions = fetch_control(&full, &community).await;
        let history: Vec<&ParsedEdition> = editions.iter().filter(|e| e.entity_id == gm && e.version < 3).collect();
        let thin = MemoryRelay::new();
        mirror_control_except(&full, &thin, &community, &|e| e.entity_id == gm && e.version < 3).await;
        let copier = Keys::generate();
        for e in &history {
            publish_fork(&[&thin], &community, &copier, vsk::GRANT, &gm, e.version, e.prev_hash, &e.content, None).await;
        }
        let f = fold_authority(&community, &fetch_control(&thin, &community).await, &Floors::default());
        assert_eq!(f.roles.highest_position(&m.to_hex()), Some(7), "the head stands on its own claims");
    }

    #[tokio::test]
    async fn refused_or_unauthorized_editions_leave_nothing_to_page_for() {
        // A banlist held from a since-demoted moderator, with nothing newer to reach, and a
        // stranger's unlinked junk above a tracked role: neither is a gap.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "NoGap", vec!["wss://r".into()], None).await.unwrap();
        let moder = Keys::generate();
        let (rm, rr) = ("e1".repeat(32), "e6".repeat(32));
        publish_role(&relay, &community, &owner, &role_at(&rm, "Mod", 1, Permissions::BAN), 1).await;
        publish_grant(&relay, &community, &owner, &moder.public_key(), vec![rm.clone()], 1).await;
        publish_role(&relay, &community, &owner, &role_at(&rr, "R", 6, 0), 1).await;
        let x = Keys::generate().public_key().to_hex();
        publish_banlist(&relay, &community, &owner, &[], 1).await;
        publish_banlist(&relay, &community, &moder, &[x.clone()], 2).await;
        follow_control(&relay, &community).await.unwrap();
        publish_grant(&relay, &community, &owner, &moder.public_key(), vec![], 2).await;
        let junk = crate::community::v2::roles::role_content_json(&role_at(&rr, "Junk", 6, 0)).unwrap();
        publish_fork(&[&relay], &community, &Keys::generate(), vsk::ROLE, &eid_of(&rr), 9, Some([3u8; 32]), &junk, None).await;
        let a = fold_authority(&community, &fetch_control(&relay, &community).await, &load_floors(&community));
        assert!(!a.gapped, "nothing to page for");
        assert_eq!(a.roles.role(&rr).map(|r| r.name.as_str()), Some("R"));
    }

    #[tokio::test]
    async fn only_the_owner_stands_in_for_a_withheld_held_role_edit() {
        // Without the held edition its claims are unknown, so a better-ranked rival can't be
        // judged against them: a relay withholding C's move can't swap in P's.
        let (_tmp, _guard, owner) = init_test_db();
        let full = MemoryRelay::new();
        let community = create_community(&full, "Rival", vec!["wss://r".into()], None).await.unwrap();
        let (c, p) = (Keys::generate(), Keys::generate());
        let (rcos, rc, rpm, rr) = ("f1".repeat(32), "f2".repeat(32), "f7".repeat(32), "fa".repeat(32));
        let mr = Permissions::MANAGE_ROLES;
        publish_role(&full, &community, &owner, &role_at(&rcos, "Cosmetic", 1, 0), 1).await;
        publish_role(&full, &community, &owner, &role_at(&rc, "C", 2, mr), 1).await;
        publish_role(&full, &community, &owner, &role_at(&rpm, "P", 7, mr), 1).await;
        publish_grant(&full, &community, &owner, &c.public_key(), vec![rc.clone()], 1).await;
        publish_grant(&full, &community, &owner, &p.public_key(), vec![rcos.clone(), rpm.clone()], 1).await;
        publish_role(&full, &community, &owner, &role_at(&rr, "R", 10, 0), 1).await;
        let v1 = head_hash_on_relay(&full, &community, &eid_of(&rr)).await;
        let moved = crate::community::v2::roles::role_content_json(&role_at(&rr, "R", 5, 0)).unwrap();
        let held = publish_fork(&[&full], &community, &c, vsk::ROLE, &eid_of(&rr), 2, v1, &moved, None).await;
        follow_control(&full, &community).await.unwrap();
        assert_eq!(floor_of(&community, &eid_of(&rr)).1, Some(held));
        let thin = MemoryRelay::new();
        mirror_control_except(&full, &thin, &community, &|e| e.inner_id == held).await;
        let down = crate::community::v2::roles::role_content_json(&role_at(&rr, "R", 11, 0)).unwrap();
        publish_fork(&[&thin], &community, &p, vsk::ROLE, &eid_of(&rr), 2, v1, &down, None).await;

        let a = fold_authority(&community, &fetch_control(&thin, &community).await, &load_floors(&community));
        assert_ne!(a.roles.role(&rr).map(|r| r.position), Some(11), "P's rival does not stand in");
        let held_c = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        follow_control(&thin, &held_c).await.unwrap();
        assert_eq!(floor_of(&community, &eid_of(&rr)).1, Some(held), "and the floor keeps C's edit");
    }

    #[tokio::test]
    async fn a_refounding_never_launders_a_kept_head() {
        // E's rename chain is the tracker's held head until S's sibling makes it refused; the
        // tracker keeps it. A Refounding must carry what a floorless reader folds, S's move,
        // or the new epoch reads E's rename on its own and S's decision is lost.
        let (bed, owner, _m) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Launder", bed.relays.clone(), None).await.unwrap();
        let (e, sk) = (Keys::generate(), Keys::generate());
        let (rs, re, rr) = ("a2".repeat(32), "a4".repeat(32), "a6".repeat(32));
        let mr = Permissions::MANAGE_ROLES;
        publish_role(&bed.relay, &community, &owner.keys, &role_at(&rs, "S", 2, mr), 1).await;
        publish_role(&bed.relay, &community, &owner.keys, &role_at(&re, "E", 4, mr), 1).await;
        publish_grant(&bed.relay, &community, &owner.keys, &sk.public_key(), vec![rs.clone()], 1).await;
        publish_grant(&bed.relay, &community, &owner.keys, &e.public_key(), vec![re.clone()], 1).await;
        publish_role(&bed.relay, &community, &owner.keys, &role_at(&rr, "R", 6, 0), 1).await;
        let v1 = head_hash_on_relay(&bed.relay, &community, &eid_of(&rr)).await;
        publish_role(&bed.relay, &community, &e, &role_at(&rr, "R by E", 6, 0), 2).await;
        publish_role(&bed.relay, &community, &e, &role_at(&rr, "R by E again", 6, 0), 3).await;
        follow_control(&bed.relay, &community).await.unwrap();
        assert_eq!(floor_of(&community, &eid_of(&rr)).0, 3);
        let up = crate::community::v2::roles::role_content_json(&role_at(&rr, "R by S", 3, 0)).unwrap();
        publish_fork(&[&bed.relay], &community, &sk, vsk::ROLE, &eid_of(&rr), 2, v1, &up, None).await;
        let a = fold_authority(&community, &fetch_control(&bed.relay, &community).await, &load_floors(&community));
        assert!(a.carried.contains(&rr), "the tracker keeps E's refused head");

        let refounded = refound_community(&bed.relay, &community, &[]).await.unwrap();
        let fresh = fold_authority(&refounded, &fetch_control(&bed.relay, &refounded).await, &Floors::default());
        assert_eq!(fresh.roles.role(&rr).map(|r| r.name.as_str()), Some("R by S"), "the new epoch carries S's move");
    }

    #[tokio::test]
    async fn a_refounding_never_carries_a_refused_control_head_it_keeps() {
        // A Mod renamed the Community twice and then lost the bit: the tracker keeps the second
        // rename, its predecessor refused too. The new epoch must read the owner's name, never
        // the kept rename re-wrapped as if it stood (CORD-06 §3).
        let (bed, owner, _m) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Original", bed.relays.clone(), None).await.unwrap();
        let mod_key = Keys::generate();
        let rm = "d2".repeat(32);
        let bits = Permissions::MANAGE_METADATA | Permissions::MANAGE_CHANNELS;
        publish_role(&bed.relay, &community, &owner.keys, &role_at(&rm, "Mod", 2, bits), 1).await;
        publish_grant(&bed.relay, &community, &owner.keys, &mod_key.public_key(), vec![rm.clone()], 1).await;
        publish_community_meta(&bed.relay, &community, &mod_key, "By Mod", 2).await;
        publish_community_meta(&bed.relay, &community, &mod_key, "By Mod again", 3).await;
        let channel = ChannelId([0xd7; 32]);
        publish_fork(&[&bed.relay], &community, &mod_key, vsk::CHANNEL_METADATA, &channel.0, 1, None, &channel_meta_json("mods"), None).await;
        follow_control(&bed.relay, &community).await.unwrap();
        assert_eq!(floor_of(&community, &community.id().0).0, 3);
        assert_eq!(floor_of(&community, &channel.0).0, 1);
        publish_grant(&bed.relay, &community, &owner.keys, &mod_key.public_key(), vec![], 2).await;
        follow_control(&bed.relay, &community).await.unwrap();
        let eds = fetch_control(&bed.relay, &community).await;
        let floors = load_floors(&community);
        let tracked = apply_control_fold(&community, &eds, &floors, &fold_authority(&community, &eds, &floors));
        assert!(tracked.kept.contains(&crate::simd::hex::bytes_to_hex_32(&community.id().0)), "the tracker keeps the refused rename");
        assert!(tracked.kept.contains(&crate::simd::hex::bytes_to_hex_32(&channel.0)), "and the refused Channel");

        let refounded = refound_community(&bed.relay, &community, &[]).await.unwrap();
        let carried = fetch_control(&bed.relay, &refounded).await;
        assert!(carried.iter().all(|e| e.author != mod_key.public_key()), "nothing the Roster refuses crosses");
        let fresh = apply_control_fold(&refounded, &carried, &Floors::default(), &fold_authority(&refounded, &carried, &Floors::default()));
        let meta = fresh.heads.iter().find(|h| h.entity_hex == crate::simd::hex::bytes_to_hex_32(&community.id().0)).expect("a metadata head crosses");
        let content = &carried.iter().find(|e| e.inner_id == meta.inner_id).unwrap().content;
        assert_eq!(serde_json::from_str::<control::CommunityMetadata>(content).unwrap().name, "Original", "the head a floorless reader folds");
    }

    #[tokio::test]
    async fn a_demoted_mods_rename_stands_through_a_refounding() {
        // A demotion seals what the Mod decided before it lands (CORD-04 §9), so the rename stands
        // for every reader, a fresh joiner of the next epoch included.
        let (bed, owner, _m) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Original", bed.relays.clone(), None).await.unwrap();
        publish_everyone(&bed.relay, &community, &owner.keys, 0, 1).await;
        let mod_key = Keys::generate();
        let rm = "d6".repeat(32);
        publish_role_v2(&bed.relay, &community, &owner.keys, &role_v2(&rm, "Mod", "F", Permissions::MANAGE_METADATA), 1).await;
        publish_grant(&bed.relay, &community, &owner.keys, &mod_key.public_key(), vec![rm.clone()], 1).await;
        publish_community_meta(&bed.relay, &community, &mod_key, "By Mod", 2).await;
        publish_community_meta(&bed.relay, &community, &mod_key, "By Mod again", 3).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        assert_eq!(held().name, "By Mod again");

        grant_roles(&bed.relay, &held(), &mod_key.public_key(), vec![]).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        let eds = fetch_control(&bed.relay, &held()).await;
        assert!(eds.iter().any(|e| e.vsk == vsk::TENURE), "the demotion wrote a Tenure");
        assert_eq!(fold_authority(&held(), &eds, &load_floors(&held())).roles.roles_of(&mod_key.public_key().to_hex()).count(), 0, "the Mod holds no Role");
        assert_eq!(held().name, "By Mod again", "and the rename stands for this member");

        let refounded = refound_community(&bed.relay, &held(), &[]).await.unwrap();
        let carried = fetch_control(&bed.relay, &refounded).await;
        let fresh = apply_control_fold(&refounded, &carried, &Floors::default(), &fold_authority(&refounded, &carried, &Floors::default()));
        let meta = fresh.heads.iter().find(|h| h.entity_hex == crate::simd::hex::bytes_to_hex_32(&community.id().0)).expect("a metadata head crosses");
        let head = carried.iter().find(|e| e.inner_id == meta.inner_id).unwrap();
        assert_eq!(head.author, mod_key.public_key());
        assert_eq!(serde_json::from_str::<control::CommunityMetadata>(&head.content).unwrap().name, "By Mod again", "and for a fresh joiner of the new epoch");
    }

    /// Every edition a follow's read holds, against a fresh open of the same wrap.
    async fn read_as_fresh_opens_read(relay: &MemoryRelay, community: &CommunityV2, step: &str) {
        let read = read_control(relay, community).await.unwrap();
        let fresh: std::collections::HashMap<[u8; 32], String> = fetch_control(relay, community).await.iter().map(|e| (e.inner_id, format!("{e:?}"))).collect();
        assert!(!read.editions.is_empty(), "{step}: the read found the plane");
        for e in &read.editions {
            assert_eq!(fresh.get(&e.inner_id), Some(&format!("{e:?}")), "{step}: an edition the follow read differs from its fresh open");
        }
    }

    #[tokio::test]
    async fn a_follow_reads_what_fresh_opens_read_through_every_kind_of_change() {
        // Each change arrives as new wraps; the memo serves only wraps the relay serves again,
        // as their own open would. So after any change a follow sees what a cold read does.
        let (bed, owner, _m) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Churn", bed.relays.clone(), None).await.unwrap();
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let (a, b) = (Keys::generate().public_key(), Keys::generate().public_key());
        follow_control(&bed.relay, &held()).await.unwrap();
        read_as_fresh_opens_read(&bed.relay, &held(), "created").await;
        let view = control::ControlPlane::of(&held());
        let q = Query { kinds: vec![stream::KIND_WRAP], authors: vec![view.pk().to_hex()], limit: Some(500), ..Default::default() };
        let before = bed.relay.fetch(&q, &held().relays).await.unwrap();
        assert!(before.iter().all(|w| control::opened_held(&view, w)), "the follow kept every open");

        grant_admin(&bed.relay, &held(), &a).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        read_as_fresh_opens_read(&bed.relay, &held(), "granted").await;
        assert!(crate::db::community::get_community_roles(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap().grants.iter().any(|g| g.member == a.to_hex()));

        let renamed = control::CommunityMetadata { name: "Churned".into(), ..held().metadata() };
        edit_community_metadata(&bed.relay, &held(), &renamed).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        read_as_fresh_opens_read(&bed.relay, &held(), "renamed").await;
        assert_eq!(held().name, "Churned");

        let ch = create_channel_in(&bed.relay, &held(), "side", false, None).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        read_as_fresh_opens_read(&bed.relay, &held(), "channel created").await;
        assert!(held().channel(&ch).is_some());

        set_banlist(&bed.relay, &held(), &[b.to_hex()]).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        read_as_fresh_opens_read(&bed.relay, &held(), "banned").await;
        assert!(crate::db::community::get_community_banlist(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap().contains(&b.to_hex()));

        kick_member(&bed.relay, &held(), &a).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        read_as_fresh_opens_read(&bed.relay, &held(), "kicked").await;

        grant_roles(&bed.relay, &held(), &a, vec![]).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        read_as_fresh_opens_read(&bed.relay, &held(), "revoked").await;
        assert!(crate::db::community::get_community_roles(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap().grants.iter().all(|g| g.member != a.to_hex() || g.role_ids.is_empty()));

        delete_channel(&bed.relay, &held(), &ch, "side").await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        read_as_fresh_opens_read(&bed.relay, &held(), "channel deleted").await;
        assert!(held().channel(&ch).is_none());

        set_banlist(&bed.relay, &held(), &[]).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        read_as_fresh_opens_read(&bed.relay, &held(), "unbanned").await;
        assert!(crate::db::community::get_community_banlist(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap().is_empty());

        // And the fold over what the follow read equals one over fresh opens, end to end.
        let floors = load_floors(&held());
        let read = read_control(&bed.relay, &held()).await.unwrap();
        control::forget_opened();
        let cold = read_control(&bed.relay, &held()).await.unwrap();
        assert_eq!(authority_whole(&read.authority), authority_whole(&cold.authority));
        assert_eq!(format!("{:?}", read.fold.updated.map(|c| c.metadata())), format!("{:?}", cold.fold.updated.map(|c| c.metadata())));
        assert_eq!(authority_whole(&fold_authority(&held(), &read.editions, &floors)), authority_whole(&fold_authority(&held(), &cold.editions, &floors)));
    }

    #[tokio::test]
    async fn opened_control_editions_stay_with_the_account_that_opened_them() {
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Mine", bed.relays.clone(), None).await.unwrap();
        follow_control(&bed.relay, &community).await.unwrap();
        let view = control::ControlPlane::of(&community);
        let q = Query { kinds: vec![stream::KIND_WRAP], authors: vec![view.pk().to_hex()], limit: Some(500), ..Default::default() };
        let wraps = bed.relay.fetch(&q, &community.relays).await.unwrap();
        assert!(wraps.iter().any(|w| control::opened_held(&view, w)));
        bed.swap_to(&member);
        assert!(!wraps.iter().any(|w| control::opened_held(&view, w)), "another account's session holds none of them");
    }

    #[tokio::test]
    async fn a_roster_fold_that_runs_out_its_bound_keeps_nothing_it_judged() {
        let (bed, owner, _m) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Bound", bed.relays.clone(), None).await.unwrap();
        follow_control(&bed.relay, &community).await.unwrap();
        let cid = community.id().0;
        let before = floor_of(&community, &cid);
        publish_community_meta(&bed.relay, &community, &owner.keys, "Renamed", 2).await;
        FOLD_BOUND.with(|b| b.set(Some(0)));
        let follow = follow_control(&bed.relay, &community).await;
        FOLD_BOUND.with(|b| b.set(None));
        assert!(follow.unwrap().updated.is_none(), "nothing adopted");
        assert_eq!(floor_of(&community, &cid), before, "no floor moves");
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        assert_eq!(held().name, "Bound");
        follow_control(&bed.relay, &community).await.unwrap();
        assert_eq!(held().name, "Renamed", "the next settled fold keeps it");
        assert_eq!(floor_of(&community, &cid).0, 2);
    }

    #[tokio::test]
    async fn a_join_seeds_nothing_from_a_roster_fold_that_runs_out_its_bound() {
        let (bed, owner, _m) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "BoundJoin", bed.relays.clone(), None).await.unwrap();
        let rm = "d4".repeat(32);
        publish_role(&bed.relay, &community, &owner.keys, &role_at(&rm, "Mod", 2, Permissions::BAN), 1).await;
        publish_grant(&bed.relay, &community, &owner.keys, &Keys::generate().public_key(), vec![rm.clone()], 1).await;
        publish_banlist(&bed.relay, &community, &owner.keys, &[Keys::generate().public_key().to_hex()], 1).await;
        let settled = verify_owner_root_and_reconcile(&bed.relay, community.clone()).await.unwrap();
        assert!(settled.roles.is_some() && settled.banlist_persist.is_some() && !settled.authority_heads.is_empty());
        FOLD_BOUND.with(|b| b.set(Some(0)));
        let guessed = verify_owner_root_and_reconcile(&bed.relay, community.clone()).await;
        FOLD_BOUND.with(|b| b.set(None));
        let guessed = guessed.unwrap();
        assert!(guessed.roles.is_none() && guessed.banlist_persist.is_none() && guessed.authority_heads.is_empty(), "no Roster, banlist or floor from a guess");
        assert_eq!(guessed.community.name, settled.community.name, "the owner's own document still folds");
    }

    #[tokio::test]
    async fn keeping_or_stepping_down_never_oscillates() {
        // Whether A's grant keeps B's refused v3 or steps down to C's v2 depends on C, whose
        // authority comes from A. Judged only on authority above A's grant, it settles.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Settle", vec!["wss://r".into()], None).await.unwrap();
        let (a, b, c) = (Keys::generate(), Keys::generate(), Keys::generate());
        let (rz, rp, rk, rq, rq2) = ("b2".repeat(32), "b3".repeat(32), "b4".repeat(32), "b5".repeat(32), "b6".repeat(32));
        let mr = Permissions::MANAGE_ROLES;
        publish_role(&relay, &community, &owner, &role_at(&rz, "Z", 2, mr | Permissions::BAN), 1).await;
        publish_role(&relay, &community, &owner, &role_at(&rp, "P", 3, mr), 1).await;
        publish_role(&relay, &community, &owner, &role_at(&rk, "K", 4, mr), 1).await;
        publish_role(&relay, &community, &owner, &role_at(&rq, "Q", 5, 0), 1).await;
        publish_role(&relay, &community, &owner, &role_at(&rq2, "Q2", 6, 0), 1).await;
        publish_grant(&relay, &community, &owner, &b.public_key(), vec![rz.clone()], 1).await;
        publish_grant(&relay, &community, &owner, &a.public_key(), vec![rq2.clone()], 1).await;
        publish_grant(&relay, &community, &c, &a.public_key(), vec![rq.clone()], 2).await;
        publish_grant(&relay, &community, &b, &a.public_key(), vec![rp.clone()], 3).await;
        publish_grant(&relay, &community, &a, &c.public_key(), vec![rk.clone()], 1).await;
        follow_control(&relay, &community).await.unwrap();
        publish_grant(&relay, &community, &owner, &b.public_key(), vec![], 2).await;

        let editions = fetch_control(&relay, &community).await;
        let floors = load_floors(&community);
        let one = fold_authority(&community, &editions, &floors);
        assert!(one.converged, "the fold settles");
        let reversed: Vec<ParsedEdition> = editions.iter().rev().cloned().collect();
        let two = fold_authority(&community, &reversed, &floors);
        assert_eq!(authority_fingerprint(&one), authority_fingerprint(&two), "in any order");
        // Unrelated extra entities don't flip it either.
        publish_role(&relay, &community, &owner, &role_at(&"b9".repeat(32), "Extra", 9, 0), 1).await;
        let three = fold_authority(&community, &fetch_control(&relay, &community).await, &floors);
        assert!(three.converged);
        assert_eq!(three.roles.highest_position(&a.public_key().to_hex()), one.roles.highest_position(&a.public_key().to_hex()));
    }

    #[tokio::test]
    async fn an_edit_its_author_could_not_make_is_never_a_gap() {
        // The lowest manager publishing far above a role they can't touch, linked to nothing:
        // refused, so nothing to page for.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "NoPage", vec!["wss://r".into()], None).await.unwrap();
        let low = Keys::generate();
        let (rlow, rr) = ("c9".repeat(32), "c3".repeat(32));
        publish_role(&relay, &community, &owner, &role_at(&rlow, "Low", 9, Permissions::MANAGE_ROLES), 1).await;
        publish_grant(&relay, &community, &owner, &low.public_key(), vec![rlow.clone()], 1).await;
        publish_role(&relay, &community, &owner, &role_at(&rr, "R", 3, 0), 1).await;
        follow_control(&relay, &community).await.unwrap();
        let junk = crate::community::v2::roles::role_content_json(&role_at(&rr, "R", 50, 0)).unwrap();
        let f1 = head_hash_on_relay(&relay, &community, &eid_of(&rr)).await;
        publish_fork(&[&relay], &community, &low, vsk::ROLE, &eid_of(&rr), 6, f1, &junk, None).await;
        let a = fold_authority(&community, &fetch_control(&relay, &community).await, &load_floors(&community));
        assert!(!a.gapped);
        assert_eq!(a.roles.role(&rr).map(|r| r.position), Some(3));
    }

    #[tokio::test]
    async fn a_ban_then_refounding_keeps_the_owners_edition_under_the_banned_one() {
        // X renamed R; the owner bans X and re-founds at once, with no follow between. The
        // re-founding carries the fold's decision, the owner's v1, not X's floored edition.
        let (bed, owner, _m) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "BanRefound", bed.relays.clone(), None).await.unwrap();
        let x = Keys::generate();
        let (rx, rr) = ("a1".repeat(32), "a6".repeat(32));
        publish_role(&bed.relay, &community, &owner.keys, &role_at(&rx, "X", 1, Permissions::MANAGE_ROLES), 1).await;
        publish_grant(&bed.relay, &community, &owner.keys, &x.public_key(), vec![rx.clone()], 1).await;
        publish_role(&bed.relay, &community, &owner.keys, &role_at(&rr, "R", 6, 0), 1).await;
        publish_role(&bed.relay, &community, &x, &role_at(&rr, "R by X", 6, 0), 2).await;
        let own = "a8".repeat(32);
        publish_role(&bed.relay, &community, &x, &role_at(&own, "X's own", 8, 0), 1).await;
        follow_control(&bed.relay, &community).await.unwrap();
        assert_eq!(floor_of(&community, &eid_of(&rr)).0, 2);
        publish_banlist(&bed.relay, &community, &owner.keys, &[x.public_key().to_hex()], 1).await;
        publish_grant(&bed.relay, &community, &owner.keys, &x.public_key(), vec![], 2).await;
        let refounded = refound_community(&bed.relay, &community, &[x.public_key()]).await.unwrap();
        let fresh = fold_authority(&refounded, &fetch_control(&bed.relay, &refounded).await, &Floors::default());
        assert_eq!(fresh.roles.role(&rr).map(|r| r.name.as_str()), Some("R"), "the owner's edition survives the re-founding");
        assert!(fresh.banned.contains(&x.public_key().to_hex()), "and so does the ban, floored here or not");
        assert!(!fetch_control(&bed.relay, &refounded).await.iter().any(|e| e.entity_id == eid_of(&own)), "a role settled as absent isn't carried");
    }

    #[tokio::test]
    async fn a_ban_falls_back_to_what_stood_before_the_banned_signer() {
        // A ban takes every edition its target wrote, the held one included: the entity is
        // read as if they never wrote, and pages for what stood before them when that is unread.
        let (_tmp, _guard, owner) = init_test_db();
        let full = MemoryRelay::new();
        let community = create_community(&full, "BanBack", vec!["wss://r".into()], None).await.unwrap();
        let x = Keys::generate();
        let (rx, r1, r2, r3) = ("b1".repeat(32), "b5".repeat(32), "b6".repeat(32), "b7".repeat(32));
        publish_role(&full, &community, &owner, &role_at(&rx, "X", 1, Permissions::MANAGE_ROLES), 1).await;
        publish_grant(&full, &community, &owner, &x.public_key(), vec![rx.clone()], 1).await;
        // R1: the owner's v1 under two of X's edits. R2: X's own from the genesis.
        publish_role(&full, &community, &owner, &role_at(&r1, "R1", 5, 0), 1).await;
        publish_role(&full, &community, &x, &role_at(&r1, "R1 x", 5, 0), 2).await;
        publish_role(&full, &community, &x, &role_at(&r1, "R1 xx", 5, 0), 3).await;
        publish_role(&full, &community, &x, &role_at(&r2, "R2", 6, 0), 1).await;
        publish_role(&full, &community, &x, &role_at(&r2, "R2 x", 6, 0), 2).await;
        // R3: the owner's v1 under one X edit, with v1 not served below.
        publish_role(&full, &community, &owner, &role_at(&r3, "R3", 7, 0), 1).await;
        let r3v1 = head_hash_on_relay(&full, &community, &eid_of(&r3)).await.unwrap();
        publish_role(&full, &community, &x, &role_at(&r3, "R3 x", 7, 0), 2).await;
        follow_control(&full, &community).await.unwrap();
        publish_banlist(&full, &community, &owner, &[x.public_key().to_hex()], 1).await;

        let a = fold_authority(&community, &fetch_control(&full, &community).await, &load_floors(&community));
        assert_eq!(a.roles.role(&r1).map(|r| r.name.as_str()), Some("R1"), "back to the owner's v1");
        assert!(a.heads.iter().any(|h| h.entity_hex == r1 && h.version == 1 && h.rebased));
        assert!(a.refused.contains(&r2) && a.roles.role(&r2).is_none(), "X's own role goes");
        assert!(!a.gapped, "with every link read, nothing to page for");
        let thin = MemoryRelay::new();
        mirror_control_except(&full, &thin, &community, &|e| e.self_hash == r3v1).await;
        let t = fold_authority(&community, &fetch_control(&thin, &community).await, &load_floors(&community));
        assert!(t.refused.contains(&r3) && t.gapped, "with what stood before unread, it settles as a floorless reader does and pages for the rest");
    }

    #[tokio::test]
    async fn a_junk_edition_never_poisons_the_proof_of_the_next_one() {
        // A link proof depends on the version it is made from: junk naming the held hash at
        // the held version must not decide the proof of the real next edition.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Poison", vec!["wss://r".into()], None).await.unwrap();
        let (a, m) = (Keys::generate(), Keys::generate());
        let (ra, rr) = ("c1".repeat(32), "c6".repeat(32));
        publish_role(&relay, &community, &owner, &role_at(&ra, "A", 1, Permissions::MANAGE_ROLES), 1).await;
        publish_grant(&relay, &community, &owner, &a.public_key(), vec![ra.clone()], 1).await;
        publish_role(&relay, &community, &owner, &role_at(&rr, "R", 6, 0), 1).await;
        publish_role(&relay, &community, &a, &role_at(&rr, "R2", 6, 0), 2).await;
        follow_control(&relay, &community).await.unwrap();
        let h2 = head_hash_on_relay(&relay, &community, &eid_of(&rr)).await;
        let junk = crate::community::v2::roles::role_content_json(&role_at(&rr, "junk", 6, 0)).unwrap();
        publish_fork(&[&relay], &community, &m, vsk::ROLE, &eid_of(&rr), 2, h2, &junk, None).await;
        let next = crate::community::v2::roles::role_content_json(&role_at(&rr, "R3", 6, 0)).unwrap();
        publish_fork(&[&relay], &community, &a, vsk::ROLE, &eid_of(&rr), 3, h2, &next, None).await;
        let f = fold_authority(&community, &fetch_control(&relay, &community).await, &load_floors(&community));
        assert_eq!(f.roles.role(&rr).map(|r| r.name.as_str()), Some("R3"), "A's next edit advances");
    }

    #[tokio::test]
    async fn an_edition_at_the_last_version_folds_without_overflow() {
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Overflow", vec!["wss://r".into()], None).await.unwrap();
        let rr = "d6".repeat(32);
        publish_role(&relay, &community, &owner, &role_at(&rr, "R", 6, 0), 1).await;
        follow_control(&relay, &community).await.unwrap();
        let junk = crate::community::v2::roles::role_content_json(&role_at(&rr, "top", 6, 0)).unwrap();
        let top = publish_fork(&[&relay], &community, &Keys::generate(), vsk::ROLE, &eid_of(&rr), u64::MAX, None, &junk, None).await;
        let top_hash = fetch_control(&relay, &community).await.into_iter().find(|e| e.inner_id == top).unwrap().self_hash;
        publish_fork(&[&relay], &community, &Keys::generate(), vsk::ROLE, &eid_of(&rr), 2, Some(top_hash), &junk, None).await;
        let f = fold_authority(&community, &fetch_control(&relay, &community).await, &load_floors(&community));
        assert_eq!(f.roles.role(&rr).map(|r| r.name.as_str()), Some("R"));
    }

    #[tokio::test]
    async fn a_channel_edition_at_the_banlists_coordinate_is_no_channel() {
        // A channel id is random, so one at the banlist's coordinate is aimed at the banlist:
        // it folds no head, and a re-founding still carries the real banlist.
        let (bed, owner, _m) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Squat", bed.relays.clone(), None).await.unwrap();
        let staff = Keys::generate();
        let rs = "e1".repeat(32);
        publish_role(&bed.relay, &community, &owner.keys, &role_at(&rs, "Staff", 1, Permissions::MANAGE_CHANNELS), 1).await;
        publish_grant(&bed.relay, &community, &owner.keys, &staff.public_key(), vec![rs.clone()], 1).await;
        let x = Keys::generate().public_key().to_hex();
        set_banlist(&bed.relay, &community, &[x.clone()]).await.unwrap();
        follow_control(&bed.relay, &community).await.unwrap();
        let bl = crate::community::v2::derive::banlist_locator(community.id());
        let head = head_hash_on_relay(&bed.relay, &community, &bl).await;
        let v = floor_of(&community, &bl).0;
        publish_fork(&[&bed.relay], &community, &staff, vsk::CHANNEL_METADATA, &bl, v + 1, head, &channel_meta_json("phantom"), None).await;

        let editions = fetch_control(&bed.relay, &community).await;
        let floors = load_floors(&community);
        let authority = fold_authority(&community, &editions, &floors);
        let fold = apply_control_fold(&community, &editions, &floors, &authority);
        assert!(!fold.heads.iter().any(|h| h.entity_hex == crate::simd::hex::bytes_to_hex_32(&bl)), "no channel head at the banlist's coordinate");
        let refounded = refound_community(&bed.relay, &community, &[]).await.unwrap();
        let fresh = fold_authority(&refounded, &fetch_control(&bed.relay, &refounded).await, &Floors::default());
        assert!(fresh.banned.contains(&x), "the real banlist is carried");
    }

    #[tokio::test]
    async fn a_ban_after_a_refounding_settles_the_banned_signers_edition() {
        // After a compaction the held edition's history is gone, so a ban that voids it reads
        // down to nothing it can name. The grant settles as absent rather than freezing the roster.
        let (bed, owner, _m) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "BanAfter", bed.relays.clone(), None).await.unwrap();
        let x = Keys::generate();
        let m = Keys::generate().public_key();
        let (rx, rmid, rlow) = ("f1".repeat(32), "f6".repeat(32), "f9".repeat(32));
        publish_role(&bed.relay, &community, &owner.keys, &role_at(&rx, "X", 1, Permissions::MANAGE_ROLES), 1).await;
        publish_role(&bed.relay, &community, &owner.keys, &role_at(&rmid, "Mid", 6, 0), 1).await;
        publish_role(&bed.relay, &community, &owner.keys, &role_at(&rlow, "Low", 9, 0), 1).await;
        publish_grant(&bed.relay, &community, &owner.keys, &x.public_key(), vec![rx.clone()], 1).await;
        publish_grant(&bed.relay, &community, &owner.keys, &m, vec![rlow.clone()], 1).await;
        publish_grant(&bed.relay, &community, &x, &m, vec![rmid.clone()], 2).await;
        follow_control(&bed.relay, &community).await.unwrap();
        let refounded = refound_community(&bed.relay, &community, &[]).await.unwrap();
        follow_control(&bed.relay, &refounded).await.unwrap();
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        set_banlist(&bed.relay, &held, &[x.public_key().to_hex()]).await.unwrap();

        let gm = crate::simd::hex::bytes_to_hex_32(&crate::community::v2::derive::grant_locator(community.id(), &m.to_bytes()));
        let a = fold_authority(&held, &fetch_control(&bed.relay, &held).await, &load_floors(&held));
        assert!(a.refused.contains(&gm), "the banned signer's grant settles as absent");
        follow_control(&bed.relay, &held).await.unwrap();
        let cached = crate::db::community::get_community_roles(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap();
        assert_eq!(cached.roles_of(&m.to_hex()).count(), 0, "and the roster cache moves on");
    }

    #[tokio::test]
    async fn a_refounding_never_carries_what_this_device_refuses() {
        // R is kept on this device, and a floorless reader would take A's edit on top of it.
        // This device's own evidence refuses that edit, so the re-founding doesn't carry it.
        let (bed, owner, _m) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "NoCarry", bed.relays.clone(), None).await.unwrap();
        let (a, b, c) = (Keys::generate(), Keys::generate(), Keys::generate());
        let (rc, rb, ra, rr) = ("a1".repeat(32), "a2".repeat(32), "a3".repeat(32), "a7".repeat(32));
        let mr = Permissions::MANAGE_ROLES;
        publish_role(&bed.relay, &community, &owner.keys, &role_at(&rc, "C", 1, mr), 1).await;
        publish_role(&bed.relay, &community, &owner.keys, &role_at(&rb, "B", 1, mr), 1).await;
        publish_role(&bed.relay, &community, &owner.keys, &role_at(&ra, "A", 3, mr), 1).await;
        for (k, r) in [(&c, &rc), (&b, &rb), (&a, &ra)] {
            publish_grant(&bed.relay, &community, &owner.keys, &k.public_key(), vec![r.clone()], 1).await;
        }
        publish_role(&bed.relay, &community, &c, &role_at(&rr, "R", 2, 0), 1).await;
        publish_role(&bed.relay, &community, &b, &role_at(&rr, "R by B", 2, 0), 2).await;
        follow_control(&bed.relay, &community).await.unwrap();
        publish_grant(&bed.relay, &community, &owner.keys, &c.public_key(), vec![], 2).await;
        publish_grant(&bed.relay, &community, &owner.keys, &b.public_key(), vec![], 2).await;
        publish_role(&bed.relay, &community, &a, &role_at(&rr, "R by A", 5, 0), 3).await;
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let t = fold_authority(&held, &fetch_control(&bed.relay, &held).await, &load_floors(&held));
        assert!(t.carried.contains(&rr), "kept on this device");

        let refounded = refound_community(&bed.relay, &held, &[]).await.unwrap();
        let fresh = fold_authority(&refounded, &fetch_control(&bed.relay, &refounded).await, &Floors::default());
        assert_ne!(fresh.roles.role(&rr).map(|r| r.name.as_str()), Some("R by A"), "A's edit isn't carried");
    }

    #[tokio::test]
    async fn an_uncited_demotion_to_a_role_the_member_minted_settles() {
        // The uncited-strip gate reads what a grant names, never what resolves: keyed on the
        // latter, refusing the grant brings back the predecessor whose roles admit the named
        // role, which admits the grant, and the fold cycles.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "UncitedDemote", vec!["wss://r".into()], None).await.unwrap();
        let (a, z) = (Keys::generate(), Keys::generate());
        let (rz, r1, rmod) = ("f0".repeat(32), "f1".repeat(32), "f5".repeat(32));
        let mr = Permissions::MANAGE_ROLES;
        publish_role(&relay, &community, &owner, &role_at(&rz, "Z", 1, mr), 1).await;
        publish_role(&relay, &community, &owner, &role_at(&r1, "R1", 2, mr), 1).await;
        publish_grant(&relay, &community, &owner, &z.public_key(), vec![rz.clone()], 1).await;
        publish_grant(&relay, &community, &owner, &a.public_key(), vec![r1.clone()], 1).await;
        publish_role(&relay, &community, &a, &role_at(&rmod, "Mod", 5, mr), 1).await;
        publish_grant_citing(&relay, &community, &z, &a.public_key(), vec![rmod.clone()], 2, None).await;
        let f = fold_authority(&community, &fetch_control(&relay, &community).await, &Floors::default());
        assert!(f.converged, "the fold settles");
        assert_eq!(f.roles.roles_of(&a.public_key().to_hex()).count(), 0);
    }

    #[tokio::test]
    async fn a_link_to_a_sibling_that_lost_the_version_still_binds() {
        // Two siblings stand at v2; the owner's wins it. An edit built on the other one acts on
        // the member as that sibling left them.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Sibling", vec!["wss://r".into()], None).await.unwrap();
        let (a, m) = (Keys::generate(), Keys::generate());
        let member = Keys::generate().public_key();
        let (ra, rsen, rm, rlow, rlower) = ("a1".repeat(32), "a2".repeat(32), "a5".repeat(32), "a9".repeat(32), "aa".repeat(32));
        let mr = Permissions::MANAGE_ROLES;
        publish_role(&relay, &community, &owner, &role_at(&ra, "A", 1, mr), 1).await;
        publish_role(&relay, &community, &owner, &role_at(&rsen, "Senior", 2, 0), 1).await;
        publish_role(&relay, &community, &owner, &role_at(&rm, "M", 5, mr), 1).await;
        publish_role(&relay, &community, &owner, &role_at(&rlow, "Low", 9, 0), 1).await;
        publish_role(&relay, &community, &owner, &role_at(&rlower, "Lower", 10, 0), 1).await;
        publish_grant(&relay, &community, &owner, &a.public_key(), vec![ra.clone()], 1).await;
        publish_grant(&relay, &community, &owner, &m.public_key(), vec![rm.clone()], 1).await;
        let gm = crate::community::v2::derive::grant_locator(community.id(), &member.to_bytes());
        publish_grant(&relay, &community, &owner, &member, vec![rlow.clone()], 1).await;
        let v1 = head_hash_on_relay(&relay, &community, &gm).await;
        let json = |ids: Vec<String>| crate::community::v2::roles::grant_content_json(&MemberGrant { member: member.to_hex(), role_ids: ids }).unwrap();
        publish_fork(&[&relay], &community, &owner, vsk::GRANT, &gm, 2, v1, &json(vec![rlow.clone()]), None).await;
        let b_id = publish_fork(&[&relay], &community, &a, vsk::GRANT, &gm, 2, v1, &json(vec![rsen.clone()]), None).await;
        let b_hash = fetch_control(&relay, &community).await.into_iter().find(|e| e.inner_id == b_id).unwrap().self_hash;
        publish_fork(&[&relay], &community, &m, vsk::GRANT, &gm, 3, Some(b_hash), &json(vec![rlower.clone()]), None).await;
        let f = fold_authority(&community, &fetch_control(&relay, &community).await, &Floors::default());
        assert_eq!(f.roles.highest_position(&member.to_hex()), Some(9), "M can't act on a member A's sibling made senior");
    }

    #[tokio::test]
    async fn a_reader_holding_nothing_never_takes_an_unauthorized_channel_edit() {
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "ColdChan", vec!["wss://r".into()], None).await.unwrap();
        let ch = community.channels[0].id;
        let v1 = head_hash_on_relay(&relay, &community, &ch.0).await;
        let before = community.channel(&ch).unwrap().name.clone();
        publish_fork(&[&relay], &community, &Keys::generate(), vsk::CHANNEL_METADATA, &ch.0, 2, v1, &channel_meta_json("stranger"), None).await;
        let _ = owner;
        let editions = fetch_control(&relay, &community).await;
        let authority = fold_authority(&community, &editions, &Floors::default());
        let fold = apply_control_fold(&community, &editions, &Floors::default(), &authority);
        assert_eq!(fold.updated.as_ref().unwrap_or(&community).channel(&ch).unwrap().name, before);
    }

    #[tokio::test]
    async fn a_step_down_lands_only_on_an_edition_decided_on_evidence() {
        // With the owner's v1 unread, A2's v2 was judged blind (one as a branch of its own,
        // one on a link nobody serves), so B's refused v3 is kept rather than stepped down.
        let (_tmp, _guard, owner) = init_test_db();
        let full = MemoryRelay::new();
        let community = create_community(&full, "Blind", vec!["wss://r".into()], None).await.unwrap();
        let (a2, b) = (Keys::generate(), Keys::generate());
        let (rb, rsen, ra2, rhelp, rlow) = ("b1".repeat(32), "b2".repeat(32), "b3".repeat(32), "b8".repeat(32), "b9".repeat(32));
        let mr = Permissions::MANAGE_ROLES;
        for (id, name, pos, bits) in [(&rb, "B", 1, mr), (&rsen, "Senior", 2, 0), (&ra2, "A2", 3, mr), (&rhelp, "Helper", 8, 0), (&rlow, "Low", 9, 0)] {
            publish_role(&full, &community, &owner, &role_at(id, name, pos, bits), 1).await;
        }
        publish_grant(&full, &community, &owner, &b.public_key(), vec![rb.clone()], 1).await;
        publish_grant(&full, &community, &owner, &a2.public_key(), vec![ra2.clone()], 1).await;
        let (m1, m2) = (Keys::generate().public_key(), Keys::generate().public_key());
        let json = |m: &PublicKey, ids: Vec<String>| crate::community::v2::roles::grant_content_json(&MemberGrant { member: m.to_hex(), role_ids: ids }).unwrap();
        let mut withheld = Vec::new();
        for (m, side) in [(&m1, true), (&m2, false)] {
            let gm = crate::community::v2::derive::grant_locator(community.id(), &m.to_bytes());
            publish_grant(&full, &community, &owner, m, vec![rsen.clone()], 1).await;
            let h1 = head_hash_on_relay(&full, &community, &gm).await;
            withheld.push(h1.unwrap());
            let i2 = publish_fork(&[&full], &community, &a2, vsk::GRANT, &gm, 2, if side { None } else { h1 }, &json(m, vec![rlow.clone()]), None).await;
            let h2 = fetch_control(&full, &community).await.into_iter().find(|e| e.inner_id == i2).unwrap().self_hash;
            publish_fork(&[&full], &community, &b, vsk::GRANT, &gm, 3, Some(h2), &json(m, vec![rlow.clone(), rhelp.clone()]), None).await;
        }
        follow_control(&full, &community).await.unwrap();
        publish_grant(&full, &community, &owner, &b.public_key(), vec![], 2).await;
        let thin = MemoryRelay::new();
        mirror_control_except(&full, &thin, &community, &|e| withheld.contains(&e.self_hash)).await;
        let f = fold_authority(&community, &fetch_control(&thin, &community).await, &load_floors(&community));
        for m in [&m1, &m2] {
            let gm = crate::simd::hex::bytes_to_hex_32(&crate::community::v2::derive::grant_locator(community.id(), &m.to_bytes()));
            let head = f.heads.iter().find(|h| h.entity_hex == gm).map(|h| (h.version, h.rebased));
            assert_eq!(head, Some((3, false)), "B's v3 is kept, not stepped down to a blind v2");
        }
    }

    #[tokio::test]
    async fn a_link_that_skips_a_version_binds_nothing() {
        // A link names the version directly beneath it, so an edit naming v1 past v2 is judged
        // only on what v2 left.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Skip", vec!["wss://r".into()], None).await.unwrap();
        let m = Keys::generate();
        let member = Keys::generate().public_key();
        let (rsen, rm, rlow, rlower) = ("c2".repeat(32), "c5".repeat(32), "c9".repeat(32), "ca".repeat(32));
        publish_role(&relay, &community, &owner, &role_at(&rsen, "Senior", 2, 0), 1).await;
        publish_role(&relay, &community, &owner, &role_at(&rm, "M", 5, Permissions::MANAGE_ROLES), 1).await;
        publish_role(&relay, &community, &owner, &role_at(&rlow, "Low", 9, 0), 1).await;
        publish_role(&relay, &community, &owner, &role_at(&rlower, "Lower", 10, 0), 1).await;
        publish_grant(&relay, &community, &owner, &m.public_key(), vec![rm.clone()], 1).await;
        let gm = crate::community::v2::derive::grant_locator(community.id(), &member.to_bytes());
        publish_grant(&relay, &community, &owner, &member, vec![rsen.clone()], 1).await;
        let v1 = head_hash_on_relay(&relay, &community, &gm).await;
        publish_grant(&relay, &community, &owner, &member, vec![rlow.clone()], 2).await;
        let json = crate::community::v2::roles::grant_content_json(&MemberGrant { member: member.to_hex(), role_ids: vec![rlower.clone()] }).unwrap();
        publish_fork(&[&relay], &community, &m, vsk::GRANT, &gm, 3, v1, &json, None).await;
        let f = fold_authority(&community, &fetch_control(&relay, &community).await, &Floors::default());
        assert_eq!(f.roles.highest_position(&member.to_hex()), Some(10), "M acts on the member v2 left at Low");
    }

    #[tokio::test]
    async fn a_refounding_carries_an_invite_registry_signed_by_its_creator() {
        // Compaction falls back to the floor for entities no fold covers; a re-signed copy of
        // that edition must not take its place.
        let (bed, owner, _m) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "RegistryCopy", bed.relays.clone(), None).await.unwrap();
        mint_public_link(&bed.relay, &community, "https://vectorapp.io", None, None).await.unwrap();
        assert!(community_is_public(&bed.relay, &community).await);
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let reg = crate::community::v2::derive::invite_links_locator(community.id(), &owner.keys.public_key().to_bytes());
        let eds = fetch_control(&bed.relay, &held).await;
        let head = eds.iter().filter(|e| e.entity_id == reg).max_by_key(|e| e.version).unwrap().clone();
        // A copy stamped newer, so a reader taking the first served edition by hash takes it.
        let copier = Keys::generate();
        let ts = now_ms() / 1000 + 100;
        let group = control::ControlPlane::of(&held).write_group().unwrap();
        let rumor = control::build_edition_rumor(copier.public_key(), &head.vsk, &reg, head.version, head.prev_hash.as_ref(), &head.content, ts, None);
        let (wrap, _) = control::seal_control_edition(&rumor, &group, &copier, Timestamp::from_secs(ts)).unwrap();
        bed.relay.publish(&wrap, &held.relays).await.unwrap();
        assert!(load_floors(&held).contains_key(&crate::simd::hex::bytes_to_hex_32(&reg)), "the creator's registry is floored here");
        let refounded = refound_community(&bed.relay, &held, &[]).await.unwrap();
        let carried: Vec<ParsedEdition> = fetch_control(&bed.relay, &refounded).await.into_iter().filter(|e| e.entity_id == reg).collect();
        assert!(!carried.is_empty() && carried.iter().all(|e| e.author == owner.keys.public_key()), "the creator's registry is carried, not the copy");
    }

    fn role_v2(id: &str, name: &str, rank: &str, bits: u64) -> Role {
        Role { role_id: id.into(), name: name.into(), position: u32::MAX, permissions: Permissions(bits), scope: RoleScope::Server, color: 0, rank: Some(rank.into()), display: false, mentionable: false, extra: Default::default() }
    }

    /// Publish a vsk-13 edition with `content` at `eid`, chained to the relay's head there.
    async fn publish_v2(relay: &MemoryRelay, community: &CommunityV2, signer: &Keys, eid: &[u8; 32], content: &str, version: u64) {
        let group = control::ControlPlane::of(community).write_group().unwrap();
        let prev = head_hash_on_relay(relay, community, eid).await;
        let cite = cite_on_relay(relay, community, signer).await;
        let binding = Some(crate::community::v2::derive::edition_binding(community.id()));
        let rumor = control::build_edition_rumor_bound(signer.public_key(), vsk::ROLE_V2, eid, version, prev.as_ref(), content, 1_000, cite.as_ref(), binding);
        let (wrap, _) = control::seal_control_edition(&rumor, &group, signer, Timestamp::from_secs(1_000)).unwrap();
        relay.publish(&wrap, &community.relays).await.unwrap();
    }

    async fn publish_role_v2(relay: &MemoryRelay, community: &CommunityV2, signer: &Keys, role: &Role, version: u64) {
        let content = crate::community::v2::roles::role_v2_content_json(role).unwrap();
        publish_v2(relay, community, signer, &eid_of(&role.role_id), &content, version).await;
    }

    async fn publish_everyone(relay: &MemoryRelay, community: &CommunityV2, signer: &Keys, bits: u64, version: u64) {
        let eid = crate::community::v2::derive::everyone_locator(community.id());
        publish_v2(relay, community, signer, &eid, &crate::community::v2::roles::everyone_content_json(bits), version).await;
    }

    #[tokio::test]
    async fn roles_v2_activate_when_the_owner_publishes_everyone() {
        // Before @everyone, vsk 13 is noise and the legacy roster stands; after, Roles fold from
        // vsk 13 alone and a vsk-1 Role is history.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Activate", vec!["wss://r".into()], None).await.unwrap();
        let m = Keys::generate().public_key();
        let (legacy, fresh) = ("a1".repeat(32), "a2".repeat(32));
        publish_role(&relay, &community, &owner, &role_at(&legacy, "Legacy", 3, Permissions::KICK), 1).await;
        publish_role_v2(&relay, &community, &owner, &role_v2(&fresh, "Fresh", "V", Permissions::KICK), 1).await;
        publish_grant(&relay, &community, &owner, &m, vec![legacy.clone(), fresh.clone()], 1).await;
        let before = fold_authority(&community, &fetch_control(&relay, &community).await, &Floors::default());
        assert!(before.roles.role(&legacy).is_some() && before.roles.role(&fresh).is_none() && before.roles.everyone.is_none());

        // A non-owner's @everyone activates nothing.
        let stranger = Keys::generate();
        publish_everyone(&relay, &community, &stranger, crate::community::v2::roles::EVERYONE_DEFAULT, 1).await;
        let still = fold_authority(&community, &fetch_control(&relay, &community).await, &Floors::default());
        assert!(still.roles.role(&legacy).is_some() && still.roles.everyone.is_none());

        publish_everyone(&relay, &community, &owner, crate::community::v2::roles::EVERYONE_DEFAULT | Permissions::CREATE_INVITE, 2).await;
        let after = fold_authority(&community, &fetch_control(&relay, &community).await, &Floors::default());
        assert!(after.converged);
        assert!(after.roles.role(&legacy).is_none(), "vsk 1 is history");
        assert!(after.roles.role(&fresh).is_some(), "vsk 13 folds");
        assert_eq!(after.roles.everyone.map(|p| p.0), Some(crate::community::v2::roles::EVERYONE_DEFAULT | Permissions::CREATE_INVITE));
        assert!(after.roles.effective_permissions(&Keys::generate().public_key().to_hex()).contains(Permissions::CREATE_INVITE), "every member holds @everyone");
        assert_eq!(after.roles.roles_of(&m.to_hex()).count(), 1, "the grant resolves against vsk 13");
        // Once seen, activation outlives the edition that made it: a relay dropping @everyone
        // can't flip a tracker back to the legacy roster.
        follow_control(&relay, &community).await.unwrap();
        let thin = MemoryRelay::new();
        let everyone_eid = crate::community::v2::derive::everyone_locator(community.id());
        mirror_control_except(&relay, &thin, &community, &|e| e.entity_id == everyone_eid).await;
        let tracked = fold_authority(&community, &fetch_control(&thin, &community).await, &load_floors(&community));
        assert!(tracked.roles.role(&legacy).is_none() && tracked.roles.role(&fresh).is_some(), "still Roles v2");
    }

    #[tokio::test]
    async fn legacy_ranks_bind_nothing_after_activation() {
        // An admin carries a legacy Role that sat at position 1 across to vsk 13. Legacy
        // positions mean nothing once Roles v2 is active, so only vsk-13 ranks judge the edit.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "LegacyRank", vec!["wss://r".into()], None).await.unwrap();
        let admin = Keys::generate();
        let (radm, rr) = ("f1".repeat(32), "f2".repeat(32));
        publish_role(&relay, &community, &owner, &role_at(&rr, "R", 1, 0), 1).await;
        // A device holding the legacy edition reads the same.
        follow_control(&relay, &community).await.unwrap();
        publish_everyone(&relay, &community, &owner, 0, 1).await;
        publish_role_v2(&relay, &community, &owner, &role_v2(&radm, "Admin", "B", Permissions::MANAGE_ROLES), 1).await;
        publish_grant(&relay, &community, &owner, &admin.public_key(), vec![radm.clone()], 1).await;
        publish_role_v2(&relay, &community, &admin, &role_v2(&rr, "R carried", "V", 0), 2).await;
        let editions = fetch_control(&relay, &community).await;
        for floors in [Floors::default(), load_floors(&community)] {
            let f = fold_authority(&community, &editions, &floors);
            assert_eq!(f.roles.role(&rr).map(|r| r.name.as_str()), Some("R carried"));
        }
    }

    #[tokio::test]
    async fn a_floor_steps_down_to_a_deletion_it_learns_of_late() {
        // A device that took the owner's v3 before it saw the deletion at v2 beneath it: the
        // deletion stands, and the floor moves down to it.
        let (_tmp, _guard, owner) = init_test_db();
        let full = MemoryRelay::new();
        let community = create_community(&full, "LateDelete", vec!["wss://r".into()], None).await.unwrap();
        publish_everyone(&full, &community, &owner, 0, 1).await;
        let rr = "f6".repeat(32);
        publish_role_v2(&full, &community, &owner, &role_v2(&rr, "R", "V", 0), 1).await;
        publish_v2(&full, &community, &owner, &eid_of(&rr), &crate::community::v2::roles::role_v2_deleted_json(&rr), 2).await;
        let d = head_hash_on_relay(&full, &community, &eid_of(&rr)).await.unwrap();
        publish_role_v2(&full, &community, &owner, &role_v2(&rr, "R again", "V", 0), 3).await;
        let thin = MemoryRelay::new();
        mirror_control_except(&full, &thin, &community, &|e| e.self_hash == d).await;
        follow_control(&thin, &community).await.unwrap();
        assert_eq!(floor_of(&community, &eid_of(&rr)).0, 3);
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        follow_control(&full, &held).await.unwrap();
        assert_eq!(floor_of(&community, &eid_of(&rr)).0, 2, "the floor moves down to the deletion");
        let cached = crate::db::community::get_community_roles(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap();
        assert!(cached.role(&rr).is_none());
    }

    #[tokio::test]
    async fn rank_keys_order_authority_and_equal_keys_are_peers() {
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Ranks", vec!["wss://r".into()], None).await.unwrap();
        publish_everyone(&relay, &community, &owner, 0, 1).await;
        let (hi, lo, peer) = (Keys::generate(), Keys::generate(), Keys::generate());
        let mr = Permissions::MANAGE_ROLES;
        let (rhi, rlo, rpeer, rtarget) = ("b1".repeat(32), "b2".repeat(32), "b3".repeat(32), "b4".repeat(32));
        publish_role_v2(&relay, &community, &owner, &role_v2(&rhi, "Hi", "B", mr), 1).await;
        publish_role_v2(&relay, &community, &owner, &role_v2(&rlo, "Lo", "V", mr), 1).await;
        publish_role_v2(&relay, &community, &owner, &role_v2(&rpeer, "Peer", "V", mr), 1).await;
        publish_role_v2(&relay, &community, &owner, &role_v2(&rtarget, "Target", "VV", 0), 1).await;
        for (k, r) in [(&hi, &rhi), (&lo, &rlo), (&peer, &rpeer)] {
            publish_grant(&relay, &community, &owner, &k.public_key(), vec![r.clone()], 1).await;
        }
        // Lo renames the role beneath it, and tries to rename Hi's and its peer's.
        publish_role_v2(&relay, &community, &lo, &role_v2(&rtarget, "Target by Lo", "VV", 0), 2).await;
        publish_role_v2(&relay, &community, &lo, &role_v2(&rhi, "Hi by Lo", "B", mr), 2).await;
        publish_role_v2(&relay, &community, &lo, &role_v2(&rpeer, "Peer by Lo", "V", mr), 2).await;
        let f = fold_authority(&community, &fetch_control(&relay, &community).await, &Floors::default());
        let name = |id: &String| f.roles.role(id).map(|r| r.name.clone());
        assert_eq!(name(&rtarget).as_deref(), Some("Target by Lo"), "a lower key is beneath");
        assert_eq!(name(&rhi).as_deref(), Some("Hi"), "a higher key isn't");
        assert_eq!(name(&rpeer).as_deref(), Some("Peer"), "equal keys are peers");
        let (p_hi, p_lo, p_peer) = (f.roles.role(&rhi).unwrap().position, f.roles.role(&rlo).unwrap().position, f.roles.role(&rpeer).unwrap().position);
        assert!(p_hi < p_lo && p_lo == p_peer, "positions follow the keys");
    }

    #[tokio::test]
    async fn a_migrated_role_continues_its_legacy_chain() {
        // The owner carries a vsk-1 Role across as vsk 13 on top of its last legacy edition: a
        // tracker holding that edition advances, and the role's grants keep resolving.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Migrate", vec!["wss://r".into()], None).await.unwrap();
        let (admin, m) = (Keys::generate(), Keys::generate().public_key());
        let (radm, rr) = ("c1".repeat(32), "c5".repeat(32));
        publish_role(&relay, &community, &owner, &role_at(&radm, "Admin", 1, Permissions::MANAGE_ROLES | Permissions::KICK), 1).await;
        publish_role(&relay, &community, &owner, &role_at(&rr, "R", 5, Permissions::KICK), 1).await;
        publish_role(&relay, &community, &owner, &role_at(&rr, "R renamed", 5, Permissions::KICK), 2).await;
        publish_grant(&relay, &community, &owner, &admin.public_key(), vec![radm.clone()], 1).await;
        publish_grant(&relay, &community, &owner, &m, vec![rr.clone()], 1).await;
        follow_control(&relay, &community).await.unwrap();
        assert_eq!(floor_of(&community, &eid_of(&rr)).0, 2);

        publish_role_v2(&relay, &community, &owner, &role_v2(&radm, "Admin", "B", Permissions::MANAGE_ROLES | Permissions::KICK), 2).await;
        publish_role_v2(&relay, &community, &owner, &role_v2(&rr, "R renamed", "V", Permissions::KICK), 3).await;
        publish_everyone(&relay, &community, &owner, crate::community::v2::roles::EVERYONE_DEFAULT, 1).await;
        // The migrated admin edits on top.
        publish_role_v2(&relay, &community, &admin, &role_v2(&rr, "R by admin", "V", Permissions::KICK), 4).await;
        let editions = fetch_control(&relay, &community).await;
        for floors in [load_floors(&community), Floors::default()] {
            let f = fold_authority(&community, &editions, &floors);
            assert!(f.converged);
            assert_eq!(f.roles.role(&rr).map(|r| r.name.as_str()), Some("R by admin"));
            assert_eq!(f.roles.roles_of(&m.to_hex()).count(), 1, "the grant keeps resolving");
        }
    }

    #[tokio::test]
    async fn a_deleted_role_is_gone_whatever_comes_after() {
        // Deletion is terminal over the authorized chain; it takes authority over the rank the
        // Role stood at, so someone beneath it can't delete it.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Delete", vec!["wss://r".into()], None).await.unwrap();
        publish_everyone(&relay, &community, &owner, 0, 1).await;
        let (adm, low) = (Keys::generate(), Keys::generate());
        let mr = Permissions::MANAGE_ROLES;
        let (radm, rlow, gone, kept) = ("d1".repeat(32), "d9".repeat(32), "d5".repeat(32), "d6".repeat(32));
        publish_role_v2(&relay, &community, &owner, &role_v2(&radm, "Adm", "B", mr), 1).await;
        publish_role_v2(&relay, &community, &owner, &role_v2(&rlow, "Low", "y", mr), 1).await;
        publish_grant(&relay, &community, &owner, &adm.public_key(), vec![radm.clone()], 1).await;
        publish_grant(&relay, &community, &owner, &low.public_key(), vec![rlow.clone()], 1).await;
        let m = Keys::generate().public_key();
        for id in [&gone, &kept] {
            publish_role_v2(&relay, &community, &owner, &role_v2(id, "R", "V", 0), 1).await;
        }
        publish_grant(&relay, &community, &owner, &m, vec![gone.clone(), kept.clone()], 1).await;
        let del = |id: &str| crate::community::v2::roles::role_v2_deleted_json(id);
        publish_v2(&relay, &community, &adm, &eid_of(&gone), &del(&gone), 2).await;
        publish_role_v2(&relay, &community, &owner, &role_v2(&gone, "R again", "V", 0), 3).await;
        publish_v2(&relay, &community, &low, &eid_of(&kept), &del(&kept), 2).await;
        let f = fold_authority(&community, &fetch_control(&relay, &community).await, &Floors::default());
        assert!(f.roles.role(&gone).is_none(), "deleted, and the later edition doesn't revive it");
        assert!(f.heads.iter().any(|h| h.entity_hex == gone && h.version == 2), "the deletion is the head");
        assert!(f.roles.role(&kept).is_some(), "a Role above its deleter stands");
        assert_eq!(f.roles.roles_of(&m.to_hex()).count(), 1, "the grant naming the deleted Role confers the rest");
    }

    #[tokio::test]
    async fn everyone_carries_only_bits_its_editor_holds_and_no_grant_names_it() {
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Everyone", vec!["wss://r".into()], None).await.unwrap();
        let base = crate::community::v2::roles::EVERYONE_DEFAULT;
        publish_everyone(&relay, &community, &owner, base, 1).await;
        let (full, partial) = (Keys::generate(), Keys::generate());
        let (rfull, rpart) = ("e1".repeat(32), "e2".repeat(32));
        publish_role_v2(&relay, &community, &owner, &role_v2(&rfull, "Full", "B", Permissions::MANAGE_ROLES | base | Permissions::PIN_MESSAGES), 1).await;
        publish_role_v2(&relay, &community, &owner, &role_v2(&rpart, "Partial", "C", Permissions::MANAGE_ROLES | Permissions::VIEW_CHANNEL), 1).await;
        publish_grant(&relay, &community, &owner, &full.public_key(), vec![rfull.clone()], 1).await;
        publish_grant(&relay, &community, &owner, &partial.public_key(), vec![rpart.clone()], 1).await;
        // Partial can't carry bits it lacks; Full can add a bit it holds.
        publish_everyone(&relay, &community, &partial, base & !Permissions::VIDEO, 2).await;
        let f = fold_authority(&community, &fetch_control(&relay, &community).await, &Floors::default());
        assert_eq!(f.roles.everyone.map(|p| p.0), Some(base), "the partial manager's edit carries bits it lacks");
        publish_everyone(&relay, &community, &full, base | Permissions::PIN_MESSAGES, 2).await;
        let g = fold_authority(&community, &fetch_control(&relay, &community).await, &Floors::default());
        assert_eq!(g.roles.everyone.map(|p| p.0), Some(base | Permissions::PIN_MESSAGES));
        // A grant naming @everyone's coordinate confers nothing.
        let everyone_hex = crate::simd::hex::bytes_to_hex_32(&crate::community::v2::derive::everyone_locator(community.id()));
        let m = Keys::generate().public_key();
        publish_grant(&relay, &community, &owner, &m, vec![everyone_hex], 1).await;
        let h = fold_authority(&community, &fetch_control(&relay, &community).await, &Floors::default());
        assert_eq!(h.roles.roles_of(&m.to_hex()).count(), 0);
        assert!(!h.roles.roles.iter().any(|r| r.name == "@everyone"), "@everyone is no Role in the list");
    }

    #[tokio::test]
    async fn the_owner_carries_a_legacy_roster_across_to_roles_v2() {
        // Order, names, colours, bits and peers survive; Grants keep resolving; nothing reads
        // vsk 13 until @everyone lands last; and a channel access role becomes overwrites.
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Carry", bed.relays.clone(), None).await.unwrap();
        let mr = Permissions::MANAGE_ROLES;
        let (radm, rmod, rpeer, rlow) = ("a1".repeat(32), "a3".repeat(32), "a4".repeat(32), "a9".repeat(32));
        publish_role(&bed.relay, &community, &owner.keys, &role_at(&radm, "Admin", 1, mr | Permissions::KICK), 1).await;
        publish_role(&bed.relay, &community, &owner.keys, &role_at(&rmod, "Mod", 3, Permissions::KICK), 1).await;
        publish_role(&bed.relay, &community, &owner.keys, &role_at(&rpeer, "Peer", 3, Permissions::KICK), 1).await;
        publish_role(&bed.relay, &community, &owner.keys, &role_at(&rlow, "Low", 9, 0), 1).await;
        publish_grant(&bed.relay, &community, &owner.keys, &member.keys.public_key(), vec![rmod.clone(), rlow.clone()], 1).await;
        follow_control(&bed.relay, &community).await.unwrap();
        let before = fetch_authority(&bed.relay, &community).await;
        assert!(!before.activated);

        let carried = activate_roles_v2(&bed.relay, &community, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
        assert_eq!(carried, 4);
        let after = fetch_authority(&bed.relay, &community).await;
        assert!(after.activated);
        assert_eq!(after.roles.everyone.map(|p| p.0), Some(crate::community::v2::roles::EVERYONE_DEFAULT));
        let pos = |id: &str| after.roles.role(id).map(|r| r.position).unwrap();
        assert!(pos(&radm) < pos(&rmod) && pos(&rmod) == pos(&rpeer) && pos(&rpeer) < pos(&rlow), "order and peers kept");
        for id in [&radm, &rmod, &rpeer, &rlow] {
            let (b, a) = (before.roles.role(id).unwrap(), after.roles.role(id).unwrap());
            // A managing Role gains the channel basics, so it can keep managing channel access.
            let gained = if b.permissions.contains(Permissions::MANAGE_ROLES) { crate::community::v2::roles::EVERYONE_DEFAULT } else { 0 };
            assert_eq!((&b.name, b.permissions.0 | gained, b.color), (&a.name, a.permissions.0, a.color));
            assert!(a.rank.is_some());
            assert_eq!(a.display, b.permissions.is_management(), "managing roles stay apart in the member list, as they were");
        }
        assert_eq!(after.roles.roles_of(&member.keys.public_key().to_hex()).count(), 2, "grants keep resolving");
        assert!(activate_roles_v2(&bed.relay, &community, 0).await.is_err(), "once is enough");

        let other = create_community(&bed.relay, "Scoped", bed.relays.clone(), None).await.unwrap();
        let scoped = Role { role_id: "b1".repeat(32), name: "Access".into(), position: 5, permissions: Permissions(0), scope: RoleScope::Channel(crate::simd::hex::bytes_to_hex_32(&other.channels[0].id.0)), color: 0, rank: None, display: false, mentionable: false, extra: Default::default() };
        publish_role(&bed.relay, &other, &owner.keys, &scoped, 1).await;
        follow_control(&bed.relay, &other).await.unwrap();
        activate_roles_v2(&bed.relay, &other, 0).await.unwrap();
        let moved = fetch_authority(&bed.relay, &other).await;
        let access = moved.roles.role(&scoped.role_id).unwrap();
        assert_eq!(access.scope, RoleScope::Server, "an access role carries across unscoped");
        assert_eq!(moved.roles.overwrites.len(), 1, "its private Channel lets the role through");
    }

    #[tokio::test]
    async fn the_roles_v2_editor_refuses_exactly_what_readers_would_drop() {
        let (bed, owner, mgr) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "V2Editor", bed.relays.clone(), None).await.unwrap();
        publish_everyone(&bed.relay, &community, &owner.keys, Permissions::VIEW_CHANNEL, 1).await;
        let mr = Permissions::MANAGE_ROLES;
        let (rtop, rmgr) = ("c1".repeat(32), "c2".repeat(32));
        publish_role_v2(&bed.relay, &community, &owner.keys, &role_v2(&rtop, "Top", "B", Permissions::BAN), 1).await;
        publish_role_v2(&bed.relay, &community, &owner.keys, &role_v2(&rmgr, "Mgr", "F", mr | Permissions::KICK | Permissions::VIEW_CHANNEL), 1).await;
        publish_grant(&bed.relay, &community, &owner.keys, &mgr.keys.public_key(), vec![rmgr.clone()], 1).await;
        follow_control(&bed.relay, &community).await.unwrap();

        bed.swap_to(&mgr);
        crate::db::community::save_community_v2(&community).unwrap();
        follow_control(&bed.relay, &community).await.unwrap();
        let a = create_role_v2(&bed.relay, &community, "A", 0, Permissions::KICK).await.unwrap();
        let b = create_role_v2(&bed.relay, &community, "B", 0, 0).await.unwrap();
        assert!(create_role_v2(&bed.relay, &community, "Banner", 0, Permissions::BAN).await.unwrap_err().contains("don't hold"));
        let v = fetch_authority(&bed.relay, &community).await;
        let pos = |v: &AuthorityView, id: &str| v.roles.role(id).map(|r| r.position).unwrap();
        assert!(pos(&v, &rmgr) < pos(&v, &a) && pos(&v, &a) < pos(&v, &b), "new roles go to the bottom, in order");

        // Moving B above A is one edition, on B alone.
        move_role_v2(&bed.relay, &community, &b, 2).await.unwrap();
        let w = fetch_authority(&bed.relay, &community).await;
        assert!(pos(&w, &b) < pos(&w, &a) && pos(&w, &rmgr) < pos(&w, &b));
        assert_eq!(w.roles.role(&a).unwrap().rank, v.roles.role(&a).unwrap().rank, "A wasn't touched");
        // Not above itself, and not the role above it.
        assert!(move_role_v2(&bed.relay, &community, &b, 0).await.is_err());
        assert!(move_role_v2(&bed.relay, &community, &rtop, 3).await.is_err());
        assert!(edit_role_v2(&bed.relay, &community, &rtop, "Top!", 0, Permissions::BAN, false, false).await.is_err());
        // @everyone carries only what the manager holds.
        assert!(set_everyone(&bed.relay, &community, Permissions::VIEW_CHANNEL | Permissions::SEND_MESSAGES).await.unwrap_err().contains("don't hold"));
        set_everyone(&bed.relay, &community, Permissions::VIEW_CHANNEL | Permissions::KICK).await.unwrap();
        // Delete beneath, never above.
        delete_role_v2(&bed.relay, &community, &a).await.unwrap();
        assert!(delete_role_v2(&bed.relay, &community, &rtop).await.is_err());
        let x = fetch_authority(&bed.relay, &community).await;
        assert!(x.roles.role(&a).is_none() && x.roles.role(&rtop).is_some());
        assert_eq!(x.roles.everyone.map(|p| p.0), Some(Permissions::VIEW_CHANNEL | Permissions::KICK));
        edit_role_v2(&bed.relay, &community, &b, "B shown", 7, 0, true, true).await.unwrap();
        let y = fetch_authority(&bed.relay, &community).await;
        let rb = y.roles.role(&b).unwrap();
        assert!(rb.display && rb.mentionable && rb.name == "B shown" && rb.color == 7);
    }

    #[tokio::test]
    async fn a_marked_edition_is_its_signers_and_its_communitys_alone() {
        // SC-6: a marked edition's hash covers its signer, so a re-signed copy is a different
        // edition; an unmarked one keeps the content hash. A marked edition re-wrapped into
        // another Community is refused there.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let a = create_community(&relay, "A", vec!["wss://r".into()], None).await.unwrap();
        let b = create_community(&relay, "B", vec!["wss://r".into()], None).await.unwrap();
        let rid = eid_of(&"a1".repeat(32));
        let content = crate::community::v2::roles::role_v2_content_json(&role_v2(&"a1".repeat(32), "R", "V", 0)).unwrap();
        let bind_a = Some(crate::community::v2::derive::edition_binding(a.id()));
        let copier = Keys::generate();
        let seal = |c: &CommunityV2, signer: &Keys, binding: Option<[u8; 32]>| {
            let group = control::ControlPlane::of(c).write_group().unwrap();
            let rumor = control::build_edition_rumor_bound(signer.public_key(), vsk::ROLE_V2, &rid, 1, None, &content, 1_000, None, binding);
            control::seal_control_edition(&rumor, &group, signer, Timestamp::from_secs(1_000)).unwrap().0
        };
        let (genuine, _) = control::ControlPlane::of(&a).open(&seal(&a, &owner, bind_a)).unwrap();
        let (copy, _) = control::ControlPlane::of(&a).open(&seal(&a, &copier, bind_a)).unwrap();
        assert_ne!(genuine.self_hash, copy.self_hash, "a copy under another key is another edition");
        let (plain, _) = control::ControlPlane::of(&a).open(&seal(&a, &owner, None)).unwrap();
        let (plain_copy, _) = control::ControlPlane::of(&a).open(&seal(&a, &copier, None)).unwrap();
        assert_eq!(plain.self_hash, plain_copy.self_hash, "unmarked editions keep the content hash");
        // Bound to A, wrapped at B: refused at B.
        let mut wrong = a.clone();
        wrong.community_root = b.community_root;
        wrong.control_pk = b.control_pk;
        wrong.control_root = b.control_root;
        let foreign = {
            let group = control::ControlPlane::of(&b).write_group().unwrap();
            let rumor = control::build_edition_rumor_bound(owner.public_key(), vsk::ROLE_V2, &rid, 1, None, &content, 1_000, None, bind_a);
            control::seal_control_edition(&rumor, &group, &owner, Timestamp::from_secs(1_000)).unwrap().0
        };
        assert!(control::ControlPlane::of(&b).open(&foreign).is_err(), "A's edition is no edition of B");
        let _ = wrong;
    }

    #[tokio::test]
    async fn on_roles_v2_every_edition_is_marked_and_an_unmarked_role_is_none() {
        let (bed, owner, _m) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Marked", bed.relays.clone(), None).await.unwrap();
        activate_roles_v2(&bed.relay, &community, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
        follow_control(&bed.relay, &community).await.unwrap();
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let ch = held.channels[0].id;
        edit_channel_metadata(&bed.relay, &held, &ch, &control::ChannelMetadata { name: "renamed".into(), private: false, ..Default::default() }).await.unwrap();
        let eds = fetch_control(&bed.relay, &held).await;
        let rename = eds.iter().filter(|e| e.entity_id == ch.0).max_by_key(|e| e.version).unwrap();
        assert!(rename.binding.is_some(), "a channel edit after activation is marked");
        assert!(eds.iter().filter(|e| e.vsk == vsk::ROLE_V2).all(|e| e.binding.is_some()));
        // An unmarked vsk-13 Role from a writer that skipped the mark folds nothing.
        let rid = "b1".repeat(32);
        let content = crate::community::v2::roles::role_v2_content_json(&role_v2(&rid, "Unmarked", "x", 0)).unwrap();
        let group = control::ControlPlane::of(&held).write_group().unwrap();
        let rumor = control::build_edition_rumor(owner.keys.public_key(), vsk::ROLE_V2, &eid_of(&rid), 1, None, &content, 1_000, None);
        let (wrap, _) = control::seal_control_edition(&rumor, &group, &owner.keys, Timestamp::from_secs(1_000)).unwrap();
        bed.relay.publish(&wrap, &held.relays).await.unwrap();
        let f = fold_authority(&held, &fetch_control(&bed.relay, &held).await, &load_floors(&held));
        assert!(f.roles.role(&rid).is_none());
    }

    #[tokio::test]
    async fn a_backdated_deletion_never_reaches_above_its_signer() {
        // A deletion acts on the Role at every rank it holds from the deletion on: published as
        // an early version beneath a Role's later life, it doesn't reach above its signer.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Backdate", vec!["wss://r".into()], None).await.unwrap();
        let m = Keys::generate();
        let mr = Permissions::MANAGE_ROLES;
        let (rtop, rm, rlegacy) = ("a1".repeat(32), "a5".repeat(32), "a7".repeat(32));
        // A legacy Role carried across at the top, and a v2 Role moved to the top by the owner.
        publish_role(&relay, &community, &owner, &role_at(&rlegacy, "Legacy", 2, 0), 1).await;
        publish_role(&relay, &community, &owner, &role_at(&rlegacy, "Legacy", 2, 0), 2).await;
        publish_everyone(&relay, &community, &owner, 0, 1).await;
        publish_role_v2(&relay, &community, &owner, &role_v2(&rlegacy, "Legacy", "1", 0), 3).await;
        publish_role_v2(&relay, &community, &owner, &role_v2(&rtop, "Top", "z", 0), 1).await;
        publish_role_v2(&relay, &community, &owner, &role_v2(&rtop, "Top", "2", 0), 2).await;
        publish_role_v2(&relay, &community, &owner, &role_v2(&rm, "M", "V", mr), 1).await;
        publish_grant(&relay, &community, &owner, &m.public_key(), vec![rm.clone()], 1).await;
        let del = |id: &str| crate::community::v2::roles::role_v2_deleted_json(id);
        // Each deletion is a genesis, beneath the Role's whole later life.
        let group = control::ControlPlane::of(&community).write_group().unwrap();
        for id in [&rtop, &rlegacy] {
            let rumor = control::build_edition_rumor_bound(m.public_key(), vsk::ROLE_V2, &eid_of(id), 1, None, &del(id), 9_000, cite_on_relay(&relay, &community, &m).await.as_ref(), Some(crate::community::v2::derive::edition_binding(community.id())));
            let (wrap, _) = control::seal_control_edition(&rumor, &group, &m, Timestamp::from_secs(9_000)).unwrap();
            relay.publish(&wrap, &community.relays).await.unwrap();
        }
        let f = fold_authority(&community, &fetch_control(&relay, &community).await, &Floors::default());
        assert!(f.roles.role(&rtop).is_some(), "M can't delete the Role the owner moved above it");
        assert!(f.roles.role(&rlegacy).is_some(), "nor the one carried across above it");
    }

    #[tokio::test]
    async fn only_everyone_activates_and_nothing_squats_its_coordinate() {
        // A manager's legacy Role or channel at @everyone's coordinate floors nothing there, so
        // no tracker reads the Community as Roles v2 before the owner moves it.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Squat2", vec!["wss://r".into()], None).await.unwrap();
        let staff = Keys::generate();
        let rs = "b1".repeat(32);
        publish_role(&relay, &community, &owner, &role_at(&rs, "Staff", 1, Permissions::MANAGE_ROLES | Permissions::MANAGE_CHANNELS), 1).await;
        publish_grant(&relay, &community, &owner, &staff.public_key(), vec![rs.clone()], 1).await;
        let everyone_hex = crate::simd::hex::bytes_to_hex_32(&crate::community::v2::derive::everyone_locator(community.id()));
        // Each squat on its own: either one alone would floor the coordinate.
        let other = create_community(&relay, "Squat3", vec!["wss://r".into()], None).await.unwrap();
        publish_role(&relay, &other, &owner, &role_at(&rs, "Staff", 1, Permissions::MANAGE_ROLES | Permissions::MANAGE_CHANNELS), 1).await;
        publish_grant(&relay, &other, &owner, &staff.public_key(), vec![rs.clone()], 1).await;
        let other_everyone = crate::simd::hex::bytes_to_hex_32(&crate::community::v2::derive::everyone_locator(other.id()));
        publish_role(&relay, &community, &staff, &role_at(&everyone_hex, "Squat", 5, 0), 1).await;
        publish_fork(&[&relay], &other, &staff, vsk::CHANNEL_METADATA, &eid_of(&other_everyone), 1, None, &channel_meta_json("squat"), None).await;
        for (c, e) in [(&community, &everyone_hex), (&other, &other_everyone)] {
            follow_control(&relay, c).await.unwrap();
            assert!(!load_floors(c).contains_key(e), "nothing floors @everyone's coordinate");
            let held = crate::db::community::load_community_v2(c.id()).unwrap().unwrap();
            let a = fold_authority(&held, &fetch_control(&relay, &held).await, &load_floors(&held));
            assert!(!a.activated && a.roles.role(&rs).is_some());
        }
    }

    #[tokio::test]
    async fn roles_v2_survives_a_refounding_after_an_admin_edits_everyone() {
        // Compaction carries @everyone's head, here an admin's: a reader at the new epoch
        // still folds Roles v2, since activation reads the head the vsk-13 fold admits.
        let (bed, owner, _m) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Survive", bed.relays.clone(), None).await.unwrap();
        let admin = Keys::generate();
        let ra = "c1".repeat(32);
        publish_everyone(&bed.relay, &community, &owner.keys, Permissions::VIEW_CHANNEL, 1).await;
        publish_role_v2(&bed.relay, &community, &owner.keys, &role_v2(&ra, "Admin", "B", Permissions::MANAGE_ROLES | Permissions::VIEW_CHANNEL | Permissions::SEND_MESSAGES | Permissions::BAN), 1).await;
        publish_grant(&bed.relay, &community, &owner.keys, &admin.public_key(), vec![ra.clone()], 1).await;
        publish_everyone(&bed.relay, &community, &admin, Permissions::VIEW_CHANNEL | Permissions::SEND_MESSAGES, 2).await;
        follow_control(&bed.relay, &community).await.unwrap();
        let refounded = refound_community(&bed.relay, &community, &[]).await.unwrap();
        let fresh = fold_authority(&refounded, &fetch_control(&bed.relay, &refounded).await, &Floors::default());
        assert!(fresh.activated, "still Roles v2 at the new epoch");
        assert!(fresh.roles.role(&ra).is_some() && fresh.roles.is_admin(&admin.public_key().to_hex()));
    }

    #[tokio::test]
    async fn a_kept_legacy_head_stands_for_nothing_after_activation() {
        // A device holding a legacy Role whose migration it can't read keeps that edition as the
        // head, but a vsk-1 Role confers nothing once Roles v2 is active.
        let (_tmp, _guard, owner) = init_test_db();
        let full = MemoryRelay::new();
        let community = create_community(&full, "KeptLegacy", vec!["wss://r".into()], None).await.unwrap();
        let m = Keys::generate().public_key();
        let rr = "d3".repeat(32);
        publish_role(&full, &community, &owner, &role_at(&rr, "Legacy", 3, Permissions::BAN), 1).await;
        publish_role(&full, &community, &owner, &role_at(&rr, "Legacy", 3, Permissions::BAN), 2).await;
        publish_grant(&full, &community, &owner, &m, vec![rr.clone()], 1).await;
        follow_control(&full, &community).await.unwrap();
        publish_role_v2(&full, &community, &owner, &role_v2(&rr, "Legacy", "V", Permissions::BAN), 3).await;
        let migrated = head_hash_on_relay(&full, &community, &eid_of(&rr)).await.unwrap();
        publish_everyone(&full, &community, &owner, 0, 1).await;
        let thin = MemoryRelay::new();
        mirror_control_except(&full, &thin, &community, &|e| e.self_hash == migrated).await;
        let a = fold_authority(&community, &fetch_control(&thin, &community).await, &load_floors(&community));
        assert!(a.activated && a.carried.contains(&rr), "kept, with nothing proven to step down to");
        assert!(a.roles.role(&rr).is_none() && !a.roles.has_permission(&m.to_hex(), Permissions::BAN), "the legacy edition confers nothing");
    }

    #[tokio::test]
    async fn everyones_bits_author_no_banlist() {
        // Removals from a banlist aren't checked by rank, so who may author one is read from
        // Roles alone: @everyone holding BAN doesn't let any member lift every ban.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "EveryoneBan", vec!["wss://r".into()], None).await.unwrap();
        publish_everyone(&relay, &community, &owner, Permissions::BAN, 1).await;
        let x = Keys::generate().public_key().to_hex();
        publish_banlist(&relay, &community, &owner, &[x.clone()], 1).await;
        let member = Keys::generate();
        let rc = "e7".repeat(32);
        publish_role_v2(&relay, &community, &owner, &role_v2(&rc, "Cosmetic", "V", 0), 1).await;
        publish_grant(&relay, &community, &owner, &member.public_key(), vec![rc.clone()], 1).await;
        publish_banlist(&relay, &community, &member, &[], 2).await;
        let f = fold_authority(&community, &fetch_control(&relay, &community).await, &Floors::default());
        assert!(f.banned.contains(&x), "a member without BAN in a Role unbans nobody");
    }

    #[tokio::test]
    async fn an_uncited_grant_naming_only_everyone_is_a_strip() {
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "UncitedEveryone", vec!["wss://r".into()], None).await.unwrap();
        publish_everyone(&relay, &community, &owner, 0, 1).await;
        let mgr = Keys::generate();
        let m = Keys::generate().public_key();
        let (rmgr, rlow) = ("e5".repeat(32), "e9".repeat(32));
        publish_role_v2(&relay, &community, &owner, &role_v2(&rmgr, "Mgr", "F", Permissions::MANAGE_ROLES), 1).await;
        publish_role_v2(&relay, &community, &owner, &role_v2(&rlow, "Low", "V", 0), 1).await;
        publish_grant(&relay, &community, &owner, &mgr.public_key(), vec![rmgr.clone()], 1).await;
        publish_grant(&relay, &community, &owner, &m, vec![rlow.clone()], 1).await;
        let everyone_hex = crate::simd::hex::bytes_to_hex_32(&crate::community::v2::derive::everyone_locator(community.id()));
        publish_grant_citing(&relay, &community, &mgr, &m, vec![everyone_hex], 2, None).await;
        let f = fold_authority(&community, &fetch_control(&relay, &community).await, &Floors::default());
        assert_eq!(f.roles.roles_of(&m.to_hex()).count(), 1, "the member keeps Low");
    }

    async fn publish_tenure(relay: &MemoryRelay, community: &CommunityV2, signer: &Keys, member: &PublicKey, sealed: Vec<crate::community::v2::roles::TenureEntry>, version: u64) {
        let eid = crate::community::v2::derive::tenure_locator(community.id(), &member.to_bytes(), &signer.public_key().to_bytes());
        let content = crate::community::v2::roles::tenure_content_json(&crate::community::v2::roles::TenureContent { member: member.to_hex(), sealed }).unwrap();
        let group = control::ControlPlane::of(community).write_group().unwrap();
        let prev = head_hash_on_relay(relay, community, &eid).await;
        let cite = cite_on_relay(relay, community, signer).await;
        let binding = Some(crate::community::v2::derive::edition_binding(community.id()));
        let rumor = control::build_edition_rumor_bound(signer.public_key(), vsk::TENURE, &eid, version, prev.as_ref(), &content, 1_000, cite.as_ref(), binding);
        let (wrap, _) = control::seal_control_edition(&rumor, &group, signer, Timestamp::from_secs(1_000)).unwrap();
        relay.publish(&wrap, &community.relays).await.unwrap();
    }

    fn entry(rank: &str, bits: u64, heads: &[[u8; 32]]) -> crate::community::v2::roles::TenureEntry {
        crate::community::v2::roles::TenureEntry { rank: rank.into(), permissions: bits, heads: heads.iter().map(crate::simd::hex::bytes_to_hex_32).collect() }
    }

    #[tokio::test]
    async fn a_tenure_keeps_what_a_demoted_admin_decided_and_nothing_after() {
        // CORD-04 §9: the listed editions are judged at the sealed standing; anything else the
        // member signs is judged on where they stand now.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Tenure", vec!["wss://r".into()], None).await.unwrap();
        publish_everyone(&relay, &community, &owner, 0, 1).await;
        let a = Keys::generate();
        let bits = Permissions::MANAGE_ROLES | Permissions::MANAGE_CHANNELS;
        let (ra, made, late) = ("a1".repeat(32), "a6".repeat(32), "a7".repeat(32));
        publish_role_v2(&relay, &community, &owner, &role_v2(&ra, "Admin", "F", bits), 1).await;
        publish_grant(&relay, &community, &owner, &a.public_key(), vec![ra.clone()], 1).await;
        publish_role_v2(&relay, &community, &a, &role_v2(&made, "Made by A", "V", 0), 1).await;
        let ch = community.channels[0].id;
        let v1 = head_hash_on_relay(&relay, &community, &ch.0).await;
        let renamed = publish_fork(&[&relay], &community, &a, vsk::CHANNEL_METADATA, &ch.0, 2, v1, &channel_meta_json("by A"), None).await;
        let eds = fetch_control(&relay, &community).await;
        let hash = |id: [u8; 32]| eds.iter().find(|e| e.inner_id == id).unwrap().self_hash;
        let role_hash = eds.iter().find(|e| e.entity_id == eid_of(&made)).unwrap().self_hash;
        publish_tenure(&relay, &community, &owner, &a.public_key(), vec![entry("F", bits, &[role_hash, hash(renamed)])], 1).await;
        publish_grant(&relay, &community, &owner, &a.public_key(), vec![], 2).await;
        // After the strip, A signs something new: nothing seals it.
        publish_role_v2(&relay, &community, &a, &role_v2(&late, "Late", "W", 0), 1).await;

        let editions = fetch_control(&relay, &community).await;
        let f = fold_authority(&community, &editions, &Floors::default());
        assert!(f.roles.role(&made).is_some(), "A's role stands on the sealed standing");
        assert!(f.roles.role(&late).is_none(), "A's later role doesn't");
        let fold = apply_control_fold(&community, &editions, &Floors::default(), &f);
        assert_eq!(fold.updated.as_ref().unwrap_or(&community).channel(&ch).unwrap().name, "by A", "and so does A's channel edit");
    }

    #[tokio::test]
    async fn a_tenure_seals_only_what_its_writer_could_grant() {
        // Beneath the writer, with bits the writer holds above it; and never by the member
        // themselves, or anyone could pre-seal against their own demotion.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "TenureLimit", vec!["wss://r".into()], None).await.unwrap();
        publish_everyone(&relay, &community, &owner, 0, 1).await;
        let (a, m) = (Keys::generate(), Keys::generate());
        let mr = Permissions::MANAGE_ROLES;
        let (ra, rm, made) = ("b1".repeat(32), "b2".repeat(32), "b6".repeat(32));
        publish_role_v2(&relay, &community, &owner, &role_v2(&ra, "A", "C", mr), 1).await;
        publish_role_v2(&relay, &community, &owner, &role_v2(&rm, "M", "F", mr), 1).await;
        publish_grant(&relay, &community, &owner, &a.public_key(), vec![ra.clone()], 1).await;
        publish_grant(&relay, &community, &owner, &m.public_key(), vec![rm.clone()], 1).await;
        publish_role_v2(&relay, &community, &a, &role_v2(&made, "Made", "V", 0), 1).await;
        let role_hash = fetch_control(&relay, &community).await.into_iter().find(|e| e.entity_id == eid_of(&made)).unwrap().self_hash;
        // M seals A at A's rank, above M: refused. A seals themselves: refused.
        publish_tenure(&relay, &community, &m, &a.public_key(), vec![entry("C", mr, &[role_hash])], 1).await;
        publish_grant(&relay, &community, &owner, &a.public_key(), vec![], 2).await;
        let f = fold_authority(&community, &fetch_control(&relay, &community).await, &Floors::default());
        assert!(f.roles.role(&made).is_none(), "a Tenure above its writer seals nothing");

        // A seal lends nothing at its own rank: A's role at A's rank stays refused.
        let peer_c = create_community(&relay, "PeerSeal", vec!["wss://r".into()], None).await.unwrap();
        publish_everyone(&relay, &peer_c, &owner, 0, 1).await;
        let peer = "b7".repeat(32);
        publish_role_v2(&relay, &peer_c, &owner, &role_v2(&ra, "A", "C", mr), 1).await;
        publish_grant(&relay, &peer_c, &owner, &a.public_key(), vec![ra.clone()], 1).await;
        publish_role_v2(&relay, &peer_c, &a, &role_v2(&peer, "Peer", "C", 0), 1).await;
        let peer_hash = fetch_control(&relay, &peer_c).await.into_iter().find(|e| e.entity_id == eid_of(&peer)).unwrap().self_hash;
        publish_tenure(&relay, &peer_c, &owner, &a.public_key(), vec![entry("C", mr, &[peer_hash])], 1).await;
        publish_grant(&relay, &peer_c, &owner, &a.public_key(), vec![], 2).await;
        let p = fold_authority(&peer_c, &fetch_control(&relay, &peer_c).await, &Floors::default());
        assert!(p.roles.role(&peer).is_none(), "sealed at C, A still can't stand a role at C");

        let other = create_community(&relay, "SelfSeal", vec!["wss://r".into()], None).await.unwrap();
        publish_everyone(&relay, &other, &owner, 0, 1).await;
        publish_role_v2(&relay, &other, &owner, &role_v2(&ra, "A", "C", mr), 1).await;
        publish_grant(&relay, &other, &owner, &a.public_key(), vec![ra.clone()], 1).await;
        publish_role_v2(&relay, &other, &a, &role_v2(&made, "Made", "V", 0), 1).await;
        let role_hash = fetch_control(&relay, &other).await.into_iter().find(|e| e.entity_id == eid_of(&made)).unwrap().self_hash;
        publish_tenure(&relay, &other, &a, &a.public_key(), vec![entry("V", 0, &[role_hash])], 1).await;
        publish_grant(&relay, &other, &owner, &a.public_key(), vec![], 2).await;
        let g = fold_authority(&other, &fetch_control(&relay, &other).await, &Floors::default());
        assert!(g.roles.role(&made).is_none(), "nor a Tenure its own member wrote");
    }

    #[tokio::test]
    async fn a_tenure_written_by_a_later_demoted_admin_still_stands() {
        // X demoted Y and sealed Y's standing; then the owner banned X, sealing X's. Y's
        // decisions hold through X's sealed standing.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Chain", vec!["wss://r".into()], None).await.unwrap();
        publish_everyone(&relay, &community, &owner, 0, 1).await;
        let (x, y) = (Keys::generate(), Keys::generate());
        let mr = Permissions::MANAGE_ROLES;
        let (rx, ry, made) = ("e1".repeat(32), "e2".repeat(32), "e6".repeat(32));
        publish_role_v2(&relay, &community, &owner, &role_v2(&rx, "X", "C", mr), 1).await;
        publish_role_v2(&relay, &community, &owner, &role_v2(&ry, "Y", "F", mr), 1).await;
        publish_grant(&relay, &community, &owner, &x.public_key(), vec![rx.clone()], 1).await;
        publish_grant(&relay, &community, &owner, &y.public_key(), vec![ry.clone()], 1).await;
        publish_role_v2(&relay, &community, &y, &role_v2(&made, "Made by Y", "V", 0), 1).await;
        let hash_at = |eds: &[ParsedEdition], eid: [u8; 32]| eds.iter().filter(|e| e.entity_id == eid).max_by_key(|e| e.version).unwrap().self_hash;
        let eds = fetch_control(&relay, &community).await;
        publish_tenure(&relay, &community, &x, &y.public_key(), vec![entry("F", mr, &[hash_at(&eds, eid_of(&made))])], 1).await;
        publish_grant(&relay, &community, &x, &y.public_key(), vec![], 2).await;
        let eds = fetch_control(&relay, &community).await;
        let tenure_y = crate::community::v2::derive::tenure_locator(community.id(), &y.public_key().to_bytes(), &x.public_key().to_bytes());
        let strip_y = crate::community::v2::derive::grant_locator(community.id(), &y.public_key().to_bytes());
        publish_tenure(&relay, &community, &owner, &x.public_key(), vec![entry("C", mr, &[hash_at(&eds, tenure_y), hash_at(&eds, strip_y)])], 1).await;
        publish_banlist(&relay, &community, &owner, &[x.public_key().to_hex()], 1).await;

        let f = fold_authority(&community, &fetch_control(&relay, &community).await, &Floors::default());
        assert!(f.banned.contains(&x.public_key().to_hex()) && f.roles.roles_of(&x.public_key().to_hex()).next().is_none());
        assert!(f.roles.roles_of(&y.public_key().to_hex()).next().is_none(), "X's strip of Y stands though X is banned");
        assert!(f.roles.role(&made).is_some(), "and so does what Y decided, through X's sealed standing");
    }

    #[tokio::test]
    async fn a_sealed_banlist_keeps_its_bans_after_its_editor_is_demoted() {
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "SealedBans", vec!["wss://r".into()], None).await.unwrap();
        publish_everyone(&relay, &community, &owner, 0, 1).await;
        let (a, t) = (Keys::generate(), Keys::generate());
        let bits = Permissions::MANAGE_ROLES | Permissions::BAN;
        let ra = "f1".repeat(32);
        publish_role_v2(&relay, &community, &owner, &role_v2(&ra, "Mod", "C", bits), 1).await;
        publish_grant(&relay, &community, &owner, &a.public_key(), vec![ra.clone()], 1).await;
        publish_banlist(&relay, &community, &a, &[t.public_key().to_hex()], 1).await;
        let eds = fetch_control(&relay, &community).await;
        let banlist = eds.iter().find(|e| e.entity_id == crate::community::v2::derive::banlist_locator(community.id())).unwrap().self_hash;
        publish_tenure(&relay, &community, &owner, &a.public_key(), vec![entry("C", bits, &[banlist])], 1).await;
        publish_grant(&relay, &community, &owner, &a.public_key(), vec![], 2).await;
        let f = fold_authority(&community, &fetch_control(&relay, &community).await, &Floors::default());
        assert!(f.banned.contains(&t.public_key().to_hex()), "the ban A made stands on A's sealed standing");
    }

    fn folded(base: &CommunityV2, eds: &[ParsedEdition]) -> CommunityV2 {
        let f = fold_authority(base, eds, &Floors::default());
        apply_control_fold(base, eds, &Floors::default(), &f).updated.unwrap_or_else(|| base.clone())
    }

    fn sidebar_names(c: &CommunityV2) -> Vec<(Option<String>, Vec<String>)> {
        c.sidebar().into_iter().map(|(k, chans)| (k.map(|k| k.name.clone()), chans.into_iter().map(|c| c.name.clone()).collect())).collect()
    }

    fn held_of(c: &CommunityV2) -> CommunityV2 {
        crate::db::community::load_community_v2(c.id()).unwrap().unwrap()
    }

    /// Every channel of a thirty-channel community, one message each, backfilled twice over a
    /// real socket: more planes than the plane pool holds. Returns the connections it took.
    async fn backfill_sockets() -> usize {
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Many", vec!["wss://r".into()], None).await.unwrap();
        for i in 1..30 {
            create_public_channel(&relay, &held_of(&community), &format!("channel {i}")).await.unwrap();
        }
        let mut community = held_of(&community);
        assert_eq!(community.channels.len(), 30);
        for ch in &community.channels {
            send_message(&relay, &community, &ch.id, &format!("hello {}", ch.name)).await.unwrap();
        }
        let wire = crate::community::transport::wire::WireRelay::start().await;
        wire.hold(relay.fetch(&Query { kinds: vec![stream::KIND_WRAP], ..Default::default() }, &community.relays).await.unwrap());
        community.relays = vec![wire.url()];
        crate::transport::set_preference(Some(crate::transport::Kind::Clearnet));
        let live = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(5));
        for _ in 0..2 {
            for ch in &community.channels {
                let read = fetch_channel_history(&live, &community, &ch.id, 50, 1, None, None, crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default());
                assert_eq!(read.await.unwrap().len(), 1, "#{} backfilled", ch.name);
            }
        }
        crate::community::transport::clear_plane_pool();
        wire.opened()
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn a_backfill_of_many_channels_holds_one_connection_to_a_relay_without_auth() {
        assert_eq!(backfill_sockets().await, 1, "connections opened to the relay");
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn a_relay_found_gating_plane_reads_is_recorded_for_the_account() {
        use nostr_sdk::prelude::FinalizeEvent;
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = crate::community::transport::wire::WireRelay::start().await;
        relay.gate(true);
        crate::transport::set_preference(Some(crate::transport::Kind::Clearnet));
        let plane = Keys::generate();
        let wrap = nostr_sdk::prelude::EventBuilder::new(nostr_sdk::prelude::Kind::Custom(stream::KIND_WRAP), "sealed").finalize(&plane).unwrap();
        relay.hold([wrap]);
        let query = Query { kinds: vec![stream::KIND_WRAP], authors: vec![plane.public_key().to_hex()], ..Default::default() };
        let live = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(5));
        live.fetch_plane(&plane, &query, &[relay.url()]).await.unwrap();
        assert!(crate::community::transport::auth_gate_live(&relay.url()));
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn a_relay_the_account_saw_challenge_goes_straight_to_authed_plane_reads() {
        use nostr_sdk::prelude::FinalizeEvent;
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = crate::community::transport::wire::WireRelay::start().await;
        relay.gate(true);
        crate::community::transport::note_auth_gate(&relay.url());
        crate::transport::set_preference(Some(crate::transport::Kind::Clearnet));
        let plane = Keys::generate();
        let wrap = nostr_sdk::prelude::EventBuilder::new(nostr_sdk::prelude::Kind::Custom(stream::KIND_WRAP), "sealed").finalize(&plane).unwrap();
        relay.hold([wrap.clone()]);
        let query = Query { kinds: vec![stream::KIND_WRAP], authors: vec![plane.public_key().to_hex()], ..Default::default() };
        let live = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(5));
        let read = live.fetch_plane(&plane, &query, &[relay.url()]).await.unwrap();
        assert_eq!(read.events.iter().map(|e| e.id).collect::<Vec<_>>(), vec![wrap.id]);
        assert_eq!(relay.opened(), 1, "no open read first");
    }

    #[tokio::test]
    async fn categories_order_and_delete_terminally() {
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Cats", vec!["wss://r".into()], None).await.unwrap();
        let staff = create_category(&relay, &held_of(&community), "Staff").await.unwrap();
        let social = create_category(&relay, &held_of(&community), "Social").await.unwrap();
        move_category(&relay, &held_of(&community), social, 0).await.unwrap();
        rename_category(&relay, &held_of(&community), staff, "Mods").await.unwrap();
        let peer = folded(&community, &fetch_control(&relay, &community).await);
        assert_eq!(sidebar_names(&peer), vec![(None, vec!["general".into()]), (Some("Social".into()), vec![]), (Some("Mods".into()), vec![])]);
        assert_eq!(sidebar_names(&held_of(&community)), sidebar_names(&peer), "this device shows what a peer folds, and keeps it across a reload");

        delete_category(&relay, &held_of(&community), social).await.unwrap();
        // A later edition can't bring a deleted Category back.
        let eds = fetch_control(&relay, &community).await;
        let head = eds.iter().filter(|e| e.entity_id == social).max_by_key(|e| e.version).unwrap();
        let revive = serde_json::to_string(&control::CategoryMetadata { name: "Back".into(), position: Some("V".into()), ..Default::default() }).unwrap();
        publish_marked(&relay, &community, &owner, vsk::CATEGORY, &social, head.version + 1, Some(head.self_hash), &revive).await;
        let peer = folded(&community, &fetch_control(&relay, &community).await);
        assert_eq!(peer.categories.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), vec!["Mods"]);
    }

    /// One marked edition at an explicit version and predecessor.
    async fn publish_marked(relay: &MemoryRelay, community: &CommunityV2, signer: &Keys, vsk_code: &str, eid: &[u8; 32], version: u64, prev: Option<[u8; 32]>, content: &str) {
        let group = control::ControlPlane::of(community).write_group().unwrap();
        let cite = cite_on_relay(relay, community, signer).await;
        let binding = Some(crate::community::v2::derive::edition_binding(community.id()));
        let rumor = control::build_edition_rumor_bound(signer.public_key(), vsk_code, eid, version, prev.as_ref(), content, 2_000 + version, cite.as_ref(), binding);
        let (wrap, _) = control::seal_control_edition(&rumor, &group, signer, Timestamp::from_secs(2_000 + version)).unwrap();
        relay.publish(&wrap, &community.relays).await.unwrap();
    }

    #[tokio::test]
    async fn a_category_needs_manage_channels_the_mark_and_its_own_coordinate() {
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "CatGate", vec!["wss://r".into()], None).await.unwrap();
        let cat = |name: &str| serde_json::to_string(&control::CategoryMetadata { name: name.into(), position: Some("V".into()), ..Default::default() }).unwrap();
        let stranger = Keys::generate();
        publish_marked(&relay, &community, &stranger, vsk::CATEGORY, &[0x31; 32], 1, None, &cat("Stranger's")).await;
        // Unmarked: nothing older ever wrote a Category, so an unmarked one is forged.
        publish_fork(&[&relay], &community, &owner, vsk::CATEGORY, &[0x32; 32], 1, None, &cat("Unmarked"), None).await;
        // At another entity's coordinate.
        let general = community.channels[0].id.0;
        publish_marked(&relay, &community, &owner, vsk::CATEGORY, &general, 1, None, &cat("On a channel")).await;
        publish_marked(&relay, &community, &owner, vsk::CATEGORY, &crate::community::v2::derive::banlist_locator(community.id()), 1, None, &cat("On the banlist")).await;
        publish_marked(&relay, &community, &owner, vsk::CATEGORY, &[0x33; 32], 1, None, &cat("Real")).await;
        // A stranger's deletion deletes nothing.
        let real = fetch_control(&relay, &community).await.into_iter().find(|e| e.entity_id == [0x33; 32]).unwrap();
        let gone = serde_json::to_string(&control::CategoryMetadata { deleted: Some(true), ..Default::default() }).unwrap();
        publish_marked(&relay, &community, &stranger, vsk::CATEGORY, &[0x33; 32], 2, Some(real.self_hash), &gone).await;
        let peer = folded(&community, &fetch_control(&relay, &community).await);
        assert_eq!(peer.categories.iter().map(|c| c.name.as_str()).collect::<Vec<_>>(), vec!["Real"]);
    }

    #[tokio::test]
    async fn a_channel_moves_in_one_edition_once_its_group_is_keyed() {
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Moves", vec!["wss://r".into()], None).await.unwrap();
        let alpha = create_public_channel(&relay, &held_of(&community), "alpha").await.unwrap();
        let beta = create_public_channel(&relay, &held_of(&community), "beta").await.unwrap();
        let gamma = create_public_channel(&relay, &held_of(&community), "gamma").await.unwrap();
        let names = |c: &CommunityV2| sidebar_names(c)[0].1.clone();
        assert_eq!(names(&held_of(&community)), vec!["alpha", "beta", "gamma", "general"], "keyless channels sort by name");
        // The first move keys the group as it shows, then places gamma.
        move_channel(&relay, &held_of(&community), &gamma, None, 0).await.unwrap();
        assert_eq!(names(&held_of(&community)), vec!["gamma", "alpha", "beta", "general"]);
        let before = fetch_control(&relay, &community).await.len();
        move_channel(&relay, &held_of(&community), &gamma, None, 2).await.unwrap();
        assert_eq!(fetch_control(&relay, &community).await.len(), before + 1, "a later move is one edition");
        assert_eq!(names(&held_of(&community)), vec!["alpha", "beta", "gamma", "general"]);

        let staff = create_category(&relay, &held_of(&community), "Staff").await.unwrap();
        move_channel(&relay, &held_of(&community), &beta, Some(staff), 0).await.unwrap();
        let delta = create_channel_in(&relay, &held_of(&community), "delta", false, Some(staff)).await.unwrap();
        let peer = folded(&community, &fetch_control(&relay, &community).await);
        assert_eq!(sidebar_names(&peer), vec![(None, vec!["alpha".into(), "gamma".into(), "general".into()]), (Some("Staff".into()), vec!["beta".into(), "delta".into()])]);
        assert_eq!(sidebar_names(&held_of(&community)), sidebar_names(&peer));
        move_channel(&relay, &held_of(&community), &delta, None, usize::MAX).await.unwrap();
        // A deleted Category unfiles its Channels, which keep pointing at it.
        delete_category(&relay, &held_of(&community), staff).await.unwrap();
        let peer = folded(&community, &fetch_control(&relay, &community).await);
        // Its key from inside Staff ties alpha's out here, and the name breaks the tie.
        assert_eq!(sidebar_names(&peer), vec![(None, vec!["alpha".into(), "beta".into(), "gamma".into(), "general".into(), "delta".into()])]);
        assert_eq!(peer.channel(&beta).unwrap().category(), Some(staff));
        assert!(move_channel(&relay, &held_of(&community), &alpha, Some(staff), 0).await.is_err(), "nothing files under a deleted Category");
    }

    #[tokio::test]
    async fn channel_details_round_trip_and_keep_what_others_wrote() {
        use crate::community::v2::community::ChannelView;
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Details", vec!["wss://r".into()], None).await.unwrap();
        let general = community.channels[0].id;
        // Another client's field, and its legacy voice flag.
        let mut foreign = community.channels[0].metadata();
        foreign.extra.insert("vnd".into(), 7.into());
        foreign.voice = Some(true);
        let v1 = head_hash_on_relay(&relay, &community, &general.0).await;
        publish_fork(&[&relay], &community, &owner, vsk::CHANNEL_METADATA, &general.0, 2, v1, &serde_json::to_string(&foreign).unwrap(), None).await;
        follow_control(&relay, &community).await.unwrap();
        assert_eq!(held_of(&community).channel(&general).unwrap().view(), ChannelView::Voice, "the legacy flag reads as a voice view");

        edit_channel_details(&relay, &held_of(&community), &general, "lobby", Some("  Say hi  "), ChannelView::Forum).await.unwrap();
        let peer = folded(&community, &fetch_control(&relay, &community).await);
        let ch = peer.channel(&general).unwrap();
        assert_eq!((ch.name.as_str(), ch.topic(), ch.view()), ("lobby", Some("Say hi"), ChannelView::Forum));
        assert_eq!(ch.meta_extra.get("vnd"), Some(&serde_json::Value::from(7)), "a field Vector doesn't drive rides through");
        edit_channel_details(&relay, &held_of(&community), &general, "lobby", None, ChannelView::Chat).await.unwrap();
        let ch = folded(&community, &fetch_control(&relay, &community).await).channel(&general).unwrap().clone();
        assert_eq!((ch.topic(), ch.view()), (None, ChannelView::Chat), "chat over a legacy voice flag is written, not implied");
        assert!(edit_channel_details(&relay, &held_of(&community), &general, "lobby", Some(&"x".repeat(1025)), ChannelView::Chat).await.is_err(), "the topic cap");
    }

    #[tokio::test]
    async fn a_refounding_carries_categories_and_filing() {
        let (bed, owner, _m) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "CarryCats", bed.relays.clone(), None).await.unwrap();
        follow_control(&bed.relay, &community).await.unwrap();
        let staff = create_category(&bed.relay, &held_of(&community), "Staff").await.unwrap();
        let general = community.channels[0].id;
        move_channel(&bed.relay, &held_of(&community), &general, Some(staff), 0).await.unwrap();
        follow_control(&bed.relay, &held_of(&community)).await.unwrap();
        set_members_banned(&bed.relay, community.id(), &[Keys::generate().public_key()], true).await.unwrap();
        let now = held_of(&community);
        assert_ne!(now.root_epoch, community.root_epoch, "the ban re-founded");
        let mut fresh = now.clone();
        fresh.categories.clear();
        let peer = folded(&fresh, &fetch_control(&bed.relay, &now).await);
        assert_eq!(sidebar_names(&peer), vec![(None, vec![]), (Some("Staff".into()), vec!["general".into()])]);
    }

    #[tokio::test]
    async fn a_ban_spares_the_floor_of_a_sealed_head() {
        // A ban voids a floor its target recorded, unless a Tenure sealed that head: then
        // the floor holds, and with the held edition withheld no admin's rival stands in.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "SealedFloor", vec!["wss://r".into()], None).await.unwrap();
        publish_everyone(&relay, &community, &owner, 0, 1).await;
        let (b, c) = (Keys::generate(), Keys::generate());
        let mr = Permissions::MANAGE_ROLES;
        let (rb, rc, made) = ("a2".repeat(32), "a3".repeat(32), "a8".repeat(32));
        publish_role_v2(&relay, &community, &owner, &role_v2(&rb, "B", "C", mr), 1).await;
        publish_role_v2(&relay, &community, &owner, &role_v2(&rc, "C", "D", mr), 1).await;
        publish_grant(&relay, &community, &owner, &b.public_key(), vec![rb.clone()], 1).await;
        publish_grant(&relay, &community, &owner, &c.public_key(), vec![rc.clone()], 1).await;
        publish_role_v2(&relay, &community, &b, &role_v2(&made, "by B", "V", 0), 1).await;
        let held = fetch_control(&relay, &community).await.into_iter().find(|e| e.entity_id == eid_of(&made)).unwrap();
        publish_tenure(&relay, &community, &owner, &b.public_key(), vec![entry("C", mr, &[held.self_hash])], 1).await;
        publish_banlist(&relay, &community, &owner, &[b.public_key().to_hex()], 1).await;
        // C, an admin in good standing, serves a rival genesis at B's coordinate.
        let group = control::ControlPlane::of(&community).write_group().unwrap();
        let cite = cite_on_relay(&relay, &community, &c).await;
        let content = crate::community::v2::roles::role_v2_content_json(&role_v2(&made, "by C", "W", 0)).unwrap();
        let binding = Some(crate::community::v2::derive::edition_binding(community.id()));
        let rumor = control::build_edition_rumor_bound(c.public_key(), vsk::ROLE_V2, &eid_of(&made), 1, None, &content, 1_000, cite.as_ref(), binding);
        let (wrap, _) = control::seal_control_edition(&rumor, &group, &c, Timestamp::from_secs(1_000)).unwrap();
        relay.publish(&wrap, &community.relays).await.unwrap();
        let served: Vec<ParsedEdition> = fetch_control(&relay, &community).await.into_iter().filter(|e| e.inner_id != held.inner_id).collect();
        let floors: Floors = [(crate::simd::hex::bytes_to_hex_32(&held.entity_id), (1, held.self_hash, Some(held.inner_id), Some(b.public_key().to_bytes()), None))].into_iter().collect();
        assert_eq!(fold_authority(&community, &served, &Floors::default()).roles.role(&made).map(|r| r.name.as_str()), Some("by C"), "read floorless, C's stands");
        let f = fold_authority(&community, &served, &floors);
        assert!(f.roles.role(&made).is_none_or(|r| r.name != "by C"), "the sealed floor holds against a non-owner rival");
        // Withheld is not refused: a relay that drops a sealed head can't settle it absent.
        assert!(!f.refused.contains(&crate::simd::hex::bytes_to_hex_32(&held.entity_id)), "the withheld sealed head isn't settled absent");
    }

    /// Serves everything but the wraps whose edition `hide` picks.
    struct Hiding<'a> {
        inner: &'a MemoryRelay,
        group: crate::community::v2::derive::GroupKey,
        hide: Box<dyn Fn(&ParsedEdition) -> bool + Send + Sync + 'a>,
    }
    #[async_trait::async_trait]
    impl Transport for Hiding<'_> {
        async fn fetch_plane(&self, _plane: &Keys, query: &Query, relays: &[String]) -> Result<crate::community::transport::PlaneFetch, String> {
            Ok(crate::community::transport::PlaneFetch::whole(self.fetch(query, relays).await?))
        }
        async fn publish(&self, e: &Event, r: &[String]) -> Result<(), String> {
            self.inner.publish(e, r).await
        }
        async fn publish_durable(&self, e: &Event, r: &[String]) -> Result<(), String> {
            self.inner.publish_durable(e, r).await
        }
        async fn fetch(&self, q: &Query, r: &[String]) -> Result<Vec<Event>, String> {
            let all = self.inner.fetch(q, r).await?;
            Ok(all.into_iter().filter(|w| control::open_control_edition(w, &self.group).ok().is_none_or(|(ed, _)| !(self.hide)(&ed))).collect())
        }
    }

    #[tokio::test]
    async fn a_withheld_tenure_leaves_what_it_seals_unsettled() {
        // A device tracking a Tenure must not read its absence as evidence: what it sealed
        // is neither refused nor stepped down while a relay withholds it.
        let (bed, owner, _m) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Withheld", bed.relays.clone(), None).await.unwrap();
        activate_roles_v2(&bed.relay, &community, 0).await.unwrap();
        follow_control(&bed.relay, &community).await.unwrap();
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let a = Keys::generate();
        let admin = create_role_v2(&bed.relay, &held(), "Admin", 0, Permissions::MANAGE_ROLES).await.unwrap();
        set_member_roles(&bed.relay, &held(), &a.public_key(), vec![admin]).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        let made = "a9".repeat(32);
        publish_role_v2(&bed.relay, &held(), &a, &role_v2(&made, "by A", "z", 0), 1).await;
        follow_control(&bed.relay, &held()).await.unwrap();
        set_member_roles(&bed.relay, &held(), &a.public_key(), vec![]).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let floors: Floors = crate::db::community::get_all_edition_heads_full(&cid_hex).unwrap().into_iter().filter(|(_, f)| f.0 == held().root_epoch.0).map(|(e, f)| (e, (f.1, f.2, f.3, f.4, f.5))).collect();
        let served: Vec<ParsedEdition> = fetch_control(&bed.relay, &held()).await.into_iter().filter(|e| e.vsk != vsk::TENURE).collect();
        let f = fold_authority(&held(), &served, &floors);
        let entity = crate::simd::hex::bytes_to_hex_32(&eid_of(&made));
        assert!(!f.refused.contains(&entity), "not settled absent");
        assert!(f.heads.iter().any(|h| h.entity_hex == entity && !h.rebased), "the held head stays the head");
        assert!(!f.complete, "and the fold knows it read short");
    }

    #[tokio::test]
    async fn a_writer_never_replaces_a_tenure_it_cant_see() {
        let (bed, owner, _m) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Clobber", bed.relays.clone(), None).await.unwrap();
        activate_roles_v2(&bed.relay, &community, 0).await.unwrap();
        follow_control(&bed.relay, &community).await.unwrap();
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let a = Keys::generate();
        let r1 = create_role_v2(&bed.relay, &held(), "One", 0, Permissions::MANAGE_ROLES).await.unwrap();
        let r2 = create_role_v2(&bed.relay, &held(), "Two", 0, Permissions::MANAGE_ROLES).await.unwrap();
        set_member_roles(&bed.relay, &held(), &a.public_key(), vec![r1.clone(), r2.clone()]).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        publish_role_v2(&bed.relay, &held(), &a, &role_v2(&"b9".repeat(32), "by A", "z", 0), 1).await;
        follow_control(&bed.relay, &held()).await.unwrap();
        set_member_roles(&bed.relay, &held(), &a.public_key(), vec![r2.clone()]).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        let hiding = Hiding { inner: &bed.relay, group: control::ControlPlane::of(&held()).write_group().unwrap(), hide: Box::new(|e| e.vsk == vsk::TENURE) };
        let before = fetch_control(&bed.relay, &held()).await.len();
        forget_held(&held());
        let err = set_member_roles(&hiding, &held(), &a.public_key(), vec![]).await.unwrap_err();
        assert!(err.contains("isn't being served"), "{err}");
        assert_eq!(fetch_control(&bed.relay, &held()).await.len(), before, "nothing was published");
        // A removal goes ahead, leaving the unseen Tenure as it was.
        kick_member(&hiding, &held(), &a.public_key()).await.unwrap();
        let eds = fetch_control(&bed.relay, &held()).await;
        assert_eq!(eds.iter().filter(|e| e.vsk == vsk::TENURE).count(), 1, "the earlier Tenure stands alone");
    }

    #[tokio::test]
    async fn a_weaker_writer_seals_beside_a_stronger_one() {
        // The owner demoted M from the top; later an admin beneath M's old rank strips M's
        // last role. Each seals in a Tenure of their own, so both standings hold.
        let (bed, owner, _m) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "TwoWriters", bed.relays.clone(), None).await.unwrap();
        activate_roles_v2(&bed.relay, &community, 0).await.unwrap();
        follow_control(&bed.relay, &community).await.unwrap();
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let mr = Permissions::MANAGE_ROLES;
        let (m, x) = (Keys::generate(), Keys::generate());
        let top = create_role_v2(&bed.relay, &held(), "Top", 0, mr | Permissions::BAN).await.unwrap();
        let admin = create_role_v2(&bed.relay, &held(), "Admin", 0, mr).await.unwrap();
        let helper = create_role_v2(&bed.relay, &held(), "Helper", 0, mr).await.unwrap();
        set_member_roles(&bed.relay, &held(), &m.public_key(), vec![top.clone()]).await.unwrap();
        set_member_roles(&bed.relay, &held(), &x.public_key(), vec![admin]).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        let (early, late) = ("c7".repeat(32), "c8".repeat(32));
        publish_role_v2(&bed.relay, &held(), &m, &role_v2(&early, "early", "z", 0), 1).await;
        follow_control(&bed.relay, &held()).await.unwrap();
        set_member_roles(&bed.relay, &held(), &m.public_key(), vec![helper.clone()]).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        publish_role_v2(&bed.relay, &held(), &m, &role_v2(&late, "late", "z", 0), 1).await;
        follow_control(&bed.relay, &held()).await.unwrap();
        crate::state::MY_SECRET_KEY.store_from_keys(&x, &[]);
        crate::state::set_my_public_key(x.public_key());
        set_member_roles(&bed.relay, &held(), &m.public_key(), vec![]).await.unwrap();
        let eds = fetch_control(&bed.relay, &held()).await;
        assert_eq!(eds.iter().filter(|e| e.vsk == vsk::TENURE).count(), 2, "one Tenure per writer");
        let f = fold_authority(&held(), &eds, &Floors::default());
        assert!(f.roles.role(&early).is_some() && f.roles.role(&late).is_some(), "both standings hold");
    }

    #[tokio::test]
    async fn a_tenure_at_another_writers_coordinate_is_ignored() {
        // Each writer's Tenure lives at a coordinate naming them: an admin can't replace the
        // owner's Tenure of a member with one of their own.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Squat", vec!["wss://r".into()], None).await.unwrap();
        publish_everyone(&relay, &community, &owner, 0, 1).await;
        let (a, x) = (Keys::generate(), Keys::generate());
        let mr = Permissions::MANAGE_ROLES;
        let (ra, rx, made) = ("d7".repeat(32), "d8".repeat(32), "d9".repeat(32));
        publish_role_v2(&relay, &community, &owner, &role_v2(&rx, "X", "B", mr), 1).await;
        publish_role_v2(&relay, &community, &owner, &role_v2(&ra, "A", "C", mr), 1).await;
        publish_grant(&relay, &community, &owner, &x.public_key(), vec![rx.clone()], 1).await;
        publish_grant(&relay, &community, &owner, &a.public_key(), vec![ra.clone()], 1).await;
        publish_role_v2(&relay, &community, &a, &role_v2(&made, "by A", "V", 0), 1).await;
        let hash = fetch_control(&relay, &community).await.into_iter().find(|e| e.entity_id == eid_of(&made)).unwrap().self_hash;
        publish_tenure(&relay, &community, &owner, &a.public_key(), vec![entry("C", mr, &[hash])], 1).await;
        publish_grant(&relay, &community, &owner, &a.public_key(), vec![], 2).await;
        // X writes v2 at the owner's coordinate, sealing nothing of note.
        let eid = crate::community::v2::derive::tenure_locator(community.id(), &a.public_key().to_bytes(), &owner.public_key().to_bytes());
        let prev = head_hash_on_relay(&relay, &community, &eid).await;
        let content = crate::community::v2::roles::tenure_content_json(&crate::community::v2::roles::TenureContent { member: a.public_key().to_hex(), sealed: vec![entry("V", 0, &[[0x11; 32]])] }).unwrap();
        publish_marked(&relay, &community, &x, vsk::TENURE, &eid, 2, prev, &content).await;
        let f = fold_authority(&community, &fetch_control(&relay, &community).await, &Floors::default());
        assert!(f.roles.role(&made).is_some(), "the owner's seal still holds");
    }

    #[tokio::test]
    async fn a_reorder_moves_only_what_left_its_run() {
        let (bed, owner, _m) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Reorder", bed.relays.clone(), None).await.unwrap();
        activate_roles_v2(&bed.relay, &community, 0).await.unwrap();
        follow_control(&bed.relay, &community).await.unwrap();
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let mut ids = Vec::new();
        for name in ["A", "B", "C", "D", "E"] {
            ids.push(create_role_v2(&bed.relay, &held(), name, 0, 0).await.unwrap());
        }
        let order = |eds: &[ParsedEdition]| {
            let f = fold_authority(&held(), eds, &Floors::default());
            let mut roles: Vec<&crate::community::roles::Role> = f.roles.roles.iter().collect();
            roles.sort_by(|a, b| a.position.cmp(&b.position).then_with(|| a.role_id.cmp(&b.role_id)));
            roles.into_iter().map(|r| r.name.clone()).collect::<Vec<_>>()
        };
        let pick = |names: &str| names.chars().map(|c| ids[(c as u8 - b'A') as usize].clone()).collect::<Vec<_>>();
        let before = fetch_control(&bed.relay, &held()).await.len();
        assert_eq!(reorder_roles_v2(&bed.relay, &held(), &pick("EABCD")).await.unwrap(), 1, "one Role left its run");
        assert_eq!(fetch_control(&bed.relay, &held()).await.len(), before + 1);
        assert_eq!(order(&fetch_control(&bed.relay, &held()).await), ["E", "A", "B", "C", "D"]);
        assert_eq!(reorder_roles_v2(&bed.relay, &held(), &pick("DBAEC")).await.unwrap(), 3);
        assert_eq!(order(&fetch_control(&bed.relay, &held()).await), ["D", "B", "A", "E", "C"]);
        assert_eq!(reorder_roles_v2(&bed.relay, &held(), &pick("DBAEC")).await.unwrap(), 0, "nothing to do");
    }

    #[tokio::test]
    async fn moving_a_role_up_past_its_grantor_keeps_it_with_its_holders() {
        let (bed, owner, _m) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "MoveUp", bed.relays.clone(), None).await.unwrap();
        activate_roles_v2(&bed.relay, &community, 0).await.unwrap();
        follow_control(&bed.relay, &community).await.unwrap();
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let (x, m) = (Keys::generate(), Keys::generate());
        let admin = create_role_v2(&bed.relay, &held(), "Admin", 0, Permissions::MANAGE_ROLES).await.unwrap();
        let vip = create_role_v2(&bed.relay, &held(), "VIP", 0, 0).await.unwrap();
        set_member_roles(&bed.relay, &held(), &x.public_key(), vec![admin]).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        crate::state::MY_SECRET_KEY.store_from_keys(&x, &[]);
        crate::state::set_my_public_key(x.public_key());
        set_member_roles(&bed.relay, &held(), &m.public_key(), vec![vip.clone()]).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        bed.swap_to(&owner);
        move_role_v2(&bed.relay, &held(), &vip, 0).await.unwrap();
        let f = fold_authority(&held(), &fetch_control(&bed.relay, &held()).await, &Floors::default());
        assert_eq!(f.roles.highest_position(&m.public_key().to_hex()), Some(1), "M still holds VIP, now at the top");
    }

    #[tokio::test]
    async fn a_seal_lends_every_standing_above_what_it_touches() {
        // Two entries list one Banlist edition: MANAGE_ROLES high, BAN lower. A target beneath
        // both is banned on the union, as Roles above it would lend.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Union", vec!["wss://r".into()], None).await.unwrap();
        publish_everyone(&relay, &community, &owner, 0, 1).await;
        let (a, t) = (Keys::generate(), Keys::generate());
        let ra = "d3".repeat(32);
        publish_role_v2(&relay, &community, &owner, &role_v2(&ra, "Mod", "C", Permissions::MANAGE_ROLES | Permissions::BAN), 1).await;
        publish_grant(&relay, &community, &owner, &a.public_key(), vec![ra.clone()], 1).await;
        publish_banlist(&relay, &community, &a, &[t.public_key().to_hex()], 1).await;
        let banlist = fetch_control(&relay, &community).await.into_iter().find(|e| e.entity_id == crate::community::v2::derive::banlist_locator(community.id())).unwrap().self_hash;
        publish_tenure(&relay, &community, &owner, &a.public_key(), vec![entry("C", Permissions::MANAGE_ROLES, &[banlist]), entry("F", Permissions::BAN, &[banlist])], 1).await;
        publish_grant(&relay, &community, &owner, &a.public_key(), vec![], 2).await;
        let f = fold_authority(&community, &fetch_control(&relay, &community).await, &Floors::default());
        assert!(f.banned.contains(&t.public_key().to_hex()));
    }

    #[tokio::test]
    async fn a_strip_to_nothing_seals_even_on_a_stale_roster() {
        let (bed, owner, _m) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Stale", bed.relays.clone(), None).await.unwrap();
        activate_roles_v2(&bed.relay, &community, 0).await.unwrap();
        follow_control(&bed.relay, &community).await.unwrap();
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let a = Keys::generate();
        // Granted on the plane, never folded here.
        let ra = "d5".repeat(32);
        publish_role_v2(&bed.relay, &held(), &owner.keys, &role_v2(&ra, "Admin", "C", Permissions::MANAGE_ROLES), 1).await;
        publish_grant(&bed.relay, &held(), &owner.keys, &a.public_key(), vec![ra], 1).await;
        publish_role_v2(&bed.relay, &held(), &a, &role_v2(&"d6".repeat(32), "by A", "z", 0), 1).await;
        grant_roles(&bed.relay, &held(), &a.public_key(), vec![]).await.unwrap();
        assert_eq!(fetch_control(&bed.relay, &held()).await.iter().filter(|e| e.vsk == vsk::TENURE).count(), 1);
        let f = fold_authority(&held(), &fetch_control(&bed.relay, &held()).await, &Floors::default());
        assert!(f.roles.role(&"d6".repeat(32)).is_some(), "what they made stands on the seal");
    }

    #[test]
    fn a_seal_keeps_a_members_deletions_ahead_of_everything_else() {
        let head = |n: u8, author: u8| FoldedHead { entity_hex: String::new(), version: 1, self_hash: [n; 32], inner_id: [n; 32], author: [author; 32], rebased: false };
        let (grant, edit, deletion, theirs_not) = (head(1, 9), head(2, 9), head(3, 9), head(4, 8));
        let order = seal_order(&[grant.clone()], &[edit.clone(), deletion.clone(), theirs_not], |h| h.author == [9; 32], |h| h.self_hash == [3; 32]);
        assert_eq!(order, vec![[3; 32], [1; 32], [2; 32]], "a budget cut takes a channel edit, never a deletion");
    }

    #[tokio::test]
    async fn a_tenure_goes_to_every_relay() {
        struct Counting<'a> {
            inner: &'a MemoryRelay,
            durable: std::sync::atomic::AtomicUsize,
        }
        #[async_trait::async_trait]
        impl Transport for Counting<'_> {
            async fn fetch_plane(&self, plane: &Keys, query: &Query, relays: &[String]) -> Result<crate::community::transport::PlaneFetch, String> {
                self.inner.fetch_plane(plane, query, relays).await
            }
            async fn publish(&self, event: &Event, relays: &[String]) -> Result<(), String> {
                self.inner.publish(event, relays).await
            }
            async fn publish_durable(&self, event: &Event, relays: &[String]) -> Result<(), String> {
                self.durable.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                self.inner.publish_durable(event, relays).await
            }
            async fn fetch(&self, query: &Query, relays: &[String]) -> Result<Vec<Event>, String> {
                self.inner.fetch(query, relays).await
            }
        }
        let (bed, owner, _m) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Durable", bed.relays.clone(), None).await.unwrap();
        activate_roles_v2(&bed.relay, &community, 0).await.unwrap();
        follow_control(&bed.relay, &community).await.unwrap();
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let a = Keys::generate();
        let ra = "e5".repeat(32);
        publish_role_v2(&bed.relay, &held(), &owner.keys, &role_v2(&ra, "Admin", "C", Permissions::MANAGE_ROLES), 1).await;
        publish_grant(&bed.relay, &held(), &owner.keys, &a.public_key(), vec![ra], 1).await;
        publish_role_v2(&bed.relay, &held(), &a, &role_v2(&"e6".repeat(32), "by A", "z", 0), 1).await;
        let counting = Counting { inner: &bed.relay, durable: Default::default() };
        grant_roles(&counting, &held(), &a.public_key(), vec![]).await.unwrap();
        assert_eq!(fetch_control(&bed.relay, &held()).await.iter().filter(|e| e.vsk == vsk::TENURE).count(), 1);
        assert_eq!(counting.durable.load(std::sync::atomic::Ordering::Relaxed), 1, "the Tenure, and only it, went out durably");
    }

    #[tokio::test]
    async fn every_reduction_seals_what_the_member_decided() {
        // The writer side: a strip, a deletion, a bit dropped, a move down and a ban each
        // publish the member's Tenure first, so what they decided stands for every reader.
        let (bed, owner, _m) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Duty", bed.relays.clone(), None).await.unwrap();
        activate_roles_v2(&bed.relay, &community, 0).await.unwrap();
        follow_control(&bed.relay, &community).await.unwrap();
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let bits = Permissions::MANAGE_ROLES | Permissions::BAN | Permissions::MANAGE_CHANNELS;
        let members: Vec<Keys> = (0..5).map(|_| Keys::generate()).collect();
        let mut roles = Vec::new();
        for (i, k) in members.iter().enumerate() {
            let rid = create_role_v2(&bed.relay, &held(), &format!("Admin {i}"), 0, bits).await.unwrap();
            set_member_roles(&bed.relay, &held(), &k.public_key(), vec![rid.clone()]).await.unwrap();
            roles.push(rid);
        }
        follow_control(&bed.relay, &held()).await.unwrap();
        let made: Vec<String> = ["c1", "c2", "c3", "c4", "c5"].iter().map(|p| p.repeat(32)).collect();
        for (k, id) in members.iter().zip(&made) {
            publish_role_v2(&bed.relay, &held(), k, &role_v2(id, "Made", "z", 0), 1).await;
        }
        follow_control(&bed.relay, &held()).await.unwrap();
        let granted = Keys::generate();
        publish_grant(&bed.relay, &held(), &members[4], &granted.public_key(), vec![made[4].clone()], 1).await;
        let ch = community.channels[0].id;
        let v1 = head_hash_on_relay(&bed.relay, &held(), &ch.0).await;
        publish_fork(&[&bed.relay], &held(), &members[4], vsk::CHANNEL_METADATA, &ch.0, 2, v1, &channel_meta_json("by the banned"), None).await;
        follow_control(&bed.relay, &held()).await.unwrap();
        let standing = |at: &CommunityV2, eds: &[ParsedEdition]| {
            let f = fold_authority(at, eds, &Floors::default());
            made.iter().map(|id| f.roles.role(id).is_some()).collect::<Vec<bool>>()
        };
        assert_eq!(standing(&held(), &fetch_control(&bed.relay, &held()).await), vec![true; 5]);

        set_member_roles(&bed.relay, &held(), &members[0].public_key(), vec![]).await.unwrap();
        delete_role_v2(&bed.relay, &held(), &roles[1]).await.unwrap();
        edit_role_v2(&bed.relay, &held(), &roles[2], "Admin 2", 0, Permissions::BAN, false, false).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        move_role_v2(&bed.relay, &held(), &roles[3], usize::MAX).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        let eds = fetch_control(&bed.relay, &held()).await;
        let f = fold_authority(&held(), &eds, &Floors::default());
        for (k, r) in members.iter().zip(&roles).take(4) {
            assert!(!f.roles.permissions_above(&k.public_key().to_hex(), u32::MAX).contains(Permissions::MANAGE_ROLES) || f.roles.role(r).is_some_and(|x| x.rank.as_deref() > Some("z")), "each reduction took");
        }
        assert_eq!(standing(&held(), &eds), vec![true; 5], "and each member's role stands on its Tenure");

        // A ban re-founds the plane: the Tenures and what they seal are carried across.
        set_members_banned(&bed.relay, held().id(), &[members[4].public_key()], true).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        let now = held();
        assert_ne!(now.root_epoch, community.root_epoch, "the ban re-founded");
        let eds = fetch_control(&bed.relay, &now).await;
        assert!(fold_authority(&now, &eds, &Floors::default()).banned.contains(&members[4].public_key().to_hex()));
        assert_eq!(standing(&now, &eds), vec![true; 5], "the banned admin's role stands too");
        let f = fold_authority(&now, &eds, &Floors::default());
        assert!(f.roles.roles_of(&granted.public_key().to_hex()).any(|r| r.role_id == made[4]), "so does their Grant");
        let fold = apply_control_fold(&now, &eds, &Floors::default(), &f);
        assert_eq!(fold.updated.as_ref().unwrap_or(&now).channel(&ch).unwrap().name, "by the banned", "and their channel edit");
        // This device's own read, on the floors it holds, agrees.
        let cached = crate::db::community::get_community_roles(&crate::simd::hex::bytes_to_hex_32(&now.id().0)).unwrap();
        assert!(made.iter().all(|id| cached.role(id).is_some()), "the followed roster keeps every sealed role");
    }

    #[tokio::test]
    async fn a_reduction_its_writer_cant_seal_waits_but_a_ban_does_not() {
        // A role edit that would drop decisions the writer couldn't have made is refused; a
        // removal goes ahead, sealing what the writer can.
        let (bed, owner, _m) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Limits", bed.relays.clone(), None).await.unwrap();
        activate_roles_v2(&bed.relay, &community, 0).await.unwrap();
        follow_control(&bed.relay, &community).await.unwrap();
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let moderator = Keys::generate();
        let (target, kicked) = (Keys::generate(), Keys::generate());
        let mr = Permissions::MANAGE_ROLES;
        let top = create_role_v2(&bed.relay, &held(), "Moderator", 0, mr | Permissions::BAN | Permissions::KICK).await.unwrap();
        let below = create_role_v2(&bed.relay, &held(), "Channels", 0, mr | Permissions::MANAGE_CHANNELS).await.unwrap();
        set_member_roles(&bed.relay, &held(), &moderator.public_key(), vec![top]).await.unwrap();
        for k in [&target, &kicked] {
            set_member_roles(&bed.relay, &held(), &k.public_key(), vec![below.clone()]).await.unwrap();
        }
        follow_control(&bed.relay, &held()).await.unwrap();
        let (made, made_kicked) = ("d1".repeat(32), "d2".repeat(32));
        publish_role_v2(&bed.relay, &held(), &target, &role_v2(&made, "Made", "z", 0), 1).await;
        publish_role_v2(&bed.relay, &held(), &kicked, &role_v2(&made_kicked, "Made", "z", 0), 1).await;
        follow_control(&bed.relay, &held()).await.unwrap();

        crate::state::MY_SECRET_KEY.store_from_keys(&moderator, &[]);
        crate::state::set_my_public_key(moderator.public_key());
        let before = fetch_control(&bed.relay, &held()).await.len();
        let err = set_member_roles(&bed.relay, &held(), &target.public_key(), vec![]).await.unwrap_err();
        assert!(err.contains("permissions you don't"), "{err}");
        assert_eq!(fetch_control(&bed.relay, &held()).await.len(), before, "nothing was published");

        kick_member(&bed.relay, &held(), &kicked.public_key()).await.unwrap();
        let f = fold_authority(&held(), &fetch_control(&bed.relay, &held()).await, &Floors::default());
        assert!(f.roles.roles_of(&kicked.public_key().to_hex()).next().is_none(), "the kick stripped");
        assert!(f.roles.role(&made_kicked).is_some(), "and sealed what it could");

        set_members_banned(&bed.relay, held().id(), &[target.public_key()], true).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        let eds = fetch_control(&bed.relay, &held()).await;
        let f = fold_authority(&held(), &eds, &Floors::default());
        assert!(f.banned.contains(&target.public_key().to_hex()), "the ban went ahead");
        assert!(f.roles.role(&made).is_some(), "sealing the bits the moderator holds, which is enough for this role");
    }

    #[tokio::test]
    async fn a_grant_draws_only_on_authority_above_what_it_touches() {
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "GrantSupport", vec!["wss://r".into()], None).await.unwrap();
        let c = Keys::generate();
        let (rtop, rlow, r5) = ("e1".repeat(32), "e2".repeat(32), "e3".repeat(32));
        // C ranks at 2, but holds MANAGE_ROLES only through a role at 8.
        publish_role(&relay, &community, &owner, &role_at(&rtop, "Top", 2, 0), 1).await;
        publish_role(&relay, &community, &owner, &role_at(&rlow, "Low", 8, Permissions::MANAGE_ROLES), 1).await;
        publish_role(&relay, &community, &owner, &role_at(&r5, "Five", 5, Permissions::KICK), 1).await;
        publish_grant(&relay, &community, &owner, &c.public_key(), vec![rtop.clone(), rlow.clone()], 1).await;
        let (m1, m2) = (Keys::generate().public_key(), Keys::generate().public_key());
        publish_grant(&relay, &community, &c, &m1, vec![r5.clone()], 1).await;
        // Beneath 8 the same authority is enough.
        let r9 = "e4".repeat(32);
        publish_role(&relay, &community, &owner, &role_at(&r9, "Nine", 9, 0), 1).await;
        publish_grant(&relay, &community, &c, &m2, vec![r9.clone()], 1).await;
        // And nobody but the owner touches the owner's own grant.
        publish_grant(&relay, &community, &c, &owner.public_key(), vec![r9.clone()], 1).await;

        // Nor anyone their own grant: a manager taking a lower role that bans would gain BAN.
        let mgr = Keys::generate();
        let (rmgr, rban) = ("e5".repeat(32), "e6".repeat(32));
        publish_role(&relay, &community, &owner, &role_at(&rmgr, "Mgr", 3, Permissions::MANAGE_ROLES), 1).await;
        publish_role(&relay, &community, &owner, &role_at(&rban, "Ban", 7, Permissions::BAN), 1).await;
        publish_grant(&relay, &community, &owner, &mgr.public_key(), vec![rmgr.clone()], 1).await;
        publish_grant(&relay, &community, &mgr, &mgr.public_key(), vec![rmgr.clone(), rban.clone()], 2).await;

        let a = fold_authority(&community, &fetch_control(&relay, &community).await, &load_floors(&community));
        assert!(!a.roles.has_permission(&mgr.public_key().to_hex(), Permissions::BAN), "a self-grant confers nothing");
        assert!(a.roles.roles_of(&m1.to_hex()).next().is_none(), "MANAGE_ROLES from a role beneath 5 can't grant at 5");
        assert!(a.roles.roles_of(&m2.to_hex()).any(|r| r.role_id == r9), "it can beneath 8");
        assert!(a.roles.roles_of(&owner.public_key().to_hex()).next().is_none(), "the owner is never a target");
    }

    #[tokio::test]
    async fn a_refused_channel_head_falls_back_only_on_a_complete_fold() {
        let (_tmp, _guard, owner) = init_test_db();
        let full = MemoryRelay::new();
        let (community, admin) = with_admin(&full, "ChannelFallback", &owner, Permissions::MANAGE_CHANNELS).await;
        let thin = MemoryRelay::new();
        mirror_control(&full, &thin, &community).await;
        // A role only the full relay serves: floored, so a thin read is incomplete.
        publish_role(&full, &community, &owner, &role_at(&"f9".repeat(32), "Kept", 9, 0), 1).await;
        let ch = community.channels[0].id;
        let v1 = head_hash_on_relay(&full, &community, &ch.0).await;
        publish_fork(&[&full, &thin], &community, &admin, vsk::CHANNEL_METADATA, &ch.0, 2, v1, &channel_meta_json("admin-name"), None).await;
        follow_control(&full, &community).await.unwrap();
        assert_eq!(floor_of(&community, &ch.0).0, 2);

        // The owner strips the admin on both relays: the v2 head is now refused.
        let geid = crate::community::v2::derive::grant_locator(community.id(), &admin.public_key().to_bytes());
        let gv1 = head_hash_on_relay(&full, &community, &geid).await;
        let strip = crate::community::v2::roles::grant_content_json_with_wrap(&MemberGrant { member: admin.public_key().to_hex(), role_ids: vec![] }, None).unwrap();
        publish_fork(&[&full, &thin], &community, &owner, vsk::GRANT, &geid, 2, gv1, &strip, None).await;

        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        forget_held(&held);
        follow_control(&thin, &held).await.unwrap();
        assert_eq!(floor_of(&community, &ch.0).0, 2, "an incomplete read never moves a floor down");
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let updated = follow_control(&full, &held).await.unwrap().updated.expect("the refused head yields");
        assert_eq!(updated.channel(&ch).unwrap().name, "general", "back to the newest admitted edition");
        assert_eq!(floor_of(&community, &ch.0).0, 1);
    }

    #[tokio::test]
    async fn the_role_editor_refuses_exactly_what_readers_would_drop() {
        let (bed, owner, mgr) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "SubsetEditor", bed.relays.clone(), None).await.unwrap();
        let rmgr = "a2".repeat(32);
        publish_role(&bed.relay, &community, &owner.keys, &role_at(&rmgr, "Mgr", 2, Permissions::MANAGE_ROLES | Permissions::KICK), 1).await;
        publish_grant(&bed.relay, &community, &owner.keys, &mgr.keys.public_key(), vec![rmgr], 1).await;
        let guarded = create_role(&bed.relay, &community, "Guarded", 0, Permissions::BAN, RoleScope::Server).await.unwrap();
        let stripped = create_role(&bed.relay, &community, "Stripped", 0, Permissions::BAN | Permissions::KICK, RoleScope::Server).await.unwrap();
        let k1 = create_role(&bed.relay, &community, "K1", 0, Permissions::KICK, RoleScope::Server).await.unwrap();
        let k2 = create_role(&bed.relay, &community, "K2", 0, Permissions::KICK, RoleScope::Server).await.unwrap();
        follow_control(&bed.relay, &community).await.unwrap();

        bed.swap_to(&mgr);
        crate::db::community::save_community_v2(&community).unwrap();
        follow_control(&bed.relay, &community).await.unwrap();
        let pos = |v: &AuthorityView, id: &str| folded_role(v, id).position;
        let before = fetch_authority(&bed.relay, &community).await;

        let err = create_role(&bed.relay, &community, "Mine", 0, Permissions::BAN, RoleScope::Server).await.unwrap_err();
        assert!(err.contains("don't hold"), "{err}");
        let err = edit_role(&bed.relay, &community, &guarded, "Renamed", 0, Permissions::BAN, RoleScope::Server).await.unwrap_err();
        assert!(err.contains("don't hold"), "keeping a bit you lack is carrying it: {err}");
        // Stripping a bit you lack leaves a role you could have made: readers admit it.
        edit_role(&bed.relay, &community, &stripped, "Stripped", 0, Permissions::KICK, RoleScope::Server).await.expect("a strip of what you lack");
        let after_strip = fetch_authority(&bed.relay, &community).await;
        assert_eq!(folded_role(&after_strip, &stripped).permissions.0, Permissions::KICK, "and the fold seats it");

        // Moving the guarded role is refused, and nothing else moved on the way.
        let err = reorder_roles(&bed.relay, &community, &[k1.clone(), guarded.clone(), stripped.clone(), k2.clone()]).await.unwrap_err();
        assert!(err.contains("Guarded"), "{err}");
        let mid = fetch_authority(&bed.relay, &community).await;
        for id in [&guarded, &stripped, &k1, &k2] {
            assert_eq!(pos(&mid, id), pos(&after_strip, id), "a refused reorder publishes nothing");
        }
        // Reordering roles of held bits beneath it works.
        let moved = reorder_roles(&bed.relay, &community, &[guarded.clone(), stripped.clone(), k2.clone(), k1.clone()]).await.expect("beneath the guarded role");
        assert!(moved > 0);
        let after = fetch_authority(&bed.relay, &community).await;
        assert!(pos(&after, &k2) < pos(&after, &k1));
        assert_eq!(pos(&after, &guarded), pos(&before, &guarded));

        // The editor's view marks exactly the role it can't touch.
        follow_control(&bed.relay, &community).await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let view = crate::VectorCore.community_roles_view(&cid_hex).unwrap();
        let manageable = |id: &str| view["roles"].as_array().unwrap().iter().find(|r| r["role_id"] == id).map(|r| r["manageable"] == true);
        assert_eq!(manageable(&guarded), Some(false));
        assert_eq!(manageable(&k1), Some(true));
    }

    #[tokio::test]
    async fn a_mid_rank_admin_cannot_demote_a_role_that_outranks_them() {
        // CORD-04 §2 rank inversion. Minting at a position you outrank is
        // necessary but NOT sufficient: an edition replaces the entity, so a
        // gate that only reads the NEW position lets an admin at position 5
        // rewrite the position-1 role to position 9. Every check passes (9 is
        // beneath them), and the role that outranked them — plus everyone
        // holding it — is now beneath them.
        let (bed, owner, attacker) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Ranks", bed.relays.clone(), None).await.unwrap();

        // A senior role at position 1, and a mid role at position 5 the attacker holds.
        let senior = "a1".repeat(32);
        let mid = "a5".repeat(32);
        publish_role(&bed.relay, &community, &owner.keys,
            &Role { role_id: senior.clone(), name: "Senior".into(), position: 1, permissions: Permissions(Permissions::BAN), scope: RoleScope::Server, color: 0, rank: None, display: false, mentionable: false, extra: Default::default() }, 1).await;
        publish_role(&bed.relay, &community, &owner.keys,
            &Role { role_id: mid.clone(), name: "Mid".into(), position: 5, permissions: Permissions(Permissions::MANAGE_ROLES | Permissions::BAN), scope: RoleScope::Server, color: 0, rank: None, display: false, mentionable: false, extra: Default::default() }, 1).await;
        publish_grant(&bed.relay, &community, &owner.keys, &attacker.keys.public_key(), vec![mid.clone()], 1).await;

        // The attacker republishes the SENIOR role, dropping it beneath themselves.
        publish_role(&bed.relay, &community, &attacker.keys,
            &Role { role_id: senior.clone(), name: "Senior".into(), position: 9, permissions: Permissions(Permissions::BAN), scope: RoleScope::Server, color: 0, rank: None, display: false, mentionable: false, extra: Default::default() }, 2).await;

        let authority = fetch_authority(&bed.relay, &community).await;
        let folded_senior = authority.roles.role(&senior).expect("the senior role survives the fold");
        assert_eq!(
            folded_senior.position, 1,
            "a role may only be repositioned by someone who outranks where it STOOD, not just where it lands",
        );
    }

    #[tokio::test]
    async fn a_non_owner_admins_edition_cites_its_grant_and_the_owners_does_not() {
        // CORD-04 §5. Armada's reader REQUIRES this on every non-owner control
        // edition (`citationOk`: "a non-owner action MUST cite its grant"), so
        // an uncited Vector admin's ban/role/channel edit was silently dropped
        // by every Armada client — only the owner's actions crossed. The
        // citation must name the actor's OWN grant coordinate, at the version
        // and edition hash the verifier can match against a grant it holds.
        let (bed, owner, admin) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Cited", bed.relays.clone(), None).await.unwrap();
        let rid = "c1".repeat(32);
        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN | Permissions::MANAGE_METADATA), 1).await;
        publish_grant(&bed.relay, &community, &owner.keys, &admin.keys.public_key(), vec![rid], 1).await;

        // The owner's own edition carries NO citation: their rank is the id.
        let owner_meta = control::CommunityMetadata { name: "By Owner".into(), relays: community.relays.clone(), ..Default::default() };
        edit_community_metadata(&bed.relay, &community, &owner_meta).await.unwrap();
        let owner_ed = fetch_control(&bed.relay, &community).await.into_iter()
            .filter(|e| e.author == owner.keys.public_key() && e.vsk == vsk::COMMUNITY_METADATA)
            .max_by_key(|e| e.version).expect("the owner's metadata edition");
        assert!(owner_ed.authority.is_none(), "the owner cites nothing — rank comes from the community id");

        // The admin JOINS and folds — the citation names the grant head their own
        // client has actually synced, so the fold must have persisted it.
        let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
        let bundle_json = serde_json::to_string(&bundle).unwrap();
        bed.swap_to(&admin);
        let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
        let _ = follow_control(&bed.relay, &joined).await;
        let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
        set_banlist(&bed.relay, &joined, &["ee".repeat(32)]).await.unwrap();

        let ban_ed = fetch_control(&bed.relay, &joined).await.into_iter()
            .find(|e| e.author == admin.keys.public_key() && e.vsk == vsk::BANLIST)
            .expect("the admin's banlist edition");
        let cite = ban_ed.authority.as_ref().expect("a non-owner MUST cite its grant");
        assert_eq!(
            cite.entity_id,
            crate::community::v2::derive::grant_locator(community.id(), &admin.keys.public_key().to_bytes()),
            "the citation must name the ACTOR'S OWN grant coordinate",
        );
        assert!(cite.version >= 1, "pinned to a real grant version");
    }

    #[tokio::test]
    async fn a_folded_metadata_edition_cannot_push_the_relay_set_past_the_cap() {
        // `cap_relays` is the truncate-on-read invariant everywhere else, and the
        // fold is a boundary like any other: MANAGE_METADATA makes an editor
        // authorized, not trusted. An oversize list costs every member a fan-out
        // per publish and the slowest of N per fetch — and Armada caps at 5, so
        // an uncapped fold also splits the two clients' operative sets.
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Fanout", vec!["wss://a".into()], None).await.unwrap();

        let many: Vec<String> = (0..30).map(|i| format!("wss://r{i}")).collect();
        let meta = control::CommunityMetadata { name: "Fanout".into(), relays: many, ..Default::default() };
        edit_community_metadata(&relay, &community, &meta).await.unwrap();

        let updated = follow_control(&relay, &community).await.unwrap().updated
            .expect("the metadata edition is folded");
        assert_eq!(
            updated.relays.len(),
            crate::community::MAX_COMMUNITY_RELAYS,
            "a folded relay list must be truncated, never adopted whole",
        );

        // …and the fold must SETTLE: comparing an oversize edition against the
        // capped working set would never be equal, so every later fold would
        // report a change and re-save forever.
        let again = follow_control(&relay, &updated).await.unwrap().updated;
        assert!(again.is_none(), "re-folding the same oversize edition must be a no-op");
    }

    #[tokio::test]
    async fn adopting_a_rotation_writes_no_registry_where_i_never_minted() {
        // One Invite List spans every community, so "I hold links" must never be
        // read as "I hold links HERE". A member with links elsewhere adopting a
        // rotation would otherwise publish an empty Registry edition into this
        // community — a control-plane write and a version bump on a coordinate
        // they never owned, every rotation, forever.
        let (bed, owner, me) = TestBed::new();
        bed.swap_to(&owner);
        let host = create_community(&bed.relay, "Host", bed.relays.clone(), None).await.unwrap();
        let rid = "b2".repeat(32);
        publish_role(&bed.relay, &host, &owner.keys, &admin_role(&rid, Permissions::BAN), 1).await;
        publish_grant(&bed.relay, &host, &owner.keys, &me.keys.public_key(), vec![rid], 1).await;

        let bundle = bundle_of(&host, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
        let bundle_json = serde_json::to_string(&bundle).unwrap();
        bed.swap_to(&me);
        let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
        let _ = follow_control(&bed.relay, &joined).await;
        let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();

        // My only link lives in a DIFFERENT community — one I own, since minting
        // is offer-gated on CREATE_INVITE.
        let elsewhere = create_community(&bed.relay, "Elsewhere", bed.relays.clone(), None).await.unwrap();
        mint_public_link(&bed.relay, &elsewhere, "https://other", None, None).await.unwrap();

        let before = bed.relay.stored_count();
        let new_root = [0xE1; 32];
        publish_base_rotation(&bed.relay, &joined, &owner.keys, &[owner.keys.public_key(), me.keys.public_key()], &new_root, &joined.community_root).await;
        let rotation_events = bed.relay.stored_count() - before;

        let after_adopt = bed.relay.stored_count();
        follow_rekeys(&bed.relay, &joined, &crate::db::current_session()).await.unwrap();
        assert_eq!(
            bed.relay.stored_count(),
            after_adopt,
            "adopting a rotation must publish NOTHING when I minted no links here",
        );
        assert!(rotation_events > 0, "the rotation itself did publish (guards the counter)");
    }

    #[tokio::test]
    async fn an_expired_link_stops_keeping_the_community_public() {
        // CORD-05 §1/§5: expiry is the one way a link dies with no user action.
        // A joiner is refused by `InviteBundle::expired`, so leaving the link in
        // the Registry states a door that isn't there — the aggregate never
        // empties and the community reads Public forever, silently inverting
        // every gate that hangs off that reading.
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Lapsing", vec!["wss://r".into()], None).await.unwrap();

        // A link that lapsed a minute ago.
        let past = now_ms() - 60_000;
        mint_public_link(&relay, &community, "https://x", Some(past), None).await.unwrap();
        assert!(
            !community_is_public(&relay, &community).await,
            "an already-expired link must never read as a live door",
        );

        // …and one that hasn't, to prove the filter isn't just dropping everything.
        mint_public_link(&relay, &community, "https://y", Some(now_ms() + 600_000), None).await.unwrap();
        assert!(community_is_public(&relay, &community).await, "an unexpired link is still live");
    }

    #[tokio::test]
    async fn minting_a_link_makes_the_community_public_and_revoke_makes_it_private() {
        // CORD-05 §5: the Registry is the Public/Private source of truth. Minting a
        // link publishes it (Public); retiring the last link empties it (Private).
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Invitable", vec!["wss://r".into()], None).await.unwrap();
        assert!(!community_is_public(&relay, &community).await, "a fresh community is Private");

        let minted = mint_public_link(&relay, &community, "https://x", None, None).await.unwrap();
        assert!(community_is_public(&relay, &community).await, "a live link makes it Public");
        let list = fetch_invite_list(&relay, &community.relays).await.unwrap().expect("the 13303 list was published");
        assert_eq!(list.entries.len(), 1, "the minted link is recorded across devices");

        let token_hex = crate::simd::hex::bytes_to_hex_16(&minted.token);
        revoke_public_link(&relay, &community, &token_hex).await.unwrap();
        assert!(!community_is_public(&relay, &community).await, "retiring the last link makes it Private again");
        let after = fetch_invite_list(&relay, &community.relays).await.unwrap().unwrap();
        assert!(after.entries.is_empty() && after.tombstones.len() == 1, "the link is tombstoned in the invite list");
    }

    #[tokio::test]
    async fn the_registry_is_cached_locally_so_public_private_is_a_sync_read() {
        // Every caller reads the `invite_registry` COLUMN, never the async fold. v2
        // published the Registry to the plane but never mirrored it locally, so every
        // v2 community read Private no matter how many live links it had.
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Cached", vec!["wss://r".into()], None).await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let cached = || crate::db::community::get_community_invite_registry(&cid_hex).unwrap();
        // The per-creator split is a SEPARATE table, and it drives the "first link flips
        // the community Public" confirm — an empty one re-asks on every later link.
        let per_creator = || crate::db::community::get_invite_link_sets(&cid_hex).unwrap();
        assert!(cached().is_empty(), "a fresh community caches an empty registry");
        assert!(per_creator().is_empty(), "…and no per-creator sets");

        let minted = mint_public_link(&relay, &community, "https://x", None, None).await.unwrap();
        assert!(!cached().is_empty(), "minting caches the registry, so the UI reads Public without folding");
        let sets = per_creator();
        assert_eq!(sets.len(), 1, "the minting creator gets a set");
        assert_eq!(sets[0].locators.len(), 1, "carrying exactly their one live link");

        // Both caches must SHRINK too — a union-only mirror would strand it Public.
        let token_hex = crate::simd::hex::bytes_to_hex_16(&minted.token);
        revoke_public_link(&relay, &community, &token_hex).await.unwrap();
        assert!(cached().is_empty(), "retiring the last link empties the cache back to Private");
        assert!(per_creator().is_empty(), "…and clears the per-creator sets");
    }

    #[tokio::test]
    async fn a_rogue_registry_fork_cannot_retire_the_owners_live_link() {
        // Registries are coordinate-bound to their creator, but `fold_head` picks an
        // equal-version winner AUTHOR-BLIND, by lowest inner id — and an author grinds
        // that freely by varying content. Folding before authorising would let any
        // member occupy the owner's registry head, fail the authority check, and drop
        // the whole registry: a live invite link silently retired, flipping the
        // community to Private and steering a moderator into the wrong ban remedy.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Forked", vec!["wss://r".into()], None).await.unwrap();
        mint_public_link(&relay, &community, "https://x", None, None).await.unwrap();
        assert!(community_is_public(&relay, &community).await, "a live link makes it Public");

        let cid = community.id();
        let control = control::ControlPlane::of(&community).write_group().unwrap();
        let eid = crate::community::v2::derive::invite_links_locator(cid, &owner.public_key().to_bytes());

        let query = Query {
            kinds: vec![stream::KIND_WRAP],
            authors: vec![control.pk_hex()],
            limit: Some(FOLLOW_PAGE),
            ..Default::default()
        };
        let wraps = relay.fetch(&query, &community.relays).await.unwrap();
        let target = wraps
            .iter()
            .filter_map(|w| control::open_control_edition(w, &control).ok().map(|(e, _)| e))
            .filter(|e| e.entity_id == eid)
            .max_by_key(|e| e.version)
            .expect("the owner published a registry");

        // Grind a same-version fork under the owner's coordinate that OUTRANKS the
        // real head on the tiebreak (~2 tries against a uniform id).
        let rogue = Keys::generate();
        let mut planted = false;
        for n in 0..4_000u64 {
            let content = format!("[{{\"token\":\"{n:032x}\",\"url\":\"https://evil\",\"expires_at\":0}}]");
            let rumor = control::build_edition_rumor(
                rogue.public_key(),
                vsk::INVITE_LINKS,
                &eid,
                target.version,
                target.prev_hash.as_ref(),
                &content,
                9_000,
                None,
            );
            let (w, _) = control::seal_control_edition(&rumor, &control, &rogue, Timestamp::from_secs(9_000)).unwrap();
            let (ed, _) = control::open_control_edition(&w, &control).unwrap();
            if ed.inner_id < target.inner_id {
                relay.publish(&w, &community.relays).await.unwrap();
                planted = true;
                break;
            }
        }
        assert!(planted, "the test needs a fork that wins the tiebreak");

        assert!(
            community_is_public(&relay, &community).await,
            "an unauthorised fork must not retire the owner's live link"
        );
    }

    #[tokio::test]
    async fn a_registry_from_a_non_create_invite_holder_does_not_make_it_public() {
        // The CREATE_INVITE gate: a rogue publishing a registry can't fake Public.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Gated", vec!["wss://r".into()], None).await.unwrap();
        let rogue = Keys::generate();
        // Rogue publishes a registry edition at THEIR coordinate with a fake signer.
        let eid = crate::community::v2::derive::invite_links_locator(community.id(), &rogue.public_key().to_bytes());
        let content = crate::community::v2::invite::build_registry_content(&[Keys::generate().public_key()]);
        let group = control::ControlPlane::of(&community).write_group().unwrap();
        let rumor = control::build_edition_rumor(rogue.public_key(), vsk::INVITE_LINKS, &eid, 1, None, &content, 1_000, None);
        let (wrap, _) = control::seal_control_edition(&rumor, &group, &rogue, Timestamp::from_secs(1_000)).unwrap();
        relay.publish(&wrap, &community.relays).await.unwrap();
        let _ = owner;
        assert!(!community_is_public(&relay, &community).await, "a non-CREATE_INVITE registry is ignored");
    }

    #[tokio::test]
    async fn full_lifecycle_e2e() {
        // The whole stack end to end across two accounts: create -> Public link ->
        // owner grants an admin -> member joins + reads history -> admin edits metadata
        // (authorized fold) -> owner bans the member (CORD-04 §6: banlist + strip +
        // Refounding) -> the banned member is severed AND stays banned across the new
        // epoch -> pre-ban history still reads -> owner dissolves -> sealed.
        let (bed, owner, member) = TestBed::new();

        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Lifecycle", bed.relays.clone(), None).await.unwrap();
        let general = community.channels[0].id;
        send_message(&bed.relay, &community, &general, "owner: welcome").await.unwrap();

        // Public link → the community reads Public.
        let _minted = mint_public_link(&bed.relay, &community, "https://x", None, None).await.unwrap();
        assert!(community_is_public(&bed.relay, &community).await, "a live link makes it Public");

        // Owner defines + grants an Admin role (MANAGE_METADATA among the bits).
        let rid = "aa".repeat(32);
        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::ADMIN_ALL), 1).await;
        publish_grant(&bed.relay, &community, &owner.keys, &member.keys.public_key(), vec![rid], 1).await;

        // Member joins from the bundle + reads the owner's message.
        let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
        let bundle_json = serde_json::to_string(&bundle).unwrap();
        bed.swap_to(&member);
        let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
        assert_eq!(texts_in(&bed.relay, &joined, &general).await, vec!["owner: welcome"]);
        // The admin folds first — adopting the staff write key their Grant
        // delivered (CORD-04 §3) — then renames the community.
        let _ = follow_control(&bed.relay, &joined).await;
        let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
        assert!(joined.control_root.is_some(), "the Grant's control_wrap was adopted on fold");
        publish_community_meta(&bed.relay, &joined, &member.keys, "Lifecycle Renamed", 2).await;

        // Owner follows: the admin's rename folds (authorized).
        bed.swap_to(&owner);
        let updated = follow_control(&bed.relay, &community).await.unwrap().updated.expect("the admin edit folds");
        assert_eq!(updated.name, "Lifecycle Renamed", "an authorized admin's metadata edit is honored");

        // Ban the member (the three-removal composition, in order).
        set_banlist(&bed.relay, &updated, &[member.keys.public_key().to_hex()]).await.unwrap();
        grant_roles(&bed.relay, &updated, &member.keys.public_key(), vec![]).await.unwrap();
        let refounded = refound_community(&bed.relay, &updated, &[member.keys.public_key()]).await.unwrap();
        assert_eq!(refounded.root_epoch, Epoch(1), "the ban rolled the root");
        // The ban survives the Refounding (the banlist head compacted forward).
        let post = fold_authority(&refounded, &fetch_control(&bed.relay, &refounded).await, &load_floors(&refounded));
        assert!(post.banned.contains(&member.keys.public_key().to_hex()), "the ban survives the re-founding");
        // Pre-ban history still reads across the new epoch.
        assert!(
            all_texts_in(&bed.relay, &refounded, &general).await.contains(&"owner: welcome".to_string()),
            "pre-refounding history stays reachable by paging"
        );

        // The banned member's rekey-follow concludes they're severed. Guard captured AFTER
        // the swap (the harness swap bumps the generation like production).
        bed.swap_to(&member);
        let session = crate::db::current_session();
        let follow = follow_rekeys(&bed.relay, &joined, &session).await.unwrap();
        assert!(follow.self_removed, "the banned member is cryptographically cut");

        // Owner dissolves → sealed.
        bed.swap_to(&owner);
        dissolve_community(&bed.relay, &refounded).await.unwrap();
        assert!(crate::db::community::load_community_v2(community.id()).unwrap().unwrap().dissolved, "the community is sealed");
    }

    /// The deep two-account e2e the way a real deployment runs: owner (A) + member (B)
    /// over one shared relay, create → channels (public + private) → converse both ways →
    /// persist (get_messages-level) → react/edit/delete → moderate (ban/unban) → dissolve.
    /// Every account, community, channel, and action is LOGGED (run with --nocapture) so it
    /// doubles as a reference transcript and a re-runnable regression.
    #[tokio::test]
    async fn a_forged_edition_cannot_suppress_a_role_across_a_refounding() {
        // A member forges a higher-version role edition at the admin coordinate before a
        // refounding. The compaction must carry the AUTHORIZED floor head, not the
        // author-blind version tip — else the forgery is re-anchored, honest folders drop
        // it, and the admin role vanishes at the new epoch (silent suppression).
        let (bed, owner, member) = TestBed::new();
        let attacker = Keys::generate();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "NoSuppress", bed.relays.clone(), None).await.unwrap();
        let rid = crate::simd::hex::bytes_to_hex_32(&[0xa1; 32]);
        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::ADMIN_ALL), 1).await;
        publish_grant(&bed.relay, &community, &owner.keys, &member.keys.public_key(), vec![rid.clone()], 1).await;
        // Owner folds → the authorized role/grant heads are floored.
        follow_control(&bed.relay, &community).await.unwrap().updated;
        assert!(fetch_authority(&bed.relay, &community).await.roles.is_admin(&member.keys.public_key().to_hex()), "member is admin pre-attack");

        // The attacker (a non-owner) forges v2 of the admin role, chaining onto v1.
        publish_role(&bed.relay, &community, &attacker, &Role { role_id: rid.clone(), name: "pwn".into(), position: 1, permissions: Permissions(0), scope: RoleScope::Server, color: 0, rank: None, display: false, mentionable: false, extra: Default::default() }, 2).await;

        // Owner refounds (keeping everyone).
        let refounded = refound_community(&bed.relay, &community, &[]).await.unwrap();
        assert_eq!(refounded.root_epoch, Epoch(1), "root rolled");

        // Post-refound, the admin role SURVIVES (the authorized floor head was carried).
        let post = fold_authority(&refounded, &fetch_control(&bed.relay, &refounded).await, &load_floors(&refounded));
        assert!(post.roles.is_admin(&member.keys.public_key().to_hex()), "the admin role survives the refounding despite the forgery");
    }

    #[tokio::test]
    async fn memberlist_survives_a_refounding_via_the_snapshot() {
        // A silent survivor (didn't re-post at the new epoch) must stay in the memberlist
        // after a refounding — the owner's 3312 snapshot re-seeds them (CORD-02 §5).
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Snapshot", bed.relays.clone(), None).await.unwrap();

        // Member joins (a Guestbook Join at epoch 0).
        let bundle = serde_json::to_string(&bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None)).unwrap();
        bed.swap_to(&member);
        accept_parked_invite(&bed.relay, &bundle, None).await.unwrap();
        bed.swap_to(&owner);
        assert!(memberlist(&bed.relay, &community).await.unwrap().contains(&member.keys.public_key()), "member present pre-refound");

        // Owner refounds keeping everyone (removed = []); survivors are snapshotted to epoch 1.
        let refounded = refound_community(&bed.relay, &community, &[]).await.unwrap();
        assert_eq!(refounded.root_epoch, Epoch(1), "the root rolled");

        // The member is STILL a member at epoch 1 purely via the snapshot (never re-posted).
        let members = memberlist(&bed.relay, &refounded).await.unwrap();
        assert!(members.contains(&member.keys.public_key()), "a silent survivor stays a member after the refounding");
        assert!(members.contains(&owner.keys.public_key()), "owner is always a member");
    }

    #[tokio::test]
    async fn e2e_two_accounts_channels_converse_moderate() {
        use crate::community::v2::inbound::{apply_chat_to_state, persist_chat};
        use nostr_sdk::prelude::ToBech32;
        let (bed, a, b) = TestBed::new();
        let (a_npub, b_npub) = (a.keys.public_key().to_bech32().unwrap(), b.keys.public_key().to_bech32().unwrap());
        let (a_hex, b_hex) = (a.keys.public_key().to_hex(), b.keys.public_key().to_hex());
        println!("\n===== Concord v2 deep e2e =====");
        println!("[acct] A (owner)  = {a_npub}");
        println!("[acct] B (member) = {b_npub}");

        // ── A creates the community + a PRIVATE channel + two extra PUBLIC channels ──
        bed.swap_to(&a);
        let mut community = create_community(&bed.relay, "Deep E2E", bed.relays.clone(), None).await.unwrap();
        let general = community.channels[0].id;
        println!("[create] community {} · #general {}", crate::simd::hex::bytes_to_hex_32(&community.id().0), crate::simd::hex::bytes_to_hex_32(&general.0));

        // A PRIVATE channel via the REAL create path: an independent key minted at
        // channel-epoch 1, delivered over the rekey plane (A is the only member yet),
        // then announced (vsk 2) — later carried to B in the join bundle.
        let priv_id = create_private_channel(&bed.relay, &community, "mods").await.unwrap();
        community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let priv_ch = community.channel(&priv_id).unwrap();
        assert!(priv_ch.private && priv_ch.key.is_some() && priv_ch.epoch == Epoch(1), "born-private: keyed at epoch 1");
        println!("[channel] +private #mods {} (native create: key over the rekey plane)", crate::simd::hex::bytes_to_hex_32(&priv_id.0));

        // Two more PUBLIC channels via the real create path.
        let announcements = create_public_channel(&bed.relay, &community, "announcements").await.unwrap();
        community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let random = create_public_channel(&bed.relay, &community, "random").await.unwrap();
        community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        println!("[channel] +public #announcements {} · #random {}", crate::simd::hex::bytes_to_hex_32(&announcements.0), crate::simd::hex::bytes_to_hex_32(&random.0));
        assert_eq!(community.channels.len(), 4, "general + mods + announcements + random");

        // A talks in a few channels.
        let m1 = send_message(&bed.relay, &community, &general, "A: welcome to the deep e2e").await.unwrap();
        send_message(&bed.relay, &community, &announcements, "A: read the rules").await.unwrap();
        send_message(&bed.relay, &community, &priv_id, "A: mods-only channel").await.unwrap();
        println!("[msg] A posted in #general / #announcements / #mods");

        // ── A grants B admin, mints a public link, B joins from the bundle ──
        let admin_rid = crate::simd::hex::bytes_to_hex_32(&[0xa1; 32]);
        publish_role(&bed.relay, &community, &a.keys, &admin_role(&admin_rid, Permissions::ADMIN_ALL), 1).await;
        publish_grant(&bed.relay, &community, &a.keys, &b.keys.public_key(), vec![admin_rid], 1).await;
        let link = mint_public_link(&bed.relay, &community, "https://vectorapp.io", None, None).await.unwrap();
        assert!(community_is_public(&bed.relay, &community).await, "a live link makes it Public");
        println!("[invite] granted B @admin · minted link {}", link.url);

        // A private channel is readable only by granted role-holders (CORD-03), so
        // B is added to its access list before the bundle is minted.
        grant_channel_access(&bed.relay, &community, &priv_id, &b.keys.public_key()).await.unwrap();
        let bundle_json = serde_json::to_string(&bundle_of(&community, BundleAudience::Member(b.keys.public_key()), Some(a.keys.public_key()), None, None)).unwrap();
        bed.swap_to(&b);
        let mut b_view = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
        println!("[join] B joined; sees {} channels", b_view.channels.len());
        assert_eq!(b_view.channels.len(), 4, "B receives all four channels (incl. the private one's key) in the bundle");
        assert!(b_view.channels.iter().any(|c| c.id.0 == priv_id.0 && c.private && c.key.is_some()), "B holds the private channel key");
        assert!(texts_in(&bed.relay, &b_view, &general).await.contains(&"A: welcome to the deep e2e".to_string()), "B reads A's #general history");
        assert!(texts_in(&bed.relay, &b_view, &priv_id).await.contains(&"A: mods-only channel".to_string()), "B reads the PRIVATE channel with the bundle key");
        // B folds the control plane (persisting the roster) — the live worker does
        // this right after any join; B's admin standing gates B's channel ops below.
        if let Some(fresh) = follow_control(&bed.relay, &b_view).await.unwrap().updated {
            b_view = fresh;
        }
        println!("[follow] B folded control (roster persisted: B is @admin)");

        // ── Conversation both ways + persistence (get_messages-level) ──
        send_message(&bed.relay, &b_view, &general, "B: thanks, glad to be here").await.unwrap();
        send_message(&bed.relay, &b_view, &priv_id, "B: mods checking in").await.unwrap();
        println!("[msg] B replied in #general + #mods");
        // Persist B's own #general view into the shared store (what sync/live ingest does)
        // and confirm it reads back via STATE — get_messages parity.
        let my_pk = b.keys.public_key();
        let gh = crate::simd::hex::bytes_to_hex_32(&general.0);
        for f in fetch_channel(&bed.relay, &b_view, &general, 100).await.unwrap() {
            let outcome = { let mut st = crate::state::STATE.lock().await; apply_chat_to_state(&mut st, &f.event, &gh, &my_pk) };
            if let Some(o) = outcome { persist_chat(&gh, &o).await; }
        }
        assert!(crate::db::events::event_exists(&m1).unwrap(), "A's message persisted into B's shared store (get_messages backfill)");
        println!("[persist] #general history persisted into the shared events store");

        // B (admin) reacts to + the author edits/deletes — the chat-op surface.
        send_reaction(&bed.relay, &b_view, &general, &m1, &a_hex, super::super::kind::MESSAGE, "🔥", None).await.unwrap();
        bed.swap_to(&a);
        let m_edit = send_message(&bed.relay, &community, &general, "A: this will be edited").await.unwrap();
        send_edit(&bed.relay, &community, &general, &m_edit, "A: edited!", &[]).await.unwrap();
        let m_del = send_message(&bed.relay, &community, &general, "A: this will be deleted").await.unwrap();
        send_delete(&bed.relay, &community, &general, &m_del, super::super::kind::MESSAGE, None).await.unwrap();
        println!("[ops] reaction + edit + delete round-tripped");

        // ── B creates a channel as admin, A folds it in ──
        bed.swap_to(&b);
        let bugs = create_public_channel(&bed.relay, &b_view, "bug-reports").await.unwrap();
        println!("[channel] B(admin) +public #bug-reports {}", crate::simd::hex::bytes_to_hex_32(&bugs.0));
        bed.swap_to(&a);
        if let Some(updated) = follow_control(&bed.relay, &community).await.unwrap().updated {
            community = updated;
        }
        assert!(community.channels.iter().any(|c| c.id.0 == bugs.0), "A folds in B's authorized new channel");
        println!("[follow] A folded in B's #bug-reports (now {} channels)", community.channels.len());

        // ── A creates a SECOND private channel while B is already a member. B is
        // NOT on its access list, so B learns the channel exists (control-follow,
        // keyless) and gets no key: CORD-03's private channel is readable only by
        // granted role-holders, never by every member. B keys up if and when A
        // grants them the channel's access role and vends the key ──
        let vault = create_private_channel(&bed.relay, &community, "vault").await.unwrap();
        community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        send_message(&bed.relay, &community, &vault, "A: vault is open").await.unwrap();
        println!("[channel] +private #vault {} (B is unentitled — no delivery)", crate::simd::hex::bytes_to_hex_32(&vault.0));
        bed.swap_to(&b);
        let session_b2 = crate::db::current_session();
        if let Some(fresh) = follow_control(&bed.relay, &b_view).await.unwrap().updated {
            b_view = fresh;
        }
        let ch = b_view.channel(&vault).expect("B recorded the announced private channel");
        assert!(ch.private && ch.key.is_none() && ch.epoch == Epoch(0), "B's record is keyless at cursor 0");
        let rf = follow_rekeys(&bed.relay, &b_view, &session_b2).await.unwrap();
        if let Some(fresh) = rf.updated {
            b_view = fresh;
        }
        let ch = b_view.channel(&vault).expect("still recorded");
        assert!(ch.key.is_none(), "an unentitled member is never delivered the key");
        assert!(
            texts_in(&bed.relay, &b_view, &vault).await.is_empty(),
            "and reads nothing from it"
        );
        assert!(
            send_message(&bed.relay, &b_view, &vault, "B: in the vault").await.is_err(),
            "an unentitled member cannot post into the channel either"
        );
        bed.swap_to(&a);
        community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        println!("[private] #vault stayed sealed to the unentitled B (no key, no read, no send)");

        // ── Members ──
        let members = memberlist(&bed.relay, &community).await.unwrap();
        let member_hexes: std::collections::BTreeSet<String> = members.iter().map(|m| m.to_hex()).collect();
        assert!(member_hexes.contains(&a_hex) && member_hexes.contains(&b_hex), "A + B both in the memberlist");
        println!("[members] {} members: A + B present", members.len());

        // ── Moderate: ban B (banlist + strip + refound), verify severance + survival ──
        set_banlist(&bed.relay, &community, &[b_hex.clone()]).await.unwrap();
        grant_roles(&bed.relay, &community, &b.keys.public_key(), vec![]).await.unwrap();
        let refounded = refound_community(&bed.relay, &community, &[b.keys.public_key()]).await.unwrap();
        assert_eq!(refounded.root_epoch, Epoch(1), "the ban rolled the root");
        let post = fold_authority(&refounded, &fetch_control(&bed.relay, &refounded).await, &load_floors(&refounded));
        assert!(post.banned.contains(&b_hex), "the ban survives the refounding");
        assert!(all_texts_in(&bed.relay, &refounded, &general).await.iter().any(|t| t == "A: welcome to the deep e2e"), "pre-ban history pages back across the new epoch");
        assert!(
            all_texts_in(&bed.relay, &refounded, &priv_id).await.iter().any(|t| t == "A: mods-only channel"),
            "PRIVATE history pages back across the channel's own rotation (per-channel multi-epoch archive)"
        );
        println!("[ban] B banned; root rolled to epoch 1; ban survives; pre-ban history intact (public + private)");
        // B concludes it's severed.
        bed.swap_to(&b);
        let session_b3 = crate::db::current_session();
        assert!(follow_rekeys(&bed.relay, &b_view, &session_b3).await.unwrap().self_removed, "B is cryptographically cut by the ban-refound");
        println!("[ban] B's rekey-follow: self_removed = true (severed)");

        // ── Unban: A lifts the ban ──
        bed.swap_to(&a);
        set_banlist(&bed.relay, &refounded, &[]).await.unwrap();
        let after_unban = fold_authority(&refounded, &fetch_control(&bed.relay, &refounded).await, &load_floors(&refounded));
        assert!(!after_unban.banned.contains(&b_hex), "the unban clears B from the banlist");
        println!("[unban] B removed from the banlist (re-invitable)");

        // ── Dissolve ──
        dissolve_community(&bed.relay, &refounded).await.unwrap();
        assert!(crate::db::community::load_community_v2(community.id()).unwrap().unwrap().dissolved, "the community is sealed");
        println!("[dissolve] community sealed (read-only)\n===== e2e PASS =====\n");
    }

    /// The same scenario on a REAL relay with TWO throwaway accounts, off by default. It
    /// LOGS both nsecs (+ every id) so you can inspect the run and RE-RUN against the same
    /// accounts by exporting `VECTOR_E2E_NSEC_A` / `_B`. Set `VECTOR_E2E_LOG=<path>` to also
    /// append the transcript to a file, `VECTOR_E2E_RELAY=<url>` to pick the relay.
    ///   cargo test -p vector-core -- --ignored --nocapture live_e2e_two_accounts
    #[tokio::test]
    #[ignore]
    async fn live_e2e_two_accounts() {
        use nostr_sdk::prelude::ToBech32;

        let relay = std::env::var("VECTOR_E2E_RELAY").unwrap_or_else(|_| "wss://jskitty.com/nostr".to_string());
        let relays = vec![relay.clone()];
        let _g = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
        crate::db::close_database();
        crate::db::clear_id_caches();
        let tmp = tempfile::tempdir().unwrap();
        crate::db::set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());

        // Throwaway (or bring-your-own via env for a re-run against the same accounts).
        let a = std::env::var("VECTOR_E2E_NSEC_A").ok().and_then(|n| Keys::parse(&n).ok()).unwrap_or_else(Keys::generate);
        let b = std::env::var("VECTOR_E2E_NSEC_B").ok().and_then(|n| Keys::parse(&n).ok()).unwrap_or_else(Keys::generate);

        let log = |line: String| {
            println!("{line}");
            if let Ok(p) = std::env::var("VECTOR_E2E_LOG") {
                use std::io::Write;
                if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(&p) {
                    let _ = writeln!(f, "{line}");
                }
            }
        };
        log(format!("===== LIVE Concord v2 e2e on {relay} ====="));
        log(format!("VECTOR_E2E_NSEC_A={}  ({})", a.secret_key().to_bech32().unwrap(), a.public_key().to_bech32().unwrap()));
        log(format!("VECTOR_E2E_NSEC_B={}  ({})", b.secret_key().to_bech32().unwrap(), b.public_key().to_bech32().unwrap()));

        for k in [&a, &b] {
            let npub = k.public_key().to_bech32().unwrap();
            std::fs::create_dir_all(tmp.path().join(&npub)).unwrap();
            crate::db::set_current_account(npub.clone()).unwrap();
            crate::db::init_database(&npub).unwrap();
        }
        // One relay connection: a v2 wrap is pre-signed (ephemeral p-key) and its seal is
        // signed by MY_SECRET_KEY, so publishing needs no per-account client signer.
        let client = crate::nostr_client_builder().build();
        client.add_managed_relay(relay.as_str()).await.ok();
        client.connect().await;
        crate::state::set_nostr_client(client);
        let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(15));
        let become_acct = |k: &Keys| {
            let npub = k.public_key().to_bech32().unwrap();
            crate::db::set_current_account(npub.clone()).unwrap();
            crate::db::init_database(&npub).unwrap();
            crate::db::clear_id_caches();
            crate::state::MY_SECRET_KEY.store_from_keys(k, &[]);
            crate::state::set_my_public_key(k.public_key());
        };
        let settle = || crate::rt::time::sleep(std::time::Duration::from_secs(2));

        // A: create + a channel + grant B admin + mint link.
        become_acct(&a);
        let mut community = create_community(&transport, "Live E2E", relays.clone(), None).await.expect("create");
        let general = community.channels[0].id;
        log(format!("[create] community {} · #general {}", crate::simd::hex::bytes_to_hex_32(&community.id().0), crate::simd::hex::bytes_to_hex_32(&general.0)));
        send_message(&transport, &community, &general, "A: live hello").await.expect("send");
        let ann = create_public_channel(&transport, &community, "announcements").await.expect("channel");
        community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        log(format!("[channel] +public #announcements {}", crate::simd::hex::bytes_to_hex_32(&ann.0)));
        grant_admin(&transport, &community, &b.public_key()).await.expect("grant admin");
        let link = mint_public_link(&transport, &community, "https://vectorapp.io", None, None).await.expect("mint");
        log(format!("[invite] B granted @admin · link {}", link.url));
        let bundle_json = serde_json::to_string(&bundle_of(&community, BundleAudience::Link, Some(a.public_key()), None, None)).unwrap();
        settle().await;

        // B: join + read A's history + reply.
        become_acct(&b);
        let b_view = accept_parked_invite(&transport, &bundle_json, None).await.expect("join");
        log(format!("[join] B joined; {} channels", b_view.channels.len()));
        settle().await;
        let page = fetch_channel(&transport, &b_view, &general, 50).await.expect("fetch");
        let seen: Vec<String> = page.iter().map(|f| f.event.opened().rumor.content.clone()).collect();
        log(format!("[read] B sees #general: {seen:?}"));
        assert!(seen.iter().any(|t| t == "A: live hello"), "B reads A's message over the real relay");
        send_message(&transport, &b_view, &general, "B: live reply").await.expect("reply");

        // B posts a NIP-22 kind-1111 THREADED REPLY to A's message (the shape Armada
        // sends) directly onto the chat plane — proving the cross-client thread
        // RECEIVE path works live, not just in the offline fixture.
        let hello = page.iter().find(|f| f.event.opened().rumor.content == "A: live hello").expect("A's message");
        let hello_id = hello.event.opened().rumor_id.to_hex();
        let bkeys = crate::state::MY_SECRET_KEY.to_keys().unwrap();
        let cgroup = channel_group_key(&b_view.community_root, &general, b_view.root_epoch);
        let reply_rumor = chat::build_comment_rumor(bkeys.public_key(), &general, b_view.root_epoch, "B: threaded reply to hello", &hello_id, super::super::kind::MESSAGE, &a.public_key().to_hex(), None, &[], now_ms());
        let (reply_wrap, _) = chat::seal_chat_rumor(&reply_rumor, &cgroup, &bkeys, Timestamp::from_secs(now_ms() / 1000), false).expect("seal 1111");
        transport.publish(&reply_wrap, &b_view.relays).await.expect("publish 1111");
        log("[thread] B published a kind-1111 threaded reply to A's message".to_string());
        settle().await;

        // A reads the thread reply back, rendered inline with A's message as parent.
        become_acct(&a);
        community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let a_page = fetch_channel(&transport, &community, &general, 50).await.expect("A fetch");
        let thread = a_page.iter().find(|f| f.event.opened().rumor.content == "B: threaded reply to hello").expect("A sees the 1111");
        if let chat::ChatEvent::Message { reply_to, opened, .. } = &thread.event {
            assert_eq!(opened.rumor.kind.as_u16(), super::super::kind::COMMENT, "wire kind preserved as 1111");
            assert_eq!(reply_to.as_ref().map(|r| crate::simd::hex::bytes_to_hex_32(&r.id)), Some(hello_id.clone()), "the 1111 renders inline with A's message as parent");
        } else {
            panic!("the 1111 parsed as a Message");
        }
        log("[thread] A read B's threaded reply, parent resolved — cross-client 1111 interop OK".to_string());
        become_acct(&b);
        settle().await;

        // A: create a PRIVATE channel while B is already a member — B is a recipient
        // of the creation delivery, so B keys up from the rekey plane over the real
        // relay (no bundle involved), then the two converse on it.
        become_acct(&a);
        community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let vault = create_private_channel(&transport, &community, "vault").await.expect("private channel");
        community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        send_message(&transport, &community, &vault, "A: vault live").await.expect("vault send");
        log(format!("[channel] +private #vault {} (key delivered over the rekey plane)", crate::simd::hex::bytes_to_hex_32(&vault.0)));
        settle().await;

        become_acct(&b);
        let session_b = crate::db::current_session();
        let mut b_view = crate::db::community::load_community_v2(b_view.id()).unwrap().unwrap();
        if let Some(fresh) = follow_control(&transport, &b_view).await.expect("B control follow").updated {
            b_view = fresh;
        }
        if let Some(fresh) = follow_rekeys(&transport, &b_view, &session_b).await.expect("B rekey follow").updated {
            b_view = fresh;
        }
        let vch = b_view.channel(&vault).expect("B folded the vault");
        assert!(vch.key.is_some() && vch.epoch == Epoch(1), "B adopted the vault key from the live rekey plane");
        let vseen = texts_in(&transport, &b_view, &vault).await;
        log(format!("[read] B sees #vault: {vseen:?}"));
        assert!(vseen.iter().any(|t| t == "A: vault live"), "B reads the private channel with the ADOPTED key");
        send_message(&transport, &b_view, &vault, "B: in the live vault").await.expect("vault reply");
        settle().await;

        become_acct(&a);
        community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        assert!(
            texts_in(&transport, &community, &vault).await.iter().any(|t| t == "B: in the live vault"),
            "A reads B's private reply"
        );
        log("[private] two-way #vault conversation over the live relay".to_string());

        // A: ban B (three-removal) + dissolve.
        set_banlist(&transport, &community, &[b.public_key().to_hex()]).await.expect("banlist");
        grant_roles(&transport, &community, &b.public_key(), vec![]).await.expect("strip");
        let refounded = refound_community(&transport, &community, &[b.public_key()]).await.expect("refound");
        log(format!("[ban] B banned; root → epoch {}", refounded.root_epoch.0));
        settle().await;
        dissolve_community(&transport, &refounded).await.expect("dissolve");
        log("[dissolve] community sealed".to_string());
        log("===== LIVE e2e PASS =====".to_string());
    }

    #[tokio::test]
    async fn an_offline_member_learns_of_a_dissolution_on_catch_up() {
        // The tombstone rides its own public plane, watched live — an OFFLINE
        // member's catch-up must fetch it too, or they follow (and post into) a
        // grave forever.
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Doomed", bed.relays.clone(), None).await.unwrap();
        let general = community.channels[0].id;
        send_direct_invite(&bed.relay, &community, &member.keys.public_key(), None, None).await.unwrap();

        bed.swap_to(&member);
        let invite_wrap = fetch_direct_invite(&bed.relay, &bed.relays, &member.keys.public_key()).await;
        let joined = accept_direct_invite(&bed.relay, &invite_wrap).await.unwrap();

        // The owner dissolves while the member sleeps.
        bed.swap_to(&owner);
        dissolve_community(&bed.relay, &community).await.unwrap();

        // The member's catch-up learns of the death, seals, and refuses to post.
        bed.swap_to(&member);
        let session = crate::db::current_session();
        let follow = follow_rekeys(&bed.relay, &joined, &session).await.unwrap();
        assert!(follow.dissolved, "the catch-up surfaces the tombstone");
        assert!(!follow.self_removed && follow.updated.is_none());
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&joined.id().0);
        assert!(crate::db::community::get_community_dissolved(&cid_hex).unwrap(), "sealed read-only locally");
        let err = send_message(&bed.relay, &joined, &general, "into the void").await.unwrap_err();
        assert!(err.contains("dissolved"), "sends refuse a grave: {err}");
        // Subsequent follows take the local fast path — still dissolved, no churn.
        let again = follow_rekeys(&bed.relay, &joined, &session).await.unwrap();
        assert!(again.dissolved && again.updated.is_none());
    }

    #[tokio::test]
    async fn a_wide_community_survives_refoundings_and_an_offline_member_converges() {
        // Scale stress: MANY private channels, each rotated on every Refounding.
        // A member offline across two refoundings must converge on all of them
        // (the per-channel rotation fan in refound + the follow's channel×root×step
        // loops stay bounded) with every channel's history readable.
        const PRIV_CHANNELS: usize = 6;
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let mut community = create_community(&bed.relay, "Wide", bed.relays.clone(), None).await.unwrap();
        let mut priv_ids = Vec::new();
        for i in 0..PRIV_CHANNELS {
            let id = create_private_channel(&bed.relay, &community, &format!("priv{i}")).await.unwrap();
            community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
            send_message(&bed.relay, &community, &id, &format!("priv{i} epoch0")).await.unwrap();
            priv_ids.push(id);
        }
        // Private channels are readable only by granted role-holders (CORD-03).
        for id in &priv_ids {
            grant_channel_access(&bed.relay, &community, id, &member.keys.public_key()).await.unwrap();
        }
        let bundle_json = serde_json::to_string(&bundle_of(&community, BundleAudience::Member(member.keys.public_key()), Some(owner.keys.public_key()), None, None)).unwrap();

        // Member joins at epoch 0 with all channel keys, then goes offline.
        bed.swap_to(&member);
        let member_view = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
        assert_eq!(member_view.channels.iter().filter(|c| c.private && c.key.is_some()).count(), PRIV_CHANNELS, "joined with all private keys");

        // Two refoundings (each rotates the base + every private channel).
        bed.swap_to(&owner);
        for epoch in 1..=2u64 {
            community = refound_community(&bed.relay, &community, &[]).await.unwrap();
            assert_eq!(community.root_epoch, Epoch(epoch));
            for id in &priv_ids {
                send_message(&bed.relay, &community, id, &format!("{} epoch{epoch}", crate::simd::hex::bytes_to_hex_32(&id.0))).await.unwrap();
            }
        }

        // Member returns: bounded follow to quiescence.
        bed.swap_to(&member);
        let session = crate::db::current_session();
        let mut passes = 0;
        loop {
            passes += 1;
            assert!(passes <= 8, "a wide catch-up must converge, not churn (pass {passes})");
            let cur = crate::db::community::load_community_v2(member_view.id()).unwrap().unwrap();
            let rk = follow_rekeys(&bed.relay, &cur, &session).await.unwrap();
            assert!(!rk.self_removed);
            let cur = crate::db::community::load_community_v2(member_view.id()).unwrap().unwrap();
            let ctl = follow_control(&bed.relay, &cur).await.unwrap().updated;
            if rk.updated.is_none() && ctl.is_none() {
                break;
            }
        }
        let caught_up = crate::db::community::load_community_v2(member_view.id()).unwrap().unwrap();
        assert_eq!(caught_up.root_epoch, Epoch(2), "walked both refoundings");
        // Every private channel converged to the owner's current key + reads all epochs.
        for id in &priv_ids {
            let mine = caught_up.channel(id).expect("channel survived");
            let theirs = community.channel(id).unwrap();
            assert_eq!(mine.key, theirs.key, "channel {} converged on the owner key", crate::simd::hex::bytes_to_hex_32(&id.0));
            assert_eq!(mine.epoch, theirs.epoch, "…at the same epoch");
            let id_hex = crate::simd::hex::bytes_to_hex_32(&id.0);
            // Opening reads the live planes; the rotated-past ones are the
            // back-paging cursor's job. Both halves asserted — the point is that
            // every epoch stays REACHABLE, not that opening drags it all in.
            let open = texts_in(&bed.relay, &caught_up, id).await;
            assert!(open.iter().any(|t| t.contains("epoch2")), "channel {id_hex} opens onto its live epoch");
            let paged = all_texts_in(&bed.relay, &caught_up, id).await;
            assert!(paged.iter().any(|t| t.contains("epoch0")), "channel {id_hex} pages back to epoch-0 history");
            for epoch in 1..=2u64 {
                assert!(paged.iter().any(|t| t.contains(&format!("epoch{epoch}"))), "channel {id_hex} pages back to epoch-{epoch} history");
            }
        }
    }

    #[tokio::test]
    async fn a_backlog_deeper_than_max_steps_still_converges() {
        // MAX_STEPS bounds ONE walk, not the catch-up. A member who slept through more
        // rotations than the bound must still land on the head — silently stopping at
        // the bound leaves them on a dead epoch reading nothing, which is
        // indistinguishable from a quiet community.
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let mut community = create_community(&bed.relay, "DeepSleeper", bed.relays.clone(), None).await.unwrap();
        let bundle_json = serde_json::to_string(&bundle_of(&community, BundleAudience::Member(member.keys.public_key()), Some(owner.keys.public_key()), None, None)).unwrap();

        bed.swap_to(&member);
        let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
        assert_eq!(joined.root_epoch, Epoch(0));

        // Past the bound, deliberately.
        bed.swap_to(&owner);
        let depth = MAX_WALK_STEPS + 3;
        for _ in 0..depth {
            community = refound_community(&bed.relay, &community, &[]).await.unwrap();
        }
        assert_eq!(community.root_epoch, Epoch(depth as u64));

        // The member follows repeatedly, exactly as a client does on each sync. Every
        // pass must make forward progress and none may lose ground.
        bed.swap_to(&member);
        let mut last = 0u64;
        for pass in 1..=8 {
            // Reload from the DB each pass, exactly as a client does: this is what
            // proves every hop was CHECKPOINTED, not merely held in the walk's memory.
            let view = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
            let session = crate::db::current_session();
            let _ = follow_rekeys(&bed.relay, &view, &session).await.unwrap();
            let view = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
            assert!(
                view.root_epoch.0 >= last,
                "pass {pass} lost ground: {} -> {}",
                last, view.root_epoch.0
            );
            last = view.root_epoch.0;
            if last == depth as u64 {
                break;
            }
        }
        let view = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        assert_eq!(
            view.root_epoch, Epoch(depth as u64),
            "a backlog deeper than one walk's step bound must still converge across passes",
        );
    }

    #[tokio::test]
    async fn an_offline_member_catches_up_across_three_refoundings() {
        // The deep offline-online scenario: a member sleeps through THREE
        // Refoundings, per-refound private-channel rotations, a mid-life private
        // channel CREATED while they slept, a public channel, a rename, and a
        // ban — then returns and converges by follow alone (no rejoin).
        use nostr_sdk::prelude::ToBech32;
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let mut community = create_community(&bed.relay, "Sleeper", bed.relays.clone(), None).await.unwrap();
        let general = community.channels[0].id;
        let mods = create_private_channel(&bed.relay, &community, "mods").await.unwrap();
        community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        send_message(&bed.relay, &community, &general, "epoch0: hello").await.unwrap();
        send_message(&bed.relay, &community, &mods, "epoch0: mods secret").await.unwrap();
        // Private channels are readable only by granted role-holders (CORD-03).
        grant_channel_access(&bed.relay, &community, &mods, &member.keys.public_key()).await.unwrap();
        let bundle_json = serde_json::to_string(&bundle_of(&community, BundleAudience::Member(member.keys.public_key()), Some(owner.keys.public_key()), None, None)).unwrap();

        // Member joins at epoch 0, then goes OFFLINE.
        bed.swap_to(&member);
        let member_view = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
        assert_eq!(member_view.root_epoch, Epoch(0));

        // While they sleep, the owner reshapes everything across three epochs.
        bed.swap_to(&owner);
        let stranger = Keys::generate();
        for epoch in 1..=3u64 {
            community = refound_community(&bed.relay, &community, &[]).await.unwrap();
            assert_eq!(community.root_epoch, Epoch(epoch));
            send_message(&bed.relay, &community, &general, &format!("epoch{epoch}: general news")).await.unwrap();
            send_message(&bed.relay, &community, &mods, &format!("epoch{epoch}: mods word")).await.unwrap();
        }
        let news = create_public_channel(&bed.relay, &community, "news").await.unwrap();
        community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let vault = create_private_channel(&bed.relay, &community, "vault").await.unwrap();
        community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        // The sleeper is on this channel's access list, so the refoundings that
        // follow deliver its key to them (CORD-03).
        grant_channel_access(&bed.relay, &community, &vault, &member.keys.public_key()).await.unwrap();
        community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        send_message(&bed.relay, &community, &vault, "epoch3: vault opened").await.unwrap();
        set_banlist(&bed.relay, &community, &[stranger.public_key().to_hex()]).await.unwrap();
        let meta = control::CommunityMetadata { name: "Sleeper Reborn".into(), relays: community.relays.clone(), ..Default::default() };
        edit_community_metadata(&bed.relay, &community, &meta).await.unwrap();

        // The member RETURNS: rekey+control follow to quiescence (the worker's
        // loop, driven explicitly). Bounded — convergence must be fast.
        bed.swap_to(&member);
        let session = crate::db::current_session();
        let mut passes = 0;
        loop {
            passes += 1;
            assert!(passes <= 6, "catch-up must converge, not churn");
            let cur = crate::db::community::load_community_v2(member_view.id()).unwrap().unwrap();
            let rekeyed = follow_rekeys(&bed.relay, &cur, &session).await.unwrap();
            assert!(!rekeyed.self_removed, "the member was never removed");
            let cur = crate::db::community::load_community_v2(member_view.id()).unwrap().unwrap();
            let controlled = follow_control(&bed.relay, &cur).await.unwrap().updated;
            if rekeyed.updated.is_none() && controlled.is_none() {
                break;
            }
        }
        let caught_up = crate::db::community::load_community_v2(member_view.id()).unwrap().unwrap();

        // Base + name converged.
        assert_eq!(caught_up.root_epoch, Epoch(3), "walked all three refoundings");
        assert_eq!(caught_up.community_root, community.community_root, "landed on the owner's root");
        assert_eq!(caught_up.name, "Sleeper Reborn");
        // Channels: renamed set incl. the mid-sleep public + private ones.
        assert!(caught_up.channels.iter().any(|c| c.id.0 == news.0), "folded the new public channel");
        let m = caught_up.channel(&mods).expect("mods survived");
        let owner_mods = community.channel(&mods).unwrap();
        assert_eq!(m.epoch, owner_mods.epoch, "mods walked every per-refound rotation");
        assert_eq!(m.key, owner_mods.key, "…to the owner's exact key");
        let v = caught_up.channel(&vault).expect("vault folded in");
        // The sleeper is on vault's access list, but it was created AFTER the last
        // refounding — no rotation followed the grant, so no blob was ever
        // addressed to them. They hold the channel keyless until the grant's own
        // key vend lands (CORD-05 §6), which is what a rekey-only walk cannot do.
        assert!(v.private && v.key.is_none(), "vault folds in keyless: entitled, but never delivered");
        // Banlist survived the compactions.
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&caught_up.id().0);
        let banned = crate::db::community::get_community_banlist(&cid_hex).unwrap();
        assert!(banned.contains(&stranger.public_key().to_hex()), "the ban folded through");
        // Opening reads the live planes only; paging back reaches EVERY epoch
        // (public via the base-root archive, private via the per-channel archive
        // built during the walk). A sleeper's deep history stays reachable — it
        // just arrives when they scroll for it rather than on open.
        let gen_open = texts_in(&bed.relay, &caught_up, &general).await;
        assert!(gen_open.contains(&"epoch3: general news".to_string()), "general opens onto its live epoch: {gen_open:?}");
        let gen_texts = all_texts_in(&bed.relay, &caught_up, &general).await;
        for epoch in 0..=3u64 {
            let needle = if epoch == 0 { "epoch0: hello".to_string() } else { format!("epoch{epoch}: general news") };
            assert!(gen_texts.contains(&needle), "general pages back to epoch {epoch}: {gen_texts:?}");
        }
        let mods_open = texts_in(&bed.relay, &caught_up, &mods).await;
        assert!(mods_open.contains(&"epoch3: mods word".to_string()), "mods opens onto its live epoch: {mods_open:?}");
        let mods_texts = all_texts_in(&bed.relay, &caught_up, &mods).await;
        for epoch in 0..=3u64 {
            let needle = if epoch == 0 { "epoch0: mods secret".to_string() } else { format!("epoch{epoch}: mods word") };
            assert!(mods_texts.contains(&needle), "private pages back to epoch {epoch}: {mods_texts:?}");
        }
        // Keyless (above) means unreadable — a rekey walk cannot substitute for the
        // key vend that a grant carries.
        assert!(texts_in(&bed.relay, &caught_up, &vault).await.is_empty());
        // And the member can still speak.
        send_message(&bed.relay, &caught_up, &general, "member: good morning").await.unwrap();
        bed.swap_to(&owner);
        assert!(
            texts_in(&bed.relay, &community, &general).await.contains(&"member: good morning".to_string()),
            "the caught-up member converses at the new epoch ({})",
            member.keys.public_key().to_bech32().unwrap()
        );
    }

    /// Seal `n` messages onto a community's #general, one per second starting at
    /// `base_secs` (distinct wrap seconds so relay-side `until` paging engages).
    async fn flood_general(relay: &MemoryRelay, community: &CommunityV2, author: &Keys, n: usize, base_secs: u64) {
        let general = community.channels[0].id;
        let group = channel_group_key(&community.community_root, &general, community.root_epoch);
        for i in 0..n {
            let at = base_secs + i as u64;
            let rumor = chat::build_message_rumor(author.public_key(), &general, community.root_epoch, &format!("msg {i}"), None, &[], vec![], at * 1000);
            let (wrap, _) = chat::seal_chat_rumor(&rumor, &group, author, Timestamp::from_secs(at), false).unwrap();
            relay.publish(&wrap, &community.relays).await.unwrap();
        }
    }

    #[tokio::test]
    async fn the_history_walk_pages_past_a_multi_page_burst() {
        // A bot offline through 120 messages must catch ALL of them, not the
        // newest page; until-paging closes the gap.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Burst", vec!["wss://r".into()], None).await.unwrap();
        let general = community.channels[0].id;
        flood_general(&relay, &community, &owner, 120, 10_000).await;

        let all = fetch_channel_history(&relay, &community, &general, 50, 8, None, None, crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await.unwrap();
        assert_eq!(all.len(), 120, "the walk pages the whole burst");
        // Oldest→newest, no duplicates.
        let contents: Vec<String> = all.iter().map(|f| f.event.opened().rumor.content.clone()).collect();
        assert_eq!(contents.first().map(String::as_str), Some("msg 0"));
        assert_eq!(contents.last().map(String::as_str), Some("msg 119"));
        let unique: std::collections::HashSet<&String> = contents.iter().collect();
        assert_eq!(unique.len(), 120, "wrap-id + rumor-id dedup holds across page boundaries");

        // The single-page fetch stays a single page.
        let one = fetch_channel(&relay, &community, &general, 50).await.unwrap();
        assert_eq!(one.len(), 50, "fetch_channel is one newest page");
        assert_eq!(one.last().map(|f| f.event.opened().rumor.content.clone()).as_deref(), Some("msg 119"));
    }

    #[tokio::test]
    async fn a_start_until_cursor_pages_history_from_that_point_backwards() {
        // The back-paging cursor: a walk that starts at an explicit `until`
        // returns only what lies at-or-before it, oldest→newest — the relay-side
        // half of the SDK's walk-until-dry loop.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Paged", vec!["wss://r".into()], None).await.unwrap();
        let general = community.channels[0].id;
        flood_general(&relay, &community, &owner, 120, 10_000).await;

        let older = fetch_channel_history(
            &relay, &community, &general, 50, 8, None, Some(10_059),
            crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default(),
        )
        .await
        .unwrap();
        let contents: Vec<String> = older.iter().map(|f| f.event.opened().rumor.content.clone()).collect();
        assert_eq!(contents.len(), 60, "everything at-or-before the cursor, nothing after");
        assert_eq!(contents.first().map(String::as_str), Some("msg 0"));
        assert_eq!(contents.last().map(String::as_str), Some("msg 59"));
    }

    #[tokio::test]
    async fn the_history_walk_stops_when_the_caller_is_caught_up() {
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Caught", vec!["wss://r".into()], None).await.unwrap();
        let general = community.channels[0].id;
        flood_general(&relay, &community, &owner, 120, 10_000).await;

        // The caller says "I hold everything" after the first page — no deeper fetch.
        let mut pages = 0usize;
        let got = fetch_channel_history(&relay, &community, &general, 50, 8, None, None, crate::community::transport::Evidence::Quorum, |_, _| {
            pages += 1;
            false
        }, |_| Default::default())
        .await
        .unwrap();
        assert_eq!(pages, 1, "the early stop is consulted once");
        assert_eq!(got.len(), 50, "only the newest page is fetched");
        assert_eq!(got.last().map(|f| f.event.opened().rumor.content.clone()).as_deref(), Some("msg 119"));
    }

    #[tokio::test]
    async fn a_page_of_settled_wraps_ends_the_walk_unopened() {
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Settled", vec!["wss://r".into()], None).await.unwrap();
        let general = community.channels[0].id;
        flood_general(&relay, &community, &owner, 120, 10_000).await;

        let asked = std::sync::atomic::AtomicUsize::new(0);
        let mut seen = Vec::new();
        let got = fetch_channel_history(&relay, &community, &general, 50, 8, None, None, crate::community::transport::Evidence::Quorum, |page, held| {
            seen.push((page.len(), held));
            held == 0
        }, |ids| {
            asked.fetch_add(ids.len(), std::sync::atomic::Ordering::Relaxed);
            ids.iter().copied().collect()
        })
        .await
        .unwrap();
        assert!(got.is_empty(), "nothing settled is opened");
        assert_eq!(seen, [(0, 50)], "a page of only settled wraps still reaches the caller's stop");
        assert_eq!(asked.into_inner(), 50, "the newest page alone: all of it held, so the walk ends there");

        // Half settled: the rest open, and the walk goes on past a page with something new.
        let newest = fetch_channel(&relay, &community, &general, 50).await.unwrap();
        let held: std::collections::HashSet<_> = newest.iter().take(25).map(|f| f.event.opened().wrapper_id).collect();
        let got = fetch_channel_history(&relay, &community, &general, 50, 8, None, None, crate::community::transport::Evidence::Quorum, |_, _| true, |ids| ids.iter().filter(|id| held.contains(*id)).copied().collect())
            .await
            .unwrap();
        assert_eq!(got.len(), 95, "everything but the 25 held");
        assert!(got.iter().all(|f| !held.contains(&f.event.opened().wrapper_id)));
    }

    #[tokio::test]
    async fn a_same_second_history_wall_terminates_instead_of_looping() {
        // 60 messages in ONE second with a 25-wrap page: a second-granular
        // `until` can never page past the wall — the walk must step over it
        // (bounded loss, logged) rather than spin.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Wall", vec!["wss://r".into()], None).await.unwrap();
        let general = community.channels[0].id;
        let group = channel_group_key(&community.community_root, &general, community.root_epoch);
        for i in 0..60usize {
            let rumor = chat::build_message_rumor(owner.public_key(), &general, community.root_epoch, &format!("burst {i}"), None, &[], vec![], 5_000_000 + i as u64);
            let (wrap, _) = chat::seal_chat_rumor(&rumor, &group, &owner, Timestamp::from_secs(5_000), false).unwrap();
            relay.publish(&wrap, &community.relays).await.unwrap();
        }
        let got = fetch_channel_history(&relay, &community, &general, 25, 8, None, None, crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await.unwrap();
        assert!(got.len() >= 25, "at least the relay page is read");
        assert!(got.len() <= 60, "sane bound");
        // Termination is the assertion: reaching here means the wall didn't loop.
    }

    #[tokio::test]
    async fn a_grant_revoke_survives_a_withholding_relay() {
        // Floor persistence on the delegation plane: after the owner revokes an admin,
        // a relay serving only the OLD (still owner-signed) grant can't resurrect it.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Revoke", vec!["wss://good".into()], None).await.unwrap();
        let admin = Keys::generate();
        let rid = "d4".repeat(32);
        publish_role(&relay, &community, &owner, &admin_role(&rid, Permissions::MANAGE_METADATA), 1).await;
        publish_grant(&relay, &community, &owner, &admin.public_key(), vec![rid.clone()], 1).await;
        follow_control(&relay, &community).await.unwrap().updated; // seed floors incl. the grant at v1
        publish_grant(&relay, &community, &owner, &admin.public_key(), vec![], 2).await; // revoke → grant floor v2
        follow_control(&relay, &community).await.unwrap().updated;

        // A stale relay serves only the grant prefix (v1, the live grant).
        inject_stale_prefix(&relay, &community, 1, "wss://stale").await;
        let mut stale = community.clone();
        stale.relays = vec!["wss://stale".into()];
        let floors = load_floors(&community);
        let editions = fetch_control(&relay, &stale).await;
        let authority = fold_authority(&stale, &editions, &floors);
        assert!(
            !authority.roles.is_authorized(&admin.public_key().to_hex(), Some(&owner.public_key().to_hex()), Permissions::MANAGE_METADATA),
            "the persisted grant floor refuses the rolled-back (re-granted) view"
        );
    }

    /// Load the current-epoch floors for a community (test mirror of follow_control).
    fn load_floors(community: &CommunityV2) -> Floors {
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        crate::db::community::get_all_edition_heads_full(&cid_hex)
            .unwrap_or_default()
            .into_iter()
            .filter(|(_, f)| f.0 == community.root_epoch.0)
            .map(|(e, f)| (e, (f.1, f.2, f.3, f.4, f.5)))
            .collect()
    }

    /// Fetch + open every control edition at a community's control plane (test helper).
    async fn fetch_control(relay: &MemoryRelay, community: &CommunityV2) -> Vec<ParsedEdition> {
        let group = control::ControlPlane::of(&community).write_group().unwrap();
        let q = Query { kinds: vec![stream::KIND_WRAP], authors: vec![group.pk_hex()], limit: Some(500), ..Default::default() };
        relay
            .fetch(&q, &community.relays)
            .await
            .unwrap_or_default()
            .iter()
            .filter_map(|w| control::open_control_edition(w, &group).ok().map(|(ed, _)| ed))
            .collect()
    }

    #[tokio::test]
    async fn follow_control_is_a_noop_on_a_freshly_created_community() {
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Fresh", vec!["wss://r".into()], None).await.unwrap();
        // Only the genesis editions exist; folding them reproduces the held view.
        assert!(follow_control(&relay, &community).await.unwrap().updated.is_none());
    }

    #[tokio::test]
    async fn follow_control_adds_a_new_public_channel_and_re_subscribes_it() {
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Grow", vec!["wss://r".into()], None).await.unwrap();
        let new_id = ChannelId([0x5a; 32]);
        publish_channel_edition(&relay, &community, &owner, &new_id, "announcements", false, 1, false).await;

        let updated = follow_control(&relay, &community).await.unwrap().updated.expect("a new channel changed the view");
        assert_eq!(updated.channels.len(), 2);
        let added = updated.channel(&new_id).expect("the new channel folded in");
        assert_eq!(added.name, "announcements");
        assert!(!added.private);
        assert_eq!(added.key, None, "a public channel derives from the root (no stored key)");

        // The new channel is now in the realtime author-set (it would be subscribed).
        let authors = super::super::realtime::plane_authors(std::slice::from_ref(&updated));
        let addr = channel_group_key(&updated.community_root, &new_id, updated.root_epoch).pk();
        assert!(authors.contains(&addr), "the added channel joins the live subscription");

        // Persisted: a reload sees it too.
        let reloaded = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        assert!(reloaded.channel(&new_id).is_some());
    }

    #[tokio::test]
    async fn follow_control_renames_the_community_and_an_existing_channel() {
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Old Name", vec!["wss://r".into()], None).await.unwrap();
        let general = community.channels[0].id;
        // A v2 metadata edition renames the community; a v2 channel edition renames #general.
        publish_community_meta(&relay, &community, &owner, "New Name", 2).await;
        publish_channel_edition(&relay, &community, &owner, &general, "lobby", false, 2, false).await;

        let updated = follow_control(&relay, &community).await.unwrap().updated.unwrap();
        assert_eq!(updated.name, "New Name");
        assert_eq!(updated.channel(&general).unwrap().name, "lobby");
        assert_eq!(updated.channels.len(), 1, "a rename doesn't add a channel");
    }

    #[tokio::test]
    async fn follow_control_deletes_a_channel() {
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Prune", vec!["wss://r".into()], None).await.unwrap();
        let extra = ChannelId([0x77; 32]);

        // The channel is first added and folded into the held view.
        publish_channel_edition(&relay, &community, &owner, &extra, "temp", false, 1, false).await;
        let with_extra = follow_control(&relay, &community).await.unwrap().updated.expect("added");
        assert!(with_extra.channel(&extra).is_some());

        // Then it's tombstoned — the delete (higher version) folds the held one back out.
        publish_channel_edition(&relay, &community, &owner, &extra, "temp", false, 2, true).await;
        let updated = follow_control(&relay, &with_extra).await.unwrap().updated.expect("removed");
        assert!(updated.channel(&extra).is_none(), "a deleted channel folds out");
        assert_eq!(updated.channels.len(), 1, "only #general remains");
    }

    #[tokio::test]
    async fn a_flood_dated_ahead_never_buries_the_history_beneath_it() {
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Flood", vec!["wss://r".into()], None).await.unwrap();
        let general = community.channels[0].id;
        let group = channel_group_key(&community.community_root, &general, community.root_epoch);
        let (member, spammer) = (Keys::generate(), Keys::generate());
        let now = crate::clock::now_ms();
        let post = |keys: &Keys, text: &str, at: u64| {
            let rumor = chat::build_message_rumor(keys.public_key(), &general, community.root_epoch, text, None, &[], vec![], at);
            chat::seal_chat_rumor(&rumor, &group, keys, Timestamp::from_secs(at / 1000), false).unwrap().0
        };
        relay.publish(&post(&member, "real", now - 60_000), &community.relays).await.unwrap();
        for i in 0..30u64 {
            relay.publish(&post(&spammer, "ahead", now + 60_000 + i * 1_000), &community.relays).await.unwrap();
        }
        let page = fetch_channel_history(&relay, &community, &general, 10, 1, None, None, crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await.unwrap();
        let texts: Vec<_> = page.iter().map(|f| f.event.opened().rumor.content.clone()).collect();
        assert_eq!(texts, vec!["real".to_string()], "pages of messages dated ahead are stepped past, not shown");
    }

    #[tokio::test]
    async fn a_history_read_holds_a_message_dated_ahead() {
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Ahead", vec!["wss://r".into()], None).await.unwrap();
        let general = community.channels[0].id;
        let group = channel_group_key(&community.community_root, &general, community.root_epoch);
        let member = Keys::generate();
        let now = crate::clock::now_ms();
        let mut ids = Vec::new();
        for (text, at) in [("on time", now), ("minutes fast", now + 3 * 60 * 1000)] {
            let rumor = chat::build_message_rumor(member.public_key(), &general, community.root_epoch, text, None, &[], vec![], at);
            ids.push(rumor.id.unwrap());
            let (wrap, _) = chat::seal_chat_rumor(&rumor, &group, &member, Timestamp::from_secs(at / 1000), false).unwrap();
            relay.publish(&wrap, &community.relays).await.unwrap();
        }
        let page: Vec<_> = fetch_channel(&relay, &community, &general, 50).await.unwrap().iter().map(|f| f.event.opened().rumor_id).collect();
        assert!(page.contains(&ids[0]));
        assert!(!page.contains(&ids[1]), "it waits for its time instead of joining the page");
    }

    #[tokio::test]
    async fn a_deleted_channel_leaves_every_device_with_its_files_and_in_time_my_wraps() {
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        relay.follow_cord01(&["wss://r".to_string()]);
        let community = create_community(&relay, "Purge", vec!["wss://r".into()], None).await.unwrap();
        let doomed = ChannelId([0x7a; 32]);
        publish_channel_edition(&relay, &community, &owner, &doomed, "doomed", false, 1, false).await;
        let held = follow_control(&relay, &community).await.unwrap().updated.expect("added");
        let doomed_hex = crate::simd::hex::bytes_to_hex_32(&doomed.0);

        // Mine, sent for real; someone else's; and two of my uploads, one also forwarded into a DM.
        let sent = send_message(&relay, &held, &doomed, "bye").await.unwrap();
        let file = |hash: &str, url: &str| crate::types::Attachment { id: hash.into(), url: url.into(), ..Default::default() };
        let (kept_url, gone_url) = ("https://cdn.example/shared", "https://cdn.example/only-here");
        let with_files = crate::types::Message {
            id: "f1".repeat(32), content: "files".into(), at: 1_700_000_000_000, mine: true,
            attachments: vec![file(&"a1".repeat(32), kept_url), file(&"b2".repeat(32), gone_url)], ..Default::default()
        };
        let theirs = crate::types::Message { id: "f2".repeat(32), content: "theirs".into(), at: 1_700_000_001_000, ..Default::default() };
        for msg in [&with_files, &theirs] {
            crate::db::events::save_message(&doomed_hex, msg).await.unwrap();
        }
        let elsewhere = crate::types::Message {
            id: "f3".repeat(32), content: "forwarded".into(), at: 1_700_000_002_000, mine: true,
            attachments: vec![file(&"a1".repeat(32), kept_url)], ..Default::default()
        };
        crate::db::events::save_message(&nostr_sdk::prelude::ToBech32::to_bech32(&Keys::generate().public_key()).unwrap(), &elsewhere).await.unwrap();

        let purged = purge::purge_deleted_channel(&held, &doomed, None).await.expect("it held the channel");
        assert_eq!(purged, purge::Purged { uploads: vec![gone_url.to_string()], scrubs: 1 }, "only my upload nothing else uses");
        assert!(crate::db::community::channel_events(&doomed_hex).unwrap().is_empty(), "its history is gone");
        assert!(!crate::state::STATE.lock().await.chats.iter().any(|c| c.id == doomed_hex));
        assert!(crate::db::events::event_exists(&elsewhere.id).unwrap(), "the forwarded copy stays");
        assert_eq!(purge::purge_deleted_channel(&held, &doomed, None).await, None, "a second run finds nothing");

        // My wrap leaves the relays from the queue, one at a time.
        assert_eq!(crate::db::community::next_wrap_scrub().unwrap().map(|(id, _)| id), Some(sent.clone()));
        let wrap_id = crate::db::community::wrap_owners(&sent).unwrap()[0].1.clone();
        assert_eq!(crate::community::message_delete::drain_scrubs(&relay, std::time::Duration::ZERO).await, 1);
        assert!(relay.fetch(&Query { ids: vec![wrap_id], ..Default::default() }, &["wss://r".to_string()]).await.unwrap().is_empty());
        assert_eq!(crate::db::community::next_wrap_scrub().unwrap(), None);
    }

    #[tokio::test]
    async fn a_folded_deletion_purges_the_channel_on_a_device_that_did_not_delete_it() {
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Seen", vec!["wss://r".into()], None).await.unwrap();
        let doomed = ChannelId([0x7b; 32]);
        publish_channel_edition(&relay, &community, &owner, &doomed, "doomed", false, 1, false).await;
        let held = follow_control(&relay, &community).await.unwrap().updated.expect("added");
        let sent = send_message(&relay, &held, &doomed, "seen elsewhere").await.unwrap();

        publish_channel_edition(&relay, &community, &owner, &doomed, "doomed", false, 2, true).await;
        follow_control(&relay, &held).await.unwrap();
        assert!(crate::db::community::channel_events(&crate::simd::hex::bytes_to_hex_32(&doomed.0)).unwrap().is_empty());
        assert_eq!(crate::db::community::next_wrap_scrub().unwrap().map(|(id, _)| id), Some(sent), "queued to leave the relays");
    }

    #[tokio::test]
    async fn a_later_edition_never_revives_a_deleted_channel() {
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Grave", vec!["wss://r".into()], None).await.unwrap();
        let extra = ChannelId([0x78; 32]);
        publish_channel_edition(&relay, &community, &owner, &extra, "temp", false, 1, false).await;
        let with_extra = follow_control(&relay, &community).await.unwrap().updated.expect("added");
        publish_channel_edition(&relay, &community, &owner, &extra, "temp", false, 2, true).await;
        publish_channel_edition(&relay, &community, &owner, &extra, "back", false, 3, false).await;
        let tracked = follow_control(&relay, &with_extra).await.unwrap().updated.expect("removed");
        assert!(tracked.channel(&extra).is_none(), "deletion is terminal over the chain, not the head");
        crate::db::community::save_community_v2(&community).unwrap();
        let fresh = follow_control(&relay, &community).await.unwrap().updated.unwrap_or(community.clone());
        assert!(fresh.channel(&extra).is_none(), "a fresh reader agrees");
    }

    #[tokio::test]
    async fn an_edition_without_its_kinds_bit_cannot_hide_a_channel() {
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Squat", vec!["wss://r".into()], None).await.unwrap();
        let extra = ChannelId([0x79; 32]);
        publish_channel_edition(&relay, &community, &owner, &extra, "kept", false, 1, false).await;
        let group = control::ControlPlane::of(&community).write_group().unwrap();
        let stranger = Keys::generate();
        for (signer, kind) in [(&owner, "99"), (&stranger, vsk::ROLE_V2)] {
            let rumor = control::build_edition_rumor(signer.public_key(), kind, &extra.0, 1, None, r#"{"role_id":"x"}"#, 1_000, None);
            let (wrap, _) = control::seal_control_edition(&rumor, &group, signer, Timestamp::from_secs(1_000)).unwrap();
            relay.publish(&wrap, &community.relays).await.unwrap();
        }
        let updated = follow_control(&relay, &community).await.unwrap().updated.expect("added");
        assert!(updated.channel(&extra).is_some(), "an unknown kind, or one its signer can't write, claims no coordinate");

        // One its signer can write does claim it, and a reader that held the Channel lets it go too.
        let rumor = control::build_edition_rumor_bound(owner.public_key(), vsk::CATEGORY, &extra.0, 1, None, r#"{"name":"Staff"}"#, 1_000, None, Some(crate::community::v2::derive::edition_binding(community.id())));
        let (wrap, _) = control::seal_control_edition(&rumor, &group, &owner, Timestamp::from_secs(1_000)).unwrap();
        relay.publish(&wrap, &community.relays).await.unwrap();
        let tracked = follow_control(&relay, &updated).await.unwrap().updated.expect("let go");
        assert!(tracked.channel(&extra).is_none(), "an edition aimed at another entity folds as no Channel");
    }

    /// Re-inject only the OLD prefix (every edition at/below `max_version`) of a
    /// community's control plane onto a second relay URL — the withholding-relay
    /// simulation: everything it serves is genuinely owner-signed, just stale.
    async fn inject_stale_prefix(relay: &MemoryRelay, community: &CommunityV2, max_version: u64, stale_relay: &str) {
        let group = control::ControlPlane::of(&community).write_group().unwrap();
        let query = Query { kinds: vec![stream::KIND_WRAP], authors: vec![group.pk_hex()], limit: Some(500), ..Default::default() };
        let wraps = relay.fetch(&query, &community.relays).await.unwrap();
        for w in &wraps {
            if let Ok((ed, _)) = control::open_control_edition(w, &group) {
                if ed.version <= max_version {
                    relay.inject(w, &[stale_relay.to_string()]);
                }
            }
        }
    }

    #[tokio::test]
    async fn a_withholding_relay_cannot_roll_back_a_rename() {
        // W2 persisted floor: after adopting the owner's v2 rename, a relay serving
        // only the (owner-signed) v1 genesis must not revert the held name.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Original", vec!["wss://good".into()], None).await.unwrap();
        publish_community_meta(&relay, &community, &owner, "Renamed", 2).await;

        let updated = follow_control(&relay, &community).await.unwrap().updated.expect("rename adopted");
        assert_eq!(updated.name, "Renamed");

        // The stale relay holds only the genesis prefix; point the follow at it.
        inject_stale_prefix(&relay, &community, 1, "wss://stale").await;
        let mut stale_view = updated.clone();
        stale_view.relays = vec!["wss://stale".into()];
        assert!(
            follow_control(&relay, &stale_view).await.unwrap().updated.is_none(),
            "a stale-only relay must not change the held view"
        );
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        assert_eq!(held.name, "Renamed", "the persisted floor refuses the rollback");
    }

    #[tokio::test]
    async fn a_withholding_relay_cannot_resurrect_a_deleted_channel() {
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Prune2", vec!["wss://good".into()], None).await.unwrap();
        let extra = ChannelId([0x44; 32]);

        // A same-content metadata edit: no visible change (None), but the floor must
        // still advance to v2 (so the genesis metadata can't re-present below).
        publish_community_meta(&relay, &community, &owner, "Prune2", 2).await;
        assert!(follow_control(&relay, &community).await.unwrap().updated.is_none());

        publish_channel_edition(&relay, &community, &owner, &extra, "temp", false, 1, false).await;
        let with_extra = follow_control(&relay, &community).await.unwrap().updated.expect("added");
        publish_channel_edition(&relay, &community, &owner, &extra, "temp", false, 2, true).await;
        let pruned = follow_control(&relay, &with_extra).await.unwrap().updated.expect("removed");
        assert!(pruned.channel(&extra).is_none());

        // The stale relay serves the add (v1) but withholds the delete (v2).
        inject_stale_prefix(&relay, &community, 1, "wss://stale").await;
        let mut stale_view = pruned.clone();
        stale_view.relays = vec!["wss://stale".into()];
        assert!(
            follow_control(&relay, &stale_view).await.unwrap().updated.is_none(),
            "the withheld delete must not resurrect the channel"
        );
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        assert!(held.channel(&extra).is_none(), "the deleted channel stays deleted");
    }

    #[tokio::test]
    async fn a_new_epoch_bootstraps_past_an_old_epoch_floor() {
        // The Armada-convergence carve-out: a Refounding compacts the chain and
        // re-wraps a detached head at the NEW epoch's control plane. The old epoch's
        // floor must not block it — epoch-filtering makes the entity bootstrap.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Before", vec!["wss://good".into()], None).await.unwrap();
        publish_community_meta(&relay, &community, &owner, "Edited", 2).await;
        let updated = follow_control(&relay, &community).await.unwrap().updated.expect("edit adopted");
        assert_eq!(updated.name, "Edited");

        // Refounding lands (epoch bump saved by the rekey path); the compacted head
        // arrives DETACHED (high version, no prev) on the new epoch's plane.
        let refounded = rotate_view(&updated, updated.community_root, 1);
        crate::db::community::save_community_v2(&refounded).unwrap();
        publish_community_meta(&relay, &refounded, &owner, "Compacted", 5).await;

        let adopted = follow_control(&relay, &refounded).await.unwrap().updated.expect("compacted head adopted");
        assert_eq!(adopted.name, "Compacted", "a fresh epoch bootstraps despite the dangling prev");
        // The persisted floor is stamped with the epoch the FOLD ran under.
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let heads = crate::db::community::get_all_edition_heads_epoched(&cid_hex).unwrap();
        assert!(
            heads.get(&cid_hex).is_some_and(|(e, v, _)| *e == 1 && *v == 5),
            "the adopted head carries the fold's epoch + version"
        );
    }

    #[tokio::test]
    async fn a_same_version_owner_fork_at_the_floor_converges_to_the_deterministic_winner() {
        // Two owner-signed editions at the SAME version (publish retry / two owner
        // devices): every client must land on the lower-inner-id winner. A hash-strict
        // floor would wedge here forever while Armada converges — the floor must
        // CONVERGE instead.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Fork", vec!["wss://r".into()], None).await.unwrap();
        let group = control::ControlPlane::of(&community).write_group().unwrap();
        let genesis_hash = head_hash_on_relay(&relay, &community, &community.id().0).await.unwrap();

        publish_community_meta(&relay, &community, &owner, "Ours", 2).await;
        let ours = follow_control(&relay, &community).await.unwrap().updated.expect("ours adopted");
        assert_eq!(ours.name, "Ours");

        // Our committed v2 edition's tiebreak id.
        let our_inner = {
            let q = Query { kinds: vec![stream::KIND_WRAP], authors: vec![group.pk_hex()], limit: Some(500), ..Default::default() };
            let wraps = relay.fetch(&q, &community.relays).await.unwrap();
            wraps
                .iter()
                .find_map(|w| {
                    control::open_control_edition(w, &group)
                        .ok()
                        .filter(|(ed, _)| ed.version == 2 && ed.vsk == vsk::COMMUNITY_METADATA)
                        .map(|(ed, _)| ed.inner_id)
                })
                .unwrap()
        };

        // Craft the concurrent fork so it WINS the deterministic tiebreak (vary the
        // authored timestamp until its inner id is lower).
        let meta = control::CommunityMetadata { name: "Theirs".into(), ..Default::default() };
        let content = serde_json::to_string(&meta).unwrap();
        let mut ts = 2_000u64;
        let fork_wrap = loop {
            let rumor = control::build_edition_rumor(owner.public_key(), vsk::COMMUNITY_METADATA, &community.id().0, 2, Some(&genesis_hash), &content, ts, None);
            let inner = rumor.id.unwrap().to_bytes();
            if inner < our_inner {
                break control::seal_control_edition(&rumor, &group, &owner, Timestamp::from_secs(ts)).unwrap().0;
            }
            ts += 1;
        };
        relay.publish(&fork_wrap, &community.relays).await.unwrap();

        let converged = follow_control(&relay, &ours).await.unwrap().updated.expect("fork winner adopted");
        assert_eq!(converged.name, "Theirs", "the floor converges to the lower-inner-id winner");
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let held = crate::db::community::get_edition_head_inner_id(&cid_hex, &cid_hex).unwrap();
        assert!(held.is_some_and(|h| h < our_inner), "the persisted floor's tiebreak key moved to the winner");
    }

    #[tokio::test]
    async fn an_anchored_prefix_applies_while_a_gap_above_awaits_the_missing_link() {
        // v2 chains to the floor; v4 arrives but its v3 link is withheld. The
        // chain-verified prefix (v2) applies NOW — refuse-downgrade holds for it —
        // while the detached v4 waits. When v3 lands, the chain heals to v4.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Prefix", vec!["wss://r".into()], None).await.unwrap();
        let group = control::ControlPlane::of(&community).write_group().unwrap();

        publish_community_meta(&relay, &community, &owner, "Two", 2).await;
        let v2_hash = head_hash_on_relay(&relay, &community, &community.id().0).await.unwrap();

        // Craft v3 (held back) and v4 (published, chained to the withheld v3).
        let c3 = serde_json::to_string(&control::CommunityMetadata { name: "Three".into(), ..Default::default() }).unwrap();
        let r3 = control::build_edition_rumor(owner.public_key(), vsk::COMMUNITY_METADATA, &community.id().0, 3, Some(&v2_hash), &c3, 3_000, None);
        let (w3, _) = control::seal_control_edition(&r3, &group, &owner, Timestamp::from_secs(3_000)).unwrap();
        let (ed3, _) = control::open_control_edition(&w3, &group).unwrap();
        let c4 = serde_json::to_string(&control::CommunityMetadata { name: "Four".into(), ..Default::default() }).unwrap();
        let r4 = control::build_edition_rumor(owner.public_key(), vsk::COMMUNITY_METADATA, &community.id().0, 4, Some(&ed3.self_hash), &c4, 4_000, None);
        let (w4, _) = control::seal_control_edition(&r4, &group, &owner, Timestamp::from_secs(4_000)).unwrap();
        relay.publish(&w4, &community.relays).await.unwrap();

        let updated = follow_control(&relay, &community).await.unwrap().updated.expect("the verified prefix applies");
        assert_eq!(updated.name, "Two", "the anchored prefix lands; the detached v4 does not");

        relay.publish(&w3, &community.relays).await.unwrap();
        let healed = follow_control(&relay, &updated).await.unwrap().updated.expect("the chain heals");
        assert_eq!(healed.name, "Four", "once the link arrives, the head advances past the prefix");
    }

    #[tokio::test]
    async fn paging_rescues_a_floor_link_evicted_from_the_newest_window() {
        // The held floor is v2; the owner publishes v3, then a flood of foreign junk
        // wraps fills the newest window, then v4. Page 1 sees only v4 (detached →
        // gapped); paging older must recover v3 (and the floor link) and heal to v4.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Paged", vec!["wss://r".into()], None).await.unwrap();
        let group = control::ControlPlane::of(&community).write_group().unwrap();

        publish_community_meta(&relay, &community, &owner, "Two", 2).await;
        let base = follow_control(&relay, &community).await.unwrap().updated.expect("floor at v2");
        publish_community_meta(&relay, &base, &owner, "Three", 3).await; // ts 1_000 (old)
        let v3_hash = head_hash_on_relay(&relay, &community, &community.id().0).await.unwrap();

        // Rogue flood occupying the newest window (sealed to the control plane, but
        // non-owner — the authority gate drops them; they only crowd the page).
        let rogue = Keys::generate();
        for i in 0..(FOLLOW_PAGE as u64 - 1) {
            let rumor = control::build_edition_rumor(rogue.public_key(), vsk::CHANNEL_METADATA, &[0xCC; 32], 1, None, "{\"name\":\"junk\",\"private\":false}", 4_000 + i, None);
            let (w, _) = control::seal_control_edition(&rumor, &group, &rogue, Timestamp::from_secs(4_000 + i)).unwrap();
            relay.publish(&w, &community.relays).await.unwrap();
        }
        // v4 chained to the real v3 (crafted directly: the flood also blinds the
        // helper's own newest-window head lookup), timestamped newest of all.
        let c4 = serde_json::to_string(&control::CommunityMetadata { name: "Four".into(), ..Default::default() }).unwrap();
        let r4 = control::build_edition_rumor(owner.public_key(), vsk::COMMUNITY_METADATA, &community.id().0, 4, Some(&v3_hash), &c4, 10_000, None);
        let (w4, _) = control::seal_control_edition(&r4, &group, &owner, Timestamp::from_secs(10_000)).unwrap();
        relay.publish(&w4, &community.relays).await.unwrap();

        let healed = follow_control(&relay, &base).await.unwrap().updated.expect("paging recovered the chain");
        assert_eq!(healed.name, "Four", "the gap paged past the flood to the floor link");
    }

    #[tokio::test]
    async fn a_follow_after_delete_does_not_resurrect_the_community() {
        // A leave/delete racing an in-flight follow: the follow must not re-insert
        // the community row or floor rows past delete_community's wipe.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Gone", vec!["wss://r".into()], None).await.unwrap();
        publish_community_meta(&relay, &community, &owner, "Edited", 2).await;
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        crate::db::community::delete_community(&cid_hex).unwrap();

        assert!(
            follow_control(&relay, &community).await.unwrap().updated.is_none(),
            "a follow racing a delete is a no-op"
        );
        assert!(crate::db::community::load_community_v2(community.id()).unwrap().is_none(), "the community stays deleted");
        assert!(crate::db::community::edition_head_entity_ids(&cid_hex).unwrap().is_empty(), "no orphan floor rows");
    }

    #[tokio::test]
    async fn a_rekey_follow_after_delete_does_not_resurrect_the_community() {
        // The rekey sibling of the follow_control guard: an owner rotation adopted
        // mid-race must not upsert the community row back after a leave/delete.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "GoneKeys", vec!["wss://r".into()], None).await.unwrap();
        let new_root = [0xB2; 32];
        publish_base_rotation(&relay, &community, &owner, &[owner.public_key()], &new_root, &community.community_root).await;
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        crate::db::community::delete_community(&cid_hex).unwrap();

        let session = crate::db::current_session();
        let follow = follow_rekeys(&relay, &community, &session).await.unwrap();
        assert!(follow.updated.is_none() && !follow.self_removed, "a rekey follow racing a delete adopts nothing");
        assert!(crate::db::community::load_community_v2(community.id()).unwrap().is_none(), "the community stays deleted");
    }

    #[tokio::test]
    async fn a_joiner_bootstraps_the_highest_head_across_a_lost_middle_edition() {
        // {v1, v3} on the relays with v2 lost at publish time (a rate-limiting relay
        // that still ACKed): the genesis anchors, so an anchored-prefix-first fold
        // would take v1 and SEED the joiner's floor there — pinning them below the
        // head Armada shows, forever. A joiner (floor 0) must bootstrap v3.
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Skip", bed.relays.clone(), None).await.unwrap();
        let group = control::ControlPlane::of(&community).write_group().unwrap();
        let genesis_hash = head_hash_on_relay(&bed.relay, &community, &community.id().0).await.unwrap();

        // v2 is crafted but NEVER published; v3 chains to it and is published.
        let c2 = serde_json::to_string(&control::CommunityMetadata { name: "Two".into(), ..Default::default() }).unwrap();
        let r2 = control::build_edition_rumor(owner.keys.public_key(), vsk::COMMUNITY_METADATA, &community.id().0, 2, Some(&genesis_hash), &c2, 2_000, None);
        let (w2, _) = control::seal_control_edition(&r2, &group, &owner.keys, Timestamp::from_secs(2_000)).unwrap();
        let (ed2, _) = control::open_control_edition(&w2, &group).unwrap();
        let c3 = serde_json::to_string(&control::CommunityMetadata { name: "Three".into(), ..Default::default() }).unwrap();
        let r3 = control::build_edition_rumor(owner.keys.public_key(), vsk::COMMUNITY_METADATA, &community.id().0, 3, Some(&ed2.self_hash), &c3, 3_000, None);
        let (w3, _) = control::seal_control_edition(&r3, &group, &owner.keys, Timestamp::from_secs(3_000)).unwrap();
        bed.relay.publish(&w3, &community.relays).await.unwrap();

        let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
        let bundle_json = serde_json::to_string(&bundle).unwrap();
        bed.swap_to(&member);
        let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
        assert_eq!(joined.name, "Three", "the joiner bootstraps the highest signed head, not the anchored stale prefix");
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&joined.id().0);
        let head = crate::db::community::get_edition_head(&cid_hex, &cid_hex).unwrap();
        assert!(head.is_some_and(|(v, _)| v == 3), "the seeded floor is the bootstrap head");
    }

    #[tokio::test]
    async fn a_losing_same_version_fork_cannot_replace_the_held_floor() {
        // The refusal half of fork convergence: a relay withholding OUR committed
        // floor edition while serving only a same-version fork with a HIGHER inner
        // id must be treated as withholding — held state and floor unchanged.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Fork2", vec!["wss://good".into()], None).await.unwrap();
        let group = control::ControlPlane::of(&community).write_group().unwrap();
        let genesis_hash = head_hash_on_relay(&relay, &community, &community.id().0).await.unwrap();

        publish_community_meta(&relay, &community, &owner, "Ours", 2).await;
        let ours = follow_control(&relay, &community).await.unwrap().updated.expect("ours adopted");
        assert_eq!(ours.name, "Ours");
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let held_before = crate::db::community::get_edition_head(&cid_hex, &cid_hex).unwrap().unwrap();
        let our_inner = crate::db::community::get_edition_head_inner_id(&cid_hex, &cid_hex).unwrap().unwrap();

        // Grind the fork to LOSE the tiebreak (higher inner id), then serve it —
        // with the genesis but WITHOUT our v2 — from a withholding relay.
        let meta = control::CommunityMetadata { name: "Theirs".into(), ..Default::default() };
        let content = serde_json::to_string(&meta).unwrap();
        let mut ts = 5_000u64;
        let fork_wrap = loop {
            let rumor = control::build_edition_rumor(owner.public_key(), vsk::COMMUNITY_METADATA, &community.id().0, 2, Some(&genesis_hash), &content, ts, None);
            if rumor.id.unwrap().to_bytes() > our_inner {
                break control::seal_control_edition(&rumor, &group, &owner, Timestamp::from_secs(ts)).unwrap().0;
            }
            ts += 1;
        };
        inject_stale_prefix(&relay, &community, 1, "wss://stale").await; // genesis only
        relay.inject(&fork_wrap, &["wss://stale".to_string()]);
        let mut stale_view = ours.clone();
        stale_view.relays = vec!["wss://stale".into()];

        assert!(
            follow_control(&relay, &stale_view).await.unwrap().updated.is_none(),
            "a losing fork served without our floor edition changes nothing"
        );
        let held_after = crate::db::community::get_edition_head(&cid_hex, &cid_hex).unwrap().unwrap();
        assert_eq!(held_after, held_before, "the floor row is untouched");
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        assert_eq!(held.name, "Ours", "the held state is untouched");
    }

    #[tokio::test]
    async fn follow_control_ignores_a_non_owner_edition() {
        // A member holds the community_root, so they CAN seal a control edition —
        // but they aren't the owner, so the authority gate drops it (first cut:
        // owner-only). The rogue channel must never appear.
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Guarded", vec!["wss://r".into()], None).await.unwrap();
        let rogue = Keys::generate();
        let rogue_id = ChannelId([0x99; 32]);
        publish_channel_edition(&relay, &community, &rogue, &rogue_id, "backdoor", false, 1, false).await;

        assert!(
            follow_control(&relay, &community).await.unwrap().updated.is_none(),
            "a non-owner control edition is not folded"
        );
    }

    #[tokio::test]
    async fn follow_control_records_a_new_private_channel_keyless_and_unreadable() {
        // A Private channel's key rides the rekey plane, not the control edition —
        // control-follow records it KEYLESS (epoch 0, the rekey-scan cursor), and
        // every read/send path refuses it until the key lands (never the root plane).
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Priv", vec!["wss://r".into()], None).await.unwrap();
        let priv_id = ChannelId([0x33; 32]);
        publish_channel_edition(&relay, &community, &owner, &priv_id, "mods", true, 1, false).await;

        let updated = follow_control(&relay, &community)
            .await
            .unwrap()
            .updated
            .expect("the keyless record is a change");
        let ch = updated.channel(&priv_id).expect("the private channel is recorded");
        assert!(ch.private && ch.key.is_none(), "recorded keyless");
        assert_eq!(ch.epoch, Epoch(0), "epoch 0 = the root generation (scan cursor)");
        assert!(updated.channel_read_coords(ch).is_empty(), "unreadable until keyed");
        assert!(
            fetch_channel(&relay, &updated, &priv_id, 50).await.unwrap().is_empty(),
            "a keyless fetch returns empty (and never queries the root plane)"
        );
        assert!(
            send_message(&relay, &updated, &priv_id, "nope").await.is_err(),
            "a keyless send refuses"
        );
        // The keyless record round-trips (the stored placeholder never surfaces
        // as a real key).
        let reloaded = crate::db::community::load_community_v2(updated.id()).unwrap().unwrap();
        let rch = reloaded.channel(&priv_id).unwrap();
        assert!(rch.private && rch.key.is_none() && rch.epoch == Epoch(0), "keyless survives reload");
        // And a bundle minted while keyless never carries the placeholder — a
        // MEMBER audience, so it's the keyless filter proving it (the link
        // filter would drop the channel for the weaker reason).
        let bundle = bundle_of(&reloaded, BundleAudience::Member(Keys::generate().public_key()), None, None, None);
        assert!(
            !bundle.channels.iter().any(|c| c.id == crate::simd::hex::bytes_to_hex_32(&priv_id.0)),
            "an ungrantable keyless channel stays out of invite bundles"
        );
    }

    #[tokio::test]
    async fn a_link_bundle_never_carries_a_private_channel_key() {
        // A link's audience holds no Role by construction (CORD-05), so a HELD
        // private key must never ride a link bundle — anyone with the URL would
        // get the channel. A member bundle carries it; a link bundle only the
        // public channels.
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Leak", vec!["wss://r".into()], None).await.unwrap();
        create_private_channel(&relay, &community, "mods").await.unwrap();
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let priv_hex = held
            .channels
            .iter()
            .find(|c| c.private)
            .map(|c| crate::simd::hex::bytes_to_hex_32(&c.id.0))
            .expect("the private channel is held WITH its key");

        let link = bundle_of(&held, BundleAudience::Link, None, None, None);
        assert!(
            !link.channels.iter().any(|c| c.id == priv_hex),
            "a held private key must never ride a link bundle"
        );
        assert!(
            link.channels.iter().any(|c| c.id != priv_hex),
            "the public channels still ride it"
        );

        // A member bundle grants it only to the ENTITLED. An unrelated npub holds
        // no scoped role, so it gets nothing; the creator (granted the companion
        // access role at create) gets the key.
        let stranger = bundle_of(&held, BundleAudience::Member(Keys::generate().public_key()), None, None, None);
        assert!(
            !stranger.channels.iter().any(|c| c.id == priv_hex),
            "an unentitled member gets no private key"
        );
        let mine = bundle_of(&held, BundleAudience::Member(me_pk().unwrap()), None, None, None);
        assert!(
            mine.channels.iter().any(|c| c.id == priv_hex),
            "the creator is entitled via the companion access role"
        );
    }

    /// Mint a server-scope role at `position` carrying `permissions`, grant it to
    /// `member`, and return its id. Used to build a RANKED roster (the owner-only
    /// tests can't exercise outranking, since the owner outranks everyone).
    async fn seat_ranked_role(
        relay: &MemoryRelay,
        community: &CommunityV2,
        member: &PublicKey,
        name: &str,
        position: u32,
        permissions: crate::community::roles::Permissions,
    ) -> String {
        let role_id = crate::crypto::sha256_hex(format!("test/role/{name}/{position}").as_bytes());
        let role = crate::community::roles::Role {
            role_id: role_id.clone(),
            name: name.to_string(),
            position,
            permissions,
            scope: crate::community::roles::RoleScope::Server,
            color: 0, rank: None, display: false, mentionable: false, extra: Default::default(),
        };
        set_role(relay, community, &role).await.unwrap();
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let mut ids: Vec<String> = {
            let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
            let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
            roster.roles_of(&member.to_hex()).map(|r| r.role_id.clone()).collect()
        };
        if !ids.contains(&role_id) {
            ids.push(role_id.clone());
        }
        grant_roles(relay, &held, member, ids).await.unwrap();
        role_id
    }

    /// Become `who` without touching the account DB — the acting identity only.
    /// Enough to exercise an offer-side authority gate from a non-owner's seat.
    fn act_as(who: &Keys) {
        crate::state::MY_SECRET_KEY.store_from_keys(who, &[]);
        crate::state::set_my_public_key(who.public_key());
    }

    #[tokio::test]
    async fn a_moderator_cannot_revoke_channel_access_from_a_superior_and_the_channel_never_rotates() {
        // CORD-04 §2: the fold drops a Grant aimed at a peer or superior, but the
        // channel rotation is gated on the citation alone — so without an
        // offer-side rank check the Grant dies and the target is severed anyway.
        // The epoch assertion is the point: refusing the publish is worthless if
        // the rekey still runs.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Ranked", vec!["wss://r".into()], None).await.unwrap();
        let vault = create_private_channel(&relay, &community, "vault").await.unwrap();

        let superior = Keys::generate();
        let moderator = Keys::generate();
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        grant_admin(&relay, &held, &superior.public_key()).await.unwrap();
        seat_ranked_role(
            &relay,
            &community,
            &moderator.public_key(),
            "Moderator",
            5,
            crate::community::roles::Permissions(crate::community::roles::Permissions::MANAGE_ROLES),
        )
        .await;

        // The superior legitimately holds the channel (granted by the owner).
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        grant_channel_access(&relay, &held, &vault, &superior.public_key()).await.unwrap();
        let before = crate::db::community::load_community_v2(community.id())
            .unwrap()
            .unwrap()
            .channel(&vault)
            .unwrap()
            .epoch;

        act_as(&moderator);
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let err = revoke_channel_access(&relay, &held, &vault, &superior.public_key())
            .await
            .expect_err("a moderator must not act on an admin");
        assert!(err.contains("outrank"), "refused for RANK, not some incidental reason: {err}");

        let after = crate::db::community::load_community_v2(community.id())
            .unwrap()
            .unwrap()
            .channel(&vault)
            .unwrap()
            .epoch;
        assert_eq!(after, before, "the refusal must also stop the rotation — the rekey IS the severance");
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
        let chan_hex = crate::simd::hex::bytes_to_hex_32(&vault.0);
        let owner_hex = owner.public_key().to_hex();
        assert!(
            roster.is_entitled(Some(&owner_hex), &superior.public_key().to_hex(), &chan_hex, &[], &[]),
            "and the superior keeps their access role"
        );
    }

    #[tokio::test]
    async fn a_moderator_cannot_grant_channel_access_to_a_superior_but_the_owner_stays_grantable() {
        // The grant direction of the same gate. The owner is never a valid rank
        // target, yet IS a legitimate recipient of a key an admin minted — the
        // rank check must not swallow that case.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Ranked", vec!["wss://r".into()], None).await.unwrap();
        let vault = create_private_channel(&relay, &community, "vault").await.unwrap();

        let superior = Keys::generate();
        let moderator = Keys::generate();
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        grant_admin(&relay, &held, &superior.public_key()).await.unwrap();
        let chan_hex = crate::simd::hex::bytes_to_hex_32(&vault.0);
        // Scoped access so the moderator holds the channel key itself, else the
        // refusal could come from "we hold no key" and prove nothing about rank.
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        grant_channel_access(&relay, &held, &vault, &moderator.public_key()).await.unwrap();
        seat_ranked_role(
            &relay,
            &community,
            &moderator.public_key(),
            "Moderator",
            5,
            crate::community::roles::Permissions(crate::community::roles::Permissions::MANAGE_ROLES),
        )
        .await;

        act_as(&moderator);
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let err = grant_channel_access(&relay, &held, &vault, &superior.public_key())
            .await
            .expect_err("a moderator must not grant against an admin");
        assert!(err.contains("outrank"), "refused for RANK: {err}");

        // Same seat, same channel, owner as the target: allowed.
        grant_channel_access(&relay, &held, &vault, &owner.public_key())
            .await
            .expect("the owner is not a rank target, and may still be handed a key");
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
        let owner_hex = owner.public_key().to_hex();
        assert!(
            roster.is_entitled(Some(&owner_hex), &owner_hex, &chan_hex, &[], &[]),
            "the owner's access role landed"
        );
    }

    #[tokio::test]
    async fn roles_v2_carries_private_access_as_overwrites_and_keys_follow_them() {
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "AclCarry", vec!["wss://r".into()], None).await.unwrap();
        let priv_id = create_private_channel(&relay, &community, "mods").await.unwrap();
        let (chan, cid_hex) = (crate::simd::hex::bytes_to_hex_32(&priv_id.0), crate::simd::hex::bytes_to_hex_32(&community.id().0));
        let owner_hex = community.owner().unwrap().to_hex();
        let (s, t) = (Keys::generate().public_key(), Keys::generate().public_key());
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        grant_channel_access(&relay, &held(), &priv_id, &s).await.unwrap();
        follow_control(&relay, &held()).await.unwrap();

        activate_roles_v2(&relay, &held(), crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
        follow_control(&relay, &held()).await.unwrap();
        let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
        assert!(roster.everyone.is_some() && roster.channel_roles(&chan).is_empty(), "on Roles v2, no scoped roles");
        assert!(roster.is_entitled(Some(&owner_hex), &s.to_hex(), &chan, &[], &[]), "the access holder still reads it");
        assert!(!roster.is_entitled(Some(&owner_hex), &t.to_hex(), &chan, &[], &[]), "nobody else does");
        assert_eq!(held().channel(&priv_id).unwrap().epoch, Epoch(1), "nobody lost access, so nothing rotated");

        // A member overwrite lets T in: their bundle carries the key, and S's deny rotates.
        grant_channel_access(&relay, &held(), &priv_id, &t).await.unwrap();
        assert!(bundle_of(&held(), BundleAudience::Member(t), None, None, None).channels.iter().any(|c| c.id == chan));
        revoke_channel_access(&relay, &held(), &priv_id, &s).await.unwrap();
        assert_eq!(held().channel(&priv_id).unwrap().epoch, Epoch(2), "the revoke rotated the channel");
        // The new key reaches who the Channel lets through, and not who it doesn't.
        let group = channel_rekey_group_key(&community.community_root, &priv_id, Epoch(2));
        let blobs: Vec<String> = fetch_rekey_chunks(&relay, &community, &group).await.unwrap().into_iter().flat_map(|c| c.blobs).map(|b| b.locator).collect();
        let me = me_pk().unwrap().to_bytes();
        let at = |pk: &PublicKey| rekey::blob_locator(&me, &pk.to_bytes(), RekeyScope::Channel(priv_id), Epoch(2));
        assert!(blobs.contains(&at(&t)) && !blobs.contains(&at(&s)), "T is keyed, S is not");
        // A peer folding the plane cold agrees.
        let eds = fetch_control(&relay, &held()).await;
        let f = fold_authority(&held(), &eds, &Floors::default());
        assert!(f.roles.is_entitled(Some(&owner_hex), &t.to_hex(), &chan, &[], &[]));
        assert!(!f.roles.is_entitled(Some(&owner_hex), &s.to_hex(), &chan, &[], &[]));
    }

    #[tokio::test]
    async fn a_channel_made_in_a_category_takes_its_rules_until_unsynced() {
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Sync", vec!["wss://r".into()], None).await.unwrap();
        activate_roles_v2(&relay, &community, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
        follow_control(&relay, &community).await.unwrap();
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let staff = create_category(&relay, &held(), "Announcements").await.unwrap();
        set_overwrite(&relay, &held(), staff, crate::community::roles::OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
        let news = create_channel_in(&relay, &held(), "news", false, Some(staff)).await.unwrap();
        let m = Keys::generate().public_key().to_hex();
        let may_send = |eds: &[ParsedEdition], ch: &ChannelId| {
            let r = fold_authority(&held(), eds, &Floors::default()).roles;
            r.channel_permissions(Some(&owner.public_key().to_hex()), &m, &crate::simd::hex::bytes_to_hex_32(&ch.0), false).contains(Permissions::SEND_MESSAGES)
        };
        let eds = fetch_control(&relay, &held()).await;
        assert!(!may_send(&eds, &news), "the new channel follows its Category's deny");
        assert!(may_send(&eds, &community.channels[0].id), "an unsynced channel doesn't");
        assert_eq!(crate::db::community::get_community_roles(&cid_hex).unwrap().syncs.get(&crate::simd::hex::bytes_to_hex_32(&news.0)), Some(&crate::simd::hex::bytes_to_hex_32(&staff)));
        set_channel_sync(&relay, &held(), &news, None).await.unwrap();
        assert!(may_send(&fetch_control(&relay, &held()).await, &news), "unsynced, it keeps no rules of its own");

        // A manager beneath a Role the Category names can't swap that rule in or out.
        let (x, top) = (Keys::generate(), "f5".repeat(32));
        publish_role_v2(&relay, &held(), &owner, &role_v2(&top, "Top", "B", 0), 1).await;
        let low = create_role_v2(&relay, &held(), "Mods", 0, Permissions::MANAGE_ROLES | Permissions::SEND_MESSAGES | Permissions::VIEW_CHANNEL).await.unwrap();
        set_member_roles(&relay, &held(), &x.public_key(), vec![low]).await.unwrap();
        follow_control(&relay, &held()).await.unwrap();
        set_overwrite(&relay, &held(), staff, crate::community::roles::OverwriteTarget::Role(top.clone()), Permissions::SEND_MESSAGES, 0).await.unwrap();
        let eid = crate::community::v2::derive::sync_locator(community.id(), &news);
        let prev = head_hash_on_relay(&relay, &held(), &eid).await;
        let version = fetch_control(&relay, &held()).await.iter().filter(|e| e.entity_id == eid).map(|e| e.version).max().unwrap();
        let content = crate::community::v2::roles::sync_content_json(&crate::simd::hex::bytes_to_hex_32(&news.0), Some(&crate::simd::hex::bytes_to_hex_32(&staff)));
        publish_marked(&relay, &held(), &x, vsk::CHANNEL_SYNC, &eid, version + 1, prev, &content).await;
        assert!(may_send(&fetch_control(&relay, &held()).await, &news), "the low manager's re-sync is refused");
    }

    /// A Roles v2 community with an admin `x` (Manage Roles, Manage Channels, the channel basics).
    async fn v2_bed_with_admin(name: &str) -> (TestBed, Actor, Keys, CommunityV2) {
        let (bed, owner, _m) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, name, bed.relays.clone(), None).await.unwrap();
        activate_roles_v2(&bed.relay, &community, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
        follow_control(&bed.relay, &community).await.unwrap();
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let x = Keys::generate();
        let bits = Permissions::MANAGE_ROLES | Permissions::MANAGE_CHANNELS | crate::community::v2::roles::EVERYONE_DEFAULT;
        let admin = create_role_v2(&bed.relay, &held, "Admin", 0, bits).await.unwrap();
        set_member_roles(&bed.relay, &held, &x.public_key(), vec![admin]).await.unwrap();
        follow_control(&bed.relay, &held).await.unwrap();
        (bed, owner, x, crate::db::community::load_community_v2(community.id()).unwrap().unwrap())
    }

    #[tokio::test]
    async fn a_new_community_starts_on_roles_v2_and_a_joiner_reads_it_so() {
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community_on_roles_v2(&bed.relay, "Born", bed.relays.clone(), None).await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let general = crate::simd::hex::bytes_to_hex_32(&community.channels[0].id.0);
        let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
        assert_eq!(roster.everyone, Some(Permissions(crate::community::v2::roles::EVERYONE_DEFAULT)), "@everyone holds the defaults");
        assert!(roster.legacy_channels.as_ref().is_some_and(|l| l.contains(&general)), "the genesis Channel is what the switch lists");
        assert!(roles_v2_held(&community));
        send_direct_invite(&bed.relay, &community, &member.keys.public_key(), None, None).await.unwrap();
        bed.swap_to(&member);
        let joined = accept_direct_invite(&bed.relay, &fetch_direct_invite(&bed.relay, &bed.relays, &member.keys.public_key()).await).await.unwrap();
        follow_control(&bed.relay, &joined).await.unwrap();
        let theirs = crate::db::community::get_community_roles(&cid_hex).unwrap();
        assert!(theirs.everyone.is_some() && theirs.channel_permissions(Some(&owner.keys.public_key().to_hex()), &member.keys.public_key().to_hex(), &general, false).contains(Permissions::SEND_MESSAGES), "a joiner folds it as Roles v2 and may post in general");
    }

    #[cfg(feature = "calls")]
    #[tokio::test]
    async fn who_may_join_a_voice_channel_and_who_is_heard_follow_the_roster() {
        use crate::calls::voice::{allowed_relay, may_connect, may_speak};
        use crate::community::roles::OverwriteTarget;
        let (bed, _owner, x, community) = v2_bed_with_admin("Voice").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let ch = held().channels[0].id;
        let (m, n) = (Keys::generate().public_key(), Keys::generate().public_key());
        assert!(may_connect(&held(), &ch, &m) && may_speak(&held(), &ch, &m), "@everyone connects and speaks by default");
        set_overwrite(&bed.relay, &held(), ch.0, OverwriteTarget::Member(m.to_hex()), 0, Permissions::SPEAK).await.unwrap();
        assert!(may_connect(&held(), &ch, &m) && !may_speak(&held(), &ch, &m), "denied Speak: in the call, not heard");
        set_overwrite(&bed.relay, &held(), ch.0, OverwriteTarget::Member(n.to_hex()), 0, Permissions::CONNECT).await.unwrap();
        assert!(!may_connect(&held(), &ch, &n), "denied Connect: never dialled or accepted");
        timeout_member(&bed.relay, &held(), &x.public_key(), 600).await.unwrap();
        assert!(may_connect(&held(), &ch, &x.public_key()) && !may_speak(&held(), &ch, &x.public_key()), "timed out: silent while it runs");
        set_members_banned(&bed.relay, community.id(), &[m], true).await.unwrap();
        assert!(!may_connect(&held(), &ch, &m), "banned: in no call");
        let n0: iroh::RelayUrl = iroh::defaults::prod::default_relay_map().urls::<Vec<iroh::RelayUrl>>()[0].clone();
        let own: iroh::RelayUrl = "https://voice.example.org/".parse().unwrap();
        assert!(allowed_relay(&n0, &held()) && !allowed_relay(&own, &held()), "iroh's defaults only, until the Community lists its own");
        let mut listed = held();
        listed.meta_extra.insert("voice_relays".into(), serde_json::json!(["https://voice.example.org/", "http://plain.example.org/"]));
        assert!(allowed_relay(&own, &listed) && !allowed_relay(&"http://plain.example.org/".parse().unwrap(), &listed), "and only over https");
    }

    #[tokio::test]
    async fn a_voice_directive_stands_only_from_who_holds_the_bit_and_outranks_the_target() {
        use super::super::voice::{self, Directive, Heard};
        let (bed, owner, x, community) = v2_bed_with_admin("Directives").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let ch = held().channels[0].id;
        let chan = crate::simd::hex::bytes_to_hex_32(&ch.0);
        let m = Keys::generate();
        let now = now_ms();
        for k in [m.public_key(), x.public_key(), owner.keys.public_key()] {
            voice::note(&chan, k, now, Heard { joined: true, transport: Some("iroh".into()), endpoint: Some(k.to_bytes()), ..Default::default() }, now);
        }
        let (secret, epoch) = held().channel_secret(held().channel(&ch).unwrap());
        let read = channel_group_key(&secret, &ch, epoch);
        let wrap = |actor: &Keys, target: &PublicKey, d: Directive| {
            let rumor = chat::build_voice_directive_rumor(actor.public_key(), &ch, epoch, target, d, None, None, now_ms());
            chat::seal_chat_rumor(&rumor, &read, actor, Timestamp::now(), true).unwrap().0
        };
        let me = m.public_key();
        let dispatch = |w: &nostr_sdk::prelude::Event| super::super::inbound::dispatch_wrap(w, &held(), &me, &crate::event_handler::NoOpEventHandler);
        dispatch(&wrap(&x, &m.public_key(), Directive::Mute));
        assert_eq!(voice::server_state(&chan, &m.public_key()), (false, false), "an admin without Mute Members mutes nobody");
        dispatch(&wrap(&owner.keys, &m.public_key(), Directive::Mute));
        assert_eq!(voice::server_state(&chan, &m.public_key()), (true, false), "the owner does");
        dispatch(&wrap(&x, &owner.keys.public_key(), Directive::Deafen));
        assert_eq!(voice::server_state(&chan, &owner.keys.public_key()), (false, false), "and nobody deafens the owner");
        dispatch(&wrap(&owner.keys, &x.public_key(), Directive::Deafen));
        assert_eq!(voice::server_state(&chan, &x.public_key()), (false, true));
        assert!(voice::present(&chan, now_ms()).iter().any(|p| p.author == m.public_key() && p.server_muted));
        act_as(&x);
        assert!(send_voice_directive(&bed.relay, &held(), &ch, &m.public_key(), Directive::Mute, None).await.is_err(), "nor can they send one");
        act_as(&owner.keys);
        assert!(send_voice_directive(&bed.relay, &held(), &ch, &m.public_key(), Directive::Move, Some([9; 32])).await.is_err(), "a move needs a voice channel to go to");
        // A same-ms tie keeps them muted: the lift is sent a moment after the mute.
        tokio::time::sleep(std::time::Duration::from_millis(2)).await;
        send_voice_directive(&bed.relay, &held(), &ch, &m.public_key(), Directive::Unmute, None).await.unwrap();
        assert_eq!(voice::server_state(&chan, &m.public_key()), (false, false));
    }

    #[tokio::test]
    async fn a_refounding_seals_each_private_channel_again_under_its_new_epoch() {
        let (bed, _owner, _x, community) = v2_bed_with_admin("Refound").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let ch = create_private_channel(&bed.relay, &held(), "inner").await.unwrap();
        let before = held().channel(&ch).unwrap().epoch;
        refound_community(&bed.relay, &held(), &[Keys::generate().public_key()]).await.unwrap();
        let after = held().channel(&ch).cloned().unwrap();
        assert!(after.epoch > before, "the Refounding mints the channel a fresh epoch");
        assert_eq!(after.sealed.as_ref().map(|s| (s.epoch, s.open)), Some((after.epoch.0, true)), "and seals its metadata under it, for whoever joins at it");
        assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().resealed, 0, "leaving the duty nothing");
    }

    #[tokio::test]
    async fn a_channel_manager_makes_a_private_channel_and_is_let_in_as_its_creator() {
        let (bed, owner, x, community) = v2_bed_with_admin("Made").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let (owner_hex, x_hex) = (owner.keys.public_key().to_hex(), x.public_key().to_hex());
        act_as(&x);
        let ch = create_private_channel(&bed.relay, &held(), "mods").await.unwrap();
        let chan = crate::simd::hex::bytes_to_hex_32(&ch.0);
        assert!(crate::db::community::get_community_roles(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap().is_entitled(Some(&owner_hex), &x_hex, &chan, &[], &[]), "in from the start");
        send_chat_message(&bed.relay, &held(), &ch, "made by a mod", None, &[], vec![]).await.unwrap();
        // The owner's device reads the creator from the sealed metadata, and its duty keeps them.
        act_as(&owner.keys);
        follow_control(&bed.relay, &held()).await.unwrap();
        let fold = || async { fold_authority(&held(), &fetch_control(&bed.relay, &held()).await, &Floors::default()).roles };
        let roster = fold().await;
        assert!(roster.is_entitled(Some(&owner_hex), &x_hex, &chan, &[], &[]), "the creator, on a fold of the plane");
        assert!(!roster.is_entitled(Some(&owner_hex), &Keys::generate().public_key().to_hex(), &chan, &[], &[]), "and no one else");
        let epoch = held().channel(&ch).unwrap().epoch;
        assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().cut, 0);
        assert_eq!(held().channel(&ch).unwrap().epoch, epoch, "no rotation cuts them");
        // An outranking member's deny still shuts them out, and so does losing Manage Channels.
        set_overwrite(&bed.relay, &held(), ch.0, crate::community::roles::OverwriteTarget::Member(x_hex.clone()), 0, Permissions::VIEW_CHANNEL).await.unwrap();
        assert!(!fold().await.is_entitled(Some(&owner_hex), &x_hex, &chan, &[], &[]), "an explicit deny wins");
        assert!(held().channel(&ch).unwrap().epoch > epoch, "and rotates them out");
        set_overwrite(&bed.relay, &held(), ch.0, crate::community::roles::OverwriteTarget::Member(x_hex.clone()), 0, 0).await.unwrap();
        assert!(fold().await.is_entitled(Some(&owner_hex), &x_hex, &chan, &[], &[]), "the creator rule stands once the deny goes");
        set_member_roles(&bed.relay, &held(), &x.public_key(), vec![]).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        assert!(!fold().await.is_entitled(Some(&owner_hex), &x_hex, &chan, &[], &[]), "only while they manage channels");
    }

    #[tokio::test]
    async fn a_reader_takes_the_key_its_creator_delivers_though_it_cant_see_the_creator_rule() {
        let (bed, _owner, x, community) = v2_bed_with_admin("Keyless").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        act_as(&x);
        let ch = create_private_channel(&bed.relay, &held(), "mods").await.unwrap();
        let chan = crate::simd::hex::bytes_to_hex_32(&ch.0);
        let m = Keys::generate();
        set_overwrite(&bed.relay, &held(), ch.0, crate::community::roles::OverwriteTarget::Member(m.public_key().to_hex()), Permissions::VIEW_CHANNEL, 0).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().delivered, 0, "the creator delivered with the change itself");
        // M's device: keyless, and its fold can't open the seal that names the creator.
        let mut c = held();
        let e = c.channels.iter_mut().find(|e| e.id.0 == ch.0).unwrap();
        (e.key, e.sealed) = (None, None);
        e.meta_extra.clear();
        crate::db::community::save_community_v2(&c).unwrap();
        let mut roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
        roster.creators.clear();
        crate::db::community::set_community_roles(&cid_hex, &roster, crate::db::community::get_community_roles_at(&cid_hex).unwrap_or(0)).unwrap();
        assert!(!roster.is_entitled(None, &x.public_key().to_hex(), &chan, &[], &[]), "to M, the creator isn't entitled");
        act_as(&m);
        assert_eq!(collect_access(&bed.relay, &held()).await.unwrap(), 1, "but manages channels, so its delivery counts");
        absorb_parked_channel_keys(&held(), &crate::db::current_session());
        assert!(held().channel(&ch).unwrap().key.is_some(), "and the key is taken");
        act_as(&x);
    }

    #[tokio::test]
    async fn a_creator_named_outside_the_seal_lets_nobody_in() {
        let (bed, owner, x, community) = v2_bed_with_admin("Plain").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let ch = create_private_channel(&bed.relay, &held(), "inner").await.unwrap();
        let chan = crate::simd::hex::bytes_to_hex_32(&ch.0);
        let mut c = held();
        let x_hex = x.public_key().to_hex();
        let entry = c.channels.iter_mut().find(|e| e.id.0 == ch.0).unwrap();
        entry.meta_extra.insert("creator".into(), x_hex.clone().into());
        assert_eq!(entry.creator(), Some(x_hex.as_str()), "read from the opened seal");
        entry.sealed = None;
        assert_eq!(entry.creator(), None, "a plain edition names no creator: anyone with Manage Channels could write one");
        let roster = fold_authority(&c, &fetch_control(&bed.relay, &c).await, &Floors::default()).roles;
        assert!(!roster.is_entitled(Some(&owner.keys.public_key().to_hex()), &x_hex, &chan, &[], &[]));
    }

    #[tokio::test]
    async fn a_private_channel_stays_closed_whatever_everyone_is_allowed() {
        // Privacy doesn't hang on an @everyone deny a manager could clear: a private
        // Channel opens only to a Role's or a member's allow.
        let (bed, owner, x, community) = v2_bed_with_admin("Closed").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let ch = create_private_channel(&bed.relay, &held(), "admins").await.unwrap();
        let chan = crate::simd::hex::bytes_to_hex_32(&ch.0);
        let owner_hex = owner.keys.public_key().to_hex();
        let m = Keys::generate().public_key().to_hex();
        let fold = || async { fold_authority(&held(), &fetch_control(&bed.relay, &held()).await, &Floors::default()).roles };
        assert!(!fold().await.is_entitled(Some(&owner_hex), &m, &chan, &[], &[]));
        assert!(!fold().await.is_entitled(Some(&owner_hex), &x.public_key().to_hex(), &chan, &[], &[]), "not even an admin, until let in");
        // The admin allows @everyone View there: still closed.
        act_as(&x);
        set_overwrite(&bed.relay, &held(), ch.0, crate::community::roles::OverwriteTarget::Everyone, Permissions::VIEW_CHANNEL, 0).await.unwrap();
        assert!(!fold().await.is_entitled(Some(&owner_hex), &m, &chan, &[], &[]), "@everyone never opens a private channel");
        assert!(fold().await.channel_permissions(Some(&owner_hex), &m, &chan, false).contains(Permissions::VIEW_CHANNEL), "a public one it would");
        act_as(&owner.keys);
    }

    #[tokio::test]
    async fn a_member_overwrite_cant_be_replaced_through_a_role_of_the_same_bytes() {
        let (bed, owner, x, community) = v2_bed_with_admin("Alias").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let ch = create_private_channel(&bed.relay, &held(), "inner").await.unwrap();
        let (chan, owner_hex) = (crate::simd::hex::bytes_to_hex_32(&ch.0), owner.keys.public_key().to_hex());
        grant_channel_access(&bed.relay, &held(), &ch, &x.public_key()).await.unwrap();
        revoke_channel_access(&bed.relay, &held(), &ch, &x.public_key()).await.unwrap();
        // X mints a Role whose id is X's own key, beneath X, then writes an overwrite for
        // that Role at the coordinate of X's Member overwrite.
        follow_control(&bed.relay, &held()).await.unwrap();
        publish_role_v2(&bed.relay, &held(), &x, &role_v2(&x.public_key().to_hex(), "Alias", "z", 0), 1).await;
        let member_eid = {
            let t = crate::community::v2::roles::overwrite_target_bytes(community.id(), &crate::community::roles::OverwriteTarget::Member(x.public_key().to_hex())).unwrap();
            crate::community::v2::derive::acl_locator(community.id(), &ch.0, &t)
        };
        let prev = head_hash_on_relay(&bed.relay, &held(), &member_eid).await;
        let version = fetch_control(&bed.relay, &held()).await.iter().filter(|e| e.entity_id == member_eid).map(|e| e.version).max().unwrap();
        let o = crate::community::roles::Overwrite { scope: chan.clone(), target: crate::community::roles::OverwriteTarget::Role(x.public_key().to_hex()), allow: Permissions(0), deny: Permissions(0) };
        publish_marked(&bed.relay, &held(), &x, vsk::CHANNEL_ACL, &member_eid, version + 1, prev, &crate::community::v2::roles::overwrite_content_json(&o)).await;
        let f = fold_authority(&held(), &fetch_control(&bed.relay, &held()).await, &Floors::default());
        assert!(f.roles.overwrites.iter().any(|o| o.target == crate::community::roles::OverwriteTarget::Member(x.public_key().to_hex()) && o.deny.contains(Permissions::VIEW_CHANNEL)), "the owner's deny stands");
        assert!(!f.roles.is_entitled(Some(&owner_hex), &x.public_key().to_hex(), &chan, &[], &[]));
    }

    #[tokio::test]
    async fn a_banned_member_loses_every_overwrite_and_every_rekey() {
        let (bed, owner, _x, community) = v2_bed_with_admin("BanAcl").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let ch = create_private_channel(&bed.relay, &held(), "inner").await.unwrap();
        let (chan, owner_hex) = (crate::simd::hex::bytes_to_hex_32(&ch.0), owner.keys.public_key().to_hex());
        let (b, keep) = (Keys::generate().public_key(), Keys::generate().public_key());
        grant_channel_access(&bed.relay, &held(), &ch, &b).await.unwrap();
        grant_channel_access(&bed.relay, &held(), &ch, &keep).await.unwrap();
        set_members_banned(&bed.relay, held().id(), &[b], true).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        let f = fold_authority(&held(), &fetch_control(&bed.relay, &held()).await, &Floors::default());
        assert!(!f.roles.is_entitled(Some(&owner_hex), &b.to_hex(), &chan, &[], &[]), "a ban drops their overwrite");
        assert!(f.roles.is_entitled(Some(&owner_hex), &keep.to_hex(), &chan, &[], &[]), "and only theirs");
        // The next rotation of the channel keys the one who kept access, not the banned.
        let other = Keys::generate().public_key();
        grant_channel_access(&bed.relay, &held(), &ch, &other).await.unwrap();
        revoke_channel_access(&bed.relay, &held(), &ch, &other).await.unwrap();
        let now = held();
        let epoch = now.channel(&ch).unwrap().epoch;
        let group = channel_rekey_group_key(&now.community_root, &ch, epoch);
        let blobs: Vec<String> = fetch_rekey_chunks(&bed.relay, &now, &group).await.unwrap().into_iter().flat_map(|c| c.blobs).map(|b| b.locator).collect();
        let me = me_pk().unwrap().to_bytes();
        let at = |pk: &PublicKey| rekey::blob_locator(&me, &pk.to_bytes(), RekeyScope::Channel(ch), epoch);
        assert!(blobs.contains(&at(&keep)) && !blobs.contains(&at(&b)));
    }

    #[tokio::test]
    async fn a_roster_read_without_everyone_changes_nothing() {
        let (bed, owner, x, community) = v2_bed_with_admin("Degraded").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let everyone = crate::community::v2::derive::everyone_locator(community.id());
        let blind = Hiding { inner: &bed.relay, group: control::ControlPlane::of(&held()).write_group().unwrap(), hide: Box::new(move |e| e.entity_id == everyone) };
        let before = fetch_control(&bed.relay, &held()).await.len();
        act_as(&x);
        forget_held(&held());
        let err = set_everyone(&blind, &held(), 0).await.unwrap_err();
        assert!(err.contains("couldn't be read"), "{err}");
        assert_eq!(fetch_control(&bed.relay, &held()).await.len(), before, "nothing was published");
        // The owner may still restate it: that is how a refused head is repaired.
        act_as(&owner.keys);
        assert!(set_everyone(&blind, &held(), crate::community::v2::roles::EVERYONE_DEFAULT).await.is_ok());
    }

    #[tokio::test]
    async fn a_withheld_overwrite_stays_as_this_device_held_it() {
        let (bed, owner, _x, community) = v2_bed_with_admin("WithheldAcl").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let ch = create_private_channel(&bed.relay, &held(), "inner").await.unwrap();
        let m = Keys::generate().public_key();
        grant_channel_access(&bed.relay, &held(), &ch, &m).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let floors: Floors = crate::db::community::get_all_edition_heads_full(&cid_hex).unwrap().into_iter().filter(|(_, f)| f.0 == held().root_epoch.0).map(|(e, f)| (e, (f.1, f.2, f.3, f.4, f.5))).collect();
        let served: Vec<ParsedEdition> = fetch_control(&bed.relay, &held()).await.into_iter().filter(|e| e.vsk != vsk::CHANNEL_ACL).collect();
        let f = fold_authority(&held(), &served, &floors);
        assert!(f.roles.is_entitled(Some(&owner.keys.public_key().to_hex()), &m.to_hex(), &crate::simd::hex::bytes_to_hex_32(&ch.0), &[], &[]), "withholding doesn't revoke");
    }

    #[tokio::test]
    async fn overwrites_and_syncs_cross_a_refounding_and_readers_agree() {
        let (bed, owner, _x, community) = v2_bed_with_admin("AclCarry2").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let owner_hex = owner.keys.public_key().to_hex();
        let ch = create_private_channel(&bed.relay, &held(), "inner").await.unwrap();
        let staff = create_role_v2(&bed.relay, &held(), "Staff", 0, 0).await.unwrap();
        set_overwrite(&bed.relay, &held(), ch.0, crate::community::roles::OverwriteTarget::Role(staff.clone()), Permissions::VIEW_CHANNEL, 0).await.unwrap();
        let m = Keys::generate().public_key();
        set_member_roles(&bed.relay, &held(), &m, vec![staff]).await.unwrap();
        let cat = create_category(&bed.relay, &held(), "Lobby").await.unwrap();
        set_overwrite(&bed.relay, &held(), cat, crate::community::roles::OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
        let news = create_channel_in(&bed.relay, &held(), "news", false, Some(cat)).await.unwrap();
        // A sync past its first edition is judged against its predecessor, which must cross too.
        set_channel_sync(&bed.relay, &held(), &news, None).await.unwrap();
        set_channel_sync(&bed.relay, &held(), &news, Some(cat)).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        let (chan, news_hex) = (crate::simd::hex::bytes_to_hex_32(&ch.0), crate::simd::hex::bytes_to_hex_32(&news.0));
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let mut epoch = community.root_epoch;
        for round in 0..2 {
            set_members_banned(&bed.relay, held().id(), &[Keys::generate().public_key()], true).await.unwrap();
            follow_control(&bed.relay, &held()).await.unwrap();
            let now = held();
            assert_ne!(now.root_epoch, epoch, "the ban re-founded");
            epoch = now.root_epoch;
            let eds = fetch_control(&bed.relay, &now).await;
            let floors: Floors = crate::db::community::get_all_edition_heads_full(&cid_hex).unwrap().into_iter().filter(|(_, f)| f.0 == now.root_epoch.0).map(|(e, f)| (e, (f.1, f.2, f.3, f.4, f.5))).collect();
            let probe = Keys::generate().public_key().to_hex();
            for (who, f) in [("cold", fold_authority(&now, &eds, &Floors::default())), ("floored", fold_authority(&now, &eds, &floors))] {
                assert!(f.roles.is_entitled(Some(&owner_hex), &m.to_hex(), &chan, &[], &[]), "{round} {who}: the role's allow crossed");
                assert!(!f.roles.is_entitled(Some(&owner_hex), &probe, &chan, &[], &[]), "{round} {who}: and nobody else got in");
                assert_eq!(f.roles.syncs.get(&news_hex), Some(&crate::simd::hex::bytes_to_hex_32(&cat)), "{round} {who}: the sync crossed");
                assert!(!f.roles.channel_permissions(Some(&owner_hex), &probe, &news_hex, false).contains(Permissions::SEND_MESSAGES), "{round} {who}: and it binds");
            }
        }
    }

    #[tokio::test]
    async fn a_member_without_add_reactions_cant_react() {
        use crate::community::roles::Permissions;
        async fn react(relay: &MemoryRelay, community: &CommunityV2, ch: &ChannelId, owner: &str) -> Result<String, String> {
            send_reaction(relay, community, ch, &"ab".repeat(32), owner, super::super::kind::MESSAGE, "+", None).await
        }
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Reacts", vec!["wss://r".into()], None).await.unwrap();
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let (ch, owner_hex, m) = (community.channels[0].id, owner.public_key().to_hex(), Keys::generate());
        act_as(&m);
        assert!(react(&relay, &held(), &ch, &owner_hex).await.is_ok(), "the legacy roster refuses no reaction");
        act_as(&owner);
        activate_roles_v2(&relay, &held(), crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
        act_as(&m);
        assert!(react(&relay, &held(), &ch, &owner_hex).await.is_ok(), "@everyone reacts by default");
        act_as(&owner);
        set_everyone(&relay, &held(), crate::community::v2::roles::EVERYONE_DEFAULT & !Permissions::ADD_REACTIONS).await.unwrap();
        act_as(&m);
        let err = react(&relay, &held(), &ch, &owner_hex).await.unwrap_err();
        assert!(err.contains("can't react"), "{err}");
        act_as(&owner);
        assert!(react(&relay, &held(), &ch, &owner_hex).await.is_ok(), "the owner holds everything");
    }

    #[tokio::test]
    async fn a_timeout_silences_until_it_ends_or_is_lifted() {
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Timeout", vec!["wss://r".into()], None).await.unwrap();
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let (m, peer) = (Keys::generate(), Keys::generate());
        let ch = community.channels[0].id;
        timeout_member(&relay, &held(), &m.public_key(), 600).await.unwrap();
        let t = community_timeouts(&held()).unwrap();
        let (from, until) = t[&m.public_key()];
        assert!(until >= from + 600 && until <= from + 601);
        act_as(&m);
        let err = send_chat_message(&relay, &held(), &ch, "hi", None, &[], vec![]).await.unwrap_err();
        assert!(err.contains("timed out"), "{err}");
        let target = "ab".repeat(32);
        let err = send_reaction(&relay, &held(), &ch, &target, &owner.public_key().to_hex(), super::super::kind::MESSAGE, "+", None).await.unwrap_err();
        assert!(err.contains("timed out"), "nor react: {err}");
        let err = send_edit(&relay, &held(), &ch, &target, "rewritten", &[]).await.unwrap_err();
        assert!(err.contains("timed out"), "nor edit: {err}");
        // A peer with no standing can't lift it, nor time anyone out.
        act_as(&peer);
        assert!(timeout_member(&relay, &held(), &m.public_key(), 0).await.is_err());
        act_as(&owner);
        // A co-moderator's clock runs ahead: the lift still outranks their Timeout.
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let (mut events, cursor) = crate::db::community::get_guestbook(&cid_hex).unwrap();
        let ahead = now_ms() + 600_000;
        events.push(guestbook::GuestbookEvent {
            rumor_id: [8; 32],
            entry: guestbook::GuestbookEntry::Timeout { actor: owner.public_key(), target: m.public_key(), until_secs: ahead / 1000 + 600, citation: None, at_ms: ahead },
            epoch: Some(held().root_epoch.0),
            observed_at: None,
        });
        crate::db::community::set_guestbook(&cid_hex, &events, cursor).unwrap();
        timeout_member(&relay, &held(), &m.public_key(), 0).await.unwrap();
        assert!(community_timeouts(&held()).unwrap().is_empty(), "a Timeout in the past lifts it");
        act_as(&m);
        assert!(send_chat_message(&relay, &held(), &ch, "back", None, &[], vec![]).await.is_ok());
        act_as(&owner);
    }

    #[tokio::test]
    async fn a_running_timeout_crosses_a_refounding() {
        let (bed, owner, _x, community) = v2_bed_with_admin("TimeoutCarry").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let (m, ended, unseen) = (Keys::generate().public_key(), Keys::generate().public_key(), Keys::generate().public_key());
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        // Issued well before the Refounding, so a window it moved would show.
        let (mut events, cursor) = crate::db::community::get_guestbook(&cid_hex).unwrap();
        let issued = now_ms() - 100_000;
        events.push(guestbook::GuestbookEvent {
            rumor_id: [7; 32],
            entry: guestbook::GuestbookEntry::Timeout { actor: owner.keys.public_key(), target: m, until_secs: issued / 1000 + 600, citation: None, at_ms: issued },
            epoch: Some(held().root_epoch.0),
            observed_at: None,
        });
        crate::db::community::set_guestbook(&cid_hex, &events, cursor).unwrap();
        timeout_member(&bed.relay, &held(), &ended, 600).await.unwrap();
        timeout_member(&bed.relay, &held(), &ended, 0).await.unwrap();
        timeout_member(&bed.relay, &held(), &unseen, 600).await.unwrap();
        let before_lift = crate::db::community::get_guestbook(&cid_hex).unwrap();
        timeout_member(&bed.relay, &held(), &unseen, 0).await.unwrap();
        // A lift another device published, which this one hasn't read.
        crate::db::community::set_guestbook(&cid_hex, &before_lift.0, before_lift.1).unwrap();
        let from = issued / 1000;
        refound_community(&bed.relay, &held(), &[]).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        assert_ne!(held().root_epoch, community.root_epoch, "the ban re-founded");
        // A device that never read the old Guestbook.
        crate::db::community::set_guestbook(&cid_hex, &[], 0).unwrap();
        sync_guestbook(&bed.relay, &held()).await.unwrap();
        let t = community_timeouts(&held()).unwrap();
        assert_eq!(t.get(&m).map(|w| w.0), Some(from), "the running Timeout crossed, its window unmoved");
        assert!(!t.contains_key(&ended), "a lifted one stayed lifted");
        assert!(!t.contains_key(&unseen), "even one lifted where the refounder hadn't read yet");
        let _ = owner;
    }

    #[tokio::test]
    async fn a_builder_cant_open_a_channel_in_a_restricted_category() {
        let (bed, _owner, _x, community) = v2_bed_with_admin("Builder").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let builders = create_role_v2(&bed.relay, &held(), "Builders", 0, Permissions::MANAGE_CHANNELS).await.unwrap();
        let y = Keys::generate();
        set_member_roles(&bed.relay, &held(), &y.public_key(), vec![builders]).await.unwrap();
        let (open, staff) = (create_category(&bed.relay, &held(), "Open").await.unwrap(), create_category(&bed.relay, &held(), "Staff").await.unwrap());
        set_overwrite(&bed.relay, &held(), staff, crate::community::roles::OverwriteTarget::Everyone, 0, Permissions::VIEW_CHANNEL).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        act_as(&y);
        let err = create_channel_in(&bed.relay, &held(), "leak", false, Some(staff)).await.unwrap_err();
        assert!(err.contains("Manage Roles"), "{err}");
        assert!(create_channel_in(&bed.relay, &held(), "fine", false, Some(open)).await.is_ok(), "a Category with no rules of its own takes anyone who may make channels");
    }

    #[tokio::test]
    async fn rules_reaching_a_private_channel_this_device_cant_read_are_refused() {
        let (bed, _owner, _x, community) = v2_bed_with_admin("Keyless").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let ch = create_private_channel(&bed.relay, &held(), "dark").await.unwrap();
        let cat = create_category(&bed.relay, &held(), "Vault").await.unwrap();
        set_channel_sync(&bed.relay, &held(), &ch, Some(cat)).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        let mut keyless = held();
        keyless.channels.iter_mut().find(|c| c.id.0 == ch.0).unwrap().key = None;
        crate::db::community::save_community_v2(&keyless).unwrap();
        let err = set_overwrite(&bed.relay, &held(), cat, crate::community::roles::OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap_err();
        assert!(err.contains("don't have access to it yourself"), "through its Category: {err}");
        let err = set_channel_sync(&bed.relay, &held(), &ch, None).await.unwrap_err();
        assert!(err.contains("don't have access to it yourself"), "or its sync: {err}");
    }

    #[tokio::test]
    async fn a_channel_squatting_a_grant_coordinate_cant_block_the_grant() {
        // A channel edition at a member's grant coordinate, before their first Grant, leaves a
        // control floor there; it must not hold the Grant to a version it never had.
        let (bed, owner, x, community) = v2_bed_with_admin("Squat").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let builders = create_role_v2(&bed.relay, &held(), "Builders", 0, Permissions::MANAGE_CHANNELS).await.unwrap();
        let readers = create_role_v2(&bed.relay, &held(), "Readers", 0, 0).await.unwrap();
        let s = Keys::generate();
        set_member_roles(&bed.relay, &held(), &s.public_key(), vec![builders]).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        let m = Keys::generate().public_key();
        let spot = super::super::derive::grant_locator(community.id(), &m.to_bytes());
        let squat = serde_json::to_string(&control::ChannelMetadata { name: "squat".into(), ..Default::default() }).unwrap();
        publish_marked(&bed.relay, &held(), &s, vsk::CHANNEL_METADATA, &spot, 50, None, &squat).await;
        follow_control(&bed.relay, &held()).await.unwrap();
        let (cid_hex, spot_hex) = (crate::simd::hex::bytes_to_hex_32(&community.id().0), crate::simd::hex::bytes_to_hex_32(&spot));
        let squatted = crate::db::community::get_all_edition_heads_full(&cid_hex).unwrap()[&spot_hex];
        let before = crate::db::community::get_community_roles(&cid_hex).unwrap();
        act_as(&x);
        set_member_roles(&bed.relay, &held(), &m, vec![readers.clone()]).await.unwrap();
        act_as(&owner.keys);
        // Another device saw the squat but not this publish.
        crate::db::community::set_community_roles(&cid_hex, &before, 0).unwrap();
        crate::db::community::delete_edition_head(&cid_hex, &spot_hex).unwrap();
        let (epoch, v, hash, inner, author, _) = squatted;
        crate::db::community::set_family_head_at_epoch(&cid_hex, &spot_hex, v, &hash, &inner.unwrap(), &author.unwrap(), epoch, crate::db::community::FLOOR_CONTROL).unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        let roster = crate::db::community::get_community_roles(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap();
        assert!(roster.roles_of(&m.to_hex()).any(|r| r.role_id == readers), "the admin's Grant stands");
    }

    /// Post `text` straight to a plane, as a client ignoring the ledger would.
    #[allow(clippy::too_many_arguments)]
    async fn post_raw(relay: &MemoryRelay, community: &CommunityV2, author: &Keys, channel: &ChannelId, group: &GroupKey, epoch: Epoch, wepoch: Option<Epoch>, text: &str, at_ms: u64) {
        post_certified(relay, community, author, channel, group, epoch, wepoch.map(|w| (w, None)), text, at_ms).await
    }

    /// [`post_raw`], at a writer epoch with the author's certificate for it, as a client posts.
    #[allow(clippy::too_many_arguments)]
    async fn post_certified(relay: &MemoryRelay, community: &CommunityV2, author: &Keys, channel: &ChannelId, group: &GroupKey, epoch: Epoch, writer: Option<(Epoch, Option<[u8; 64]>)>, text: &str, at_ms: u64) {
        let rumor = chat::build_message_rumor(author.public_key(), channel, epoch, text, None, &[], vec![], at_ms);
        let rumor = match writer {
            Some((w, cert)) => chat::with_writer(rumor, w, cert.as_ref()),
            None => rumor,
        };
        let (wrap, _) = chat::seal_chat_rumor(&rumor, group, author, Timestamp::from_secs(at_ms / 1000), false).unwrap();
        relay.publish(&wrap, &community.relays).await.unwrap();
    }

    async fn channel_texts(relay: &MemoryRelay, community: &CommunityV2, channel: &ChannelId) -> Vec<String> {
        fetch_channel(relay, community, channel, 50)
            .await
            .unwrap()
            .into_iter()
            .filter_map(|f| match f.event {
                ChatEvent::Message { opened, .. } => Some(opened.rumor.content.clone()),
                _ => None,
            })
            .collect()
    }

    /// What a handler was shown: a message's text and whether it rang, an update's text after
    /// `~` with its mark, a removal's id after `-`.
    #[derive(Default)]
    struct Shown(std::sync::Mutex<Vec<(String, bool)>>);

    impl crate::event_handler::InboundEventHandler for Shown {
        fn on_community_message(&self, _chat: &str, m: &crate::types::Message, is_new: bool) {
            self.0.lock().unwrap().push((m.content.clone(), is_new));
        }
        fn on_community_update(&self, _chat: &str, _target: &str, m: &crate::types::Message) {
            self.0.lock().unwrap().push((format!("~{}", m.content), m.unauthorized));
        }
        fn on_community_removed(&self, _chat: &str, target: &str) {
            self.0.lock().unwrap().push((format!("-{target}"), false));
        }
    }

    impl Shown {
        fn take(&self) -> Vec<(String, bool)> {
            std::mem::take(&mut *self.0.lock().unwrap())
        }
    }

    /// An owner and a member (a manager when `manages`) in a community whose #general the owner
    /// has restricted, both having read it so.
    async fn restricted_bed(manages: bool) -> (TestBed, Actor, Actor, CommunityV2, ChannelId) {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, member) = TestBed::new();
        let held = |c: &CommunityV2| crate::db::community::load_community_v2(c.id()).unwrap().unwrap();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Held", bed.relays.clone(), None).await.unwrap();
        activate_roles_v2(&bed.relay, &community, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
        follow_control(&bed.relay, &community).await.unwrap();
        let general = community.channels[0].id;
        let bits = if manages { Permissions::MANAGE_CHANNELS } else { 0 };
        let role = create_role_v2(&bed.relay, &held(&community), "Member", 0, bits).await.unwrap();
        set_member_roles(&bed.relay, &held(&community), &member.keys.public_key(), vec![role]).await.unwrap();
        send_direct_invite(&bed.relay, &held(&community), &member.keys.public_key(), None, None).await.unwrap();
        bed.swap_to(&member);
        accept_direct_invite(&bed.relay, &fetch_direct_invite(&bed.relay, &bed.relays, &member.keys.public_key()).await).await.unwrap();
        follow_control(&bed.relay, &held(&community)).await.unwrap();
        bed.swap_to(&owner);
        set_overwrite(&bed.relay, &held(&community), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
        bed.swap_to(&member);
        follow_control(&bed.relay, &held(&community)).await.unwrap();
        collect_writers(&bed.relay, &held(&community)).await.unwrap();
        assert!(held(&community).channel(&general).unwrap().restricted());
        let community = held(&community);
        (bed, owner, member, community, general)
    }

    /// The reactions `community`'s `channel` shows a reader: (author, emoji).
    async fn channel_reactions(relay: &MemoryRelay, community: &CommunityV2, channel: &ChannelId) -> Vec<(PublicKey, String)> {
        fetch_channel(relay, community, channel, 50)
            .await
            .unwrap()
            .into_iter()
            .filter_map(|f| match f.event {
                ChatEvent::Reaction { opened, emoji, .. } => Some((opened.author, emoji)),
                _ => None,
            })
            .collect()
    }

    #[tokio::test]
    async fn a_locked_channel_takes_every_write_only_from_whom_it_lets_write() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, member) = TestBed::new();
        let held = |c: &CommunityV2| crate::db::community::load_community_v2(c.id()).unwrap().unwrap();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Locked", bed.relays.clone(), None).await.unwrap();
        activate_roles_v2(&bed.relay, &community, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
        follow_control(&bed.relay, &community).await.unwrap();
        let general = community.channels[0].id;
        let reactor = create_role_v2(&bed.relay, &held(&community), "Reactor", 0, 0).await.unwrap();
        set_member_roles(&bed.relay, &held(&community), &member.keys.public_key(), vec![reactor.clone()]).await.unwrap();
        send_direct_invite(&bed.relay, &held(&community), &member.keys.public_key(), None, None).await.unwrap();
        bed.swap_to(&member);
        accept_direct_invite(&bed.relay, &fetch_direct_invite(&bed.relay, &bed.relays, &member.keys.public_key()).await).await.unwrap();
        follow_control(&bed.relay, &held(&community)).await.unwrap();

        // The Reactor Role may react; @everyone may write nothing at all.
        bed.swap_to(&owner);
        set_overwrite(&bed.relay, &held(&community), general.0, OverwriteTarget::Role(reactor), Permissions::ADD_REACTIONS, 0).await.unwrap();
        let nothing = Permissions::SEND_MESSAGES | Permissions::ADD_REACTIONS | Permissions::CONNECT;
        set_overwrite(&bed.relay, &held(&community), general.0, OverwriteTarget::Everyone, 0, nothing).await.unwrap();
        let ch = held(&community).channel(&general).cloned().unwrap();
        assert!(ch.restricted() && ch.locked(), "locking mints a Locked writer epoch");
        let rules = send_chat_message(&bed.relay, &held(&community), &general, "the rules", None, &[], vec![]).await.unwrap();
        let owner_hex = owner.keys.public_key().to_hex();

        bed.swap_to(&member);
        follow_control(&bed.relay, &held(&community)).await.unwrap();
        collect_writers(&bed.relay, &held(&community)).await.unwrap();
        let ch = held(&community).channel(&general).cloned().unwrap();
        let (live, ..) = writing::live_writer(&held(&community), &ch).expect("a reactor holds the key");
        assert!(writing::my_cert(&held(&community), &ch, live).is_none(), "but no whole certificate");
        assert_eq!(writing::my_scoped_cert(&held(&community), &ch, live).map(|(_, r)| r), Some(Permissions::ADD_REACTIONS), "a scoped one, for reactions");
        send_reaction(&bed.relay, &held(&community), &general, &rules, &owner_hex, super::super::kind::MESSAGE, "👍", None).await.unwrap();
        assert!(send_chat_message(&bed.relay, &held(&community), &general, "may I post?", None, &[], vec![]).await.is_err(), "a reactor can't post");
        assert!(!can_post(&held(&community), &general));
        // Nor does a post they force out at the writer address stand on a scoped certificate.
        let (_, _, writer) = writing::live_writer(&held(&community), &ch).unwrap();
        let read = channel_group_key(&community.community_root, &general, community.root_epoch);
        let at_writer = GroupKey::from_parts(writer.keys().clone(), read.conv_key().clone());
        let (cert, rights) = writing::my_scoped_cert(&held(&community), &ch, live).unwrap();
        let forced = chat::with_writer_cert(chat::build_message_rumor(member.keys.public_key(), &general, community.root_epoch, "forced", None, &[], vec![], now_ms()), live, Some(chat::WriterCert::Scoped(cert, rights)));
        let (wrap, _) = chat::seal_chat_rumor(&forced, &at_writer, &member.keys, Timestamp::from_secs(now_ms() / 1000), false).unwrap();
        bed.relay.publish(&wrap, &community.relays).await.unwrap();
        // Dated back to when the Channel was open, before the key it rides was given.
        let before = ch.writers.as_ref().unwrap().writer_start(live).unwrap() - 60_000;
        let backdated = chat::with_writer_cert(chat::build_message_rumor(member.keys.public_key(), &general, community.root_epoch, "backdated", None, &[], vec![], before), live, Some(chat::WriterCert::Scoped(cert, rights)));
        let (wrap, _) = chat::seal_chat_rumor(&backdated, &at_writer, &member.keys, Timestamp::from_secs(before / 1000), false).unwrap();
        bed.relay.publish(&wrap, &community.relays).await.unwrap();
        // A certificate for reactions doesn't put them in a call.
        let judge = writing::Judge::of(&held(&community), &ch).unwrap();
        let presence = chat::with_writer_cert(chat::build_voice_presence_rumor(member.keys.public_key(), &general, community.root_epoch, None, Default::default(), now_ms()), live, Some(chat::WriterCert::Scoped(cert, rights)));
        let (wrap, _) = chat::seal_chat_rumor(&presence, &at_writer, &member.keys, Timestamp::from_secs(now_ms() / 1000), true).unwrap();
        let heard = chat::open_writer_chat_event(&wrap, &wrap.pubkey, live, read.conv_key(), &general, community.root_epoch).unwrap();
        assert!(!judge.admits(&heard, Some(live)), "a reactor joins no call");
        let me = member.keys.public_key();
        assert!(matches!(crate::community::v2::inbound::dispatch_wrap(&wrap, &held(&community), &me, &crate::NoOpEventHandler), crate::community::v2::inbound::DispatchedV2::Ignored), "and is shown in none");
        let at_read = chat::seal_chat_rumor(&chat::build_voice_presence_rumor(member.keys.public_key(), &general, community.root_epoch, None, Default::default(), now_ms()), &read, &member.keys, Timestamp::from_secs(now_ms() / 1000), true).unwrap().0;
        assert!(!judge.admits(&chat::open_chat_event(&at_read, &read, &general, community.root_epoch).unwrap(), None), "nor through the read address");

        // A key alone with no rights: someone who can't react is refused before anything goes out.
        let stranger = Keys::generate();
        act_as(&stranger);
        assert!(send_reaction(&bed.relay, &held(&community), &general, &rules, &owner_hex, super::super::kind::MESSAGE, "💩", None).await.is_err());
        // And a reaction forged at the read address, or by a reactor posting there, stands nowhere.
        let forged = chat::build_reaction_rumor(stranger.public_key(), &general, community.root_epoch, &rules, &owner_hex, super::super::kind::MESSAGE, "💩", None, now_ms());
        let (wrap, _) = chat::seal_chat_rumor(&forged, &read, &stranger, Timestamp::from_secs(now_ms() / 1000), false).unwrap();
        bed.relay.publish(&wrap, &community.relays).await.unwrap();
        // A reactor's client gets the ten minutes past the lock any writer does to read the move.
        let past_grace = ch.writers.as_ref().unwrap().writer_start(live).unwrap() + crate::community::v2::writers::ENTRY_SKEW_MS + 1_000;
        let sneaky = chat::build_reaction_rumor(member.keys.public_key(), &general, community.root_epoch, &rules, &owner_hex, super::super::kind::MESSAGE, "🙃", None, past_grace);
        let (wrap, _) = chat::seal_chat_rumor(&sneaky, &read, &member.keys, Timestamp::from_secs(past_grace / 1000), false).unwrap();
        bed.relay.publish(&wrap, &community.relays).await.unwrap();

        // Junk posted at the read address after the lock reaches nobody, a manager included.
        let junk = chat::build_message_rumor(stranger.public_key(), &general, community.root_epoch, "junk", None, &[], vec![], past_grace);
        let (wrap, _) = chat::seal_chat_rumor(&junk, &read, &stranger, Timestamp::from_secs(past_grace / 1000), false).unwrap();
        bed.relay.publish(&wrap, &community.relays).await.unwrap();
        assert!(!crate::community::v2::realtime::plane_authors(&[held(&community)]).contains(&read.pk()), "nobody listens at a Locked read address");

        bed.swap_to(&owner);
        assert!(!channel_texts(&bed.relay, &held(&community), &general).await.contains(&"junk".to_string()), "not even marked for a manager");
        let seen = channel_reactions(&bed.relay, &held(&community), &general).await;
        assert_eq!(seen, vec![(member.keys.public_key(), "👍".to_string())], "only the reactor's, at the writer address: {seen:?}");
        let sent = fetch_channel(&bed.relay, &held(&community), &general, 50).await.unwrap();
        let carried = sent.iter().find_map(|f| match &f.event {
            ChatEvent::Reaction { opened, .. } => Some(opened.rumor.clone()),
            _ => None,
        });
        let carried = carried.unwrap();
        assert!(chat::writer_cert_of(&carried).is_none() && chat::scoped_cert_of(&carried).is_some(), "it carries its scoped certificate");
        let forced: Vec<bool> = sent.iter().filter(|f| matches!(&f.event, ChatEvent::Message { opened, .. } if opened.rumor.content == "forced")).map(|f| f.event.opened().held).collect();
        assert_eq!(forced, vec![true], "a scoped certificate never carries a post: a manager sees it only marked");
        let backdated: Vec<bool> = sent.iter().filter(|f| matches!(&f.event, ChatEvent::Message { opened, .. } if opened.rumor.content == "backdated")).map(|f| f.event.opened().held).collect();
        assert_eq!(backdated, vec![true], "nor one dated into the open past");

        // Letting @everyone react again leaves posting gated: a fresh epoch that isn't Locked.
        set_overwrite(&bed.relay, &held(&community), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
        let ch = held(&community).channel(&general).cloned().unwrap();
        assert!(ch.restricted() && !ch.locked());
        assert!(ch.writers.as_ref().unwrap().current_writer().unwrap().0 > live, "the flag is the window's: a new epoch");
    }

    /// Serves what `inner` does, noting every query it was asked.
    struct Watching<'a> {
        inner: &'a MemoryRelay,
        asked: std::sync::Mutex<Vec<Query>>,
    }
    #[async_trait::async_trait]
    impl Transport for Watching<'_> {
        async fn fetch_plane(&self, plane: &Keys, query: &Query, relays: &[String]) -> Result<crate::community::transport::PlaneFetch, String> {
            self.asked.lock().unwrap().push(query.clone());
            self.inner.fetch_plane(plane, query, relays).await
        }
        async fn publish(&self, e: &Event, r: &[String]) -> Result<(), String> {
            self.inner.publish(e, r).await
        }
        async fn publish_durable(&self, e: &Event, r: &[String]) -> Result<(), String> {
            self.inner.publish_durable(e, r).await
        }
        async fn fetch(&self, q: &Query, r: &[String]) -> Result<Vec<Event>, String> {
            self.asked.lock().unwrap().push(q.clone());
            self.inner.fetch(q, r).await
        }
    }

    #[tokio::test]
    async fn a_locked_read_address_is_read_only_up_to_the_lock() {
        use crate::community::roles::OverwriteTarget;
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Quiet", vec!["wss://r".into()], None).await.unwrap();
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        activate_roles_v2(&relay, &held(), crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
        let general = community.channels[0].id;
        send_chat_message(&relay, &held(), &general, "before", None, &[], vec![]).await.unwrap();
        let nothing = Permissions::SEND_MESSAGES | Permissions::ADD_REACTIONS | Permissions::CONNECT;
        set_overwrite(&relay, &held(), general.0, OverwriteTarget::Everyone, 0, nothing).await.unwrap();
        let ledger = held().channel(&general).unwrap().writers.clone().unwrap();
        assert!(ledger.locked());
        let lock = ledger.writer_start(ledger.current_writer().unwrap().0).unwrap();
        let read = channel_group_key(&community.community_root, &general, community.root_epoch).pk().to_hex();
        let watching = Watching { inner: &relay, asked: Default::default() };
        // Read as from an hour on, past the minutes a client that hadn't read the lock gets.
        let later = Some(now_ms() / 1000 + 3600);
        let got = fetch_channel_history(&watching, &held(), &general, 50, 4, None, later, crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await.unwrap();
        assert!(got.iter().any(|f| matches!(&f.event, ChatEvent::Message { opened, .. } if opened.rumor.content == "before")), "history before the lock still reads");
        let asked: Vec<Query> = watching.asked.lock().unwrap().iter().filter(|q| q.authors.contains(&read)).cloned().collect();
        assert!(!asked.is_empty());
        let bound = (lock + crate::community::v2::writers::ENTRY_SKEW_MS) / 1000 + 1;
        assert!(asked.iter().all(|q| q.until.is_some_and(|u| u <= bound)), "never past the lock's first minutes: {:?}", asked.iter().map(|q| q.until).collect::<Vec<_>>());
        // The minter seals up to the lock at once, and the lock's first minutes once they pass.
        let skew = crate::community::v2::writers::ENTRY_SKEW_MS;
        assert_eq!(held().channel(&general).unwrap().writers.as_ref().unwrap().seal_target(lock), Some(lock));
        access_duty(&relay, &held()).await.unwrap();
        let ledger = held().channel(&general).unwrap().writers.clone().unwrap();
        assert_eq!(ledger.seal.as_ref().map(|s| (s.until, s.run, s.count)), Some((lock, lock, 1)), "sealed to the lock");
        assert_eq!(ledger.seal_target(lock + skew - 1), None, "not before its time");
        assert_eq!(ledger.seal_target(lock + skew), Some(lock + skew));
        let _ = owner;
    }

    #[tokio::test]
    async fn a_sealed_lock_reads_its_history_by_id_so_nothing_backdated_gets_in() {
        use crate::community::roles::OverwriteTarget;
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Sealed", vec!["wss://r".into()], None).await.unwrap();
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        activate_roles_v2(&relay, &held(), crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
        let general = community.channels[0].id;
        let read = channel_group_key(&community.community_root, &general, community.root_epoch);
        // More than two pages of history, a second apart, before the lock.
        let total = crate::community::v2::seal::MAX_SEAL_IDS * 2 + 50;
        let start = now_ms() - (total as u64 + 100) * 1000;
        for i in 0..total {
            post_raw(&relay, &held(), &owner, &general, &read, community.root_epoch, None, &format!("m{i}"), start + i as u64 * 1000).await;
        }
        let nothing = Permissions::SEND_MESSAGES | Permissions::ADD_REACTIONS | Permissions::CONNECT;
        set_overwrite(&relay, &held(), general.0, OverwriteTarget::Everyone, 0, nothing).await.unwrap();
        let ch = held().channel(&general).cloned().unwrap();
        let lock = ch.writers.as_ref().unwrap().run_start().unwrap();
        let after_grace = lock + crate::community::v2::writers::ENTRY_SKEW_MS;
        assert_eq!(sealing::seal_history_at(&relay, &held(), &ch, lock).await.unwrap(), Some(total), "to the lock at once");
        assert_eq!(sealing::seal_history_at(&relay, &held(), held().channel(&general).unwrap(), after_grace - 1).await.unwrap(), None);
        assert_eq!(sealing::seal_history_at(&relay, &held(), held().channel(&general).unwrap(), after_grace).await.unwrap(), Some(0));
        let sealed = held().channel(&general).unwrap().writers.clone().unwrap().seal.expect("the ledger names the seal");
        assert_eq!((sealed.until, sealed.count), (after_grace, total as u64), "the seal covers the lock's first minutes");
        assert_eq!(sealing::seal_history_at(&relay, &held(), held().channel(&general).unwrap(), after_grace).await.unwrap(), None, "once per run");
        // A fresh epoch while still Locked keeps the run, and its seal.
        let roster = crate::db::community::get_community_roles(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap();
        writing::mint_for_test(&relay, &held(), &general, &roster).await.unwrap();
        let ledger = held().channel(&general).unwrap().writers.clone().unwrap();
        assert!(ledger.current_writer().unwrap().0 > ch.writers.as_ref().unwrap().current_writer().unwrap().0 && ledger.seal_target(after_grace).is_none() && ledger.locked());

        // Anyone with the read key dates junk into the sealed past, after the seal was made.
        let stranger = Keys::generate();
        for (i, at) in [start - 5_000, start + 1_500, start + (total as u64 / 2) * 1000 + 500].into_iter().enumerate() {
            post_raw(&relay, &held(), &stranger, &general, &read, community.root_epoch, None, &format!("junk{i}"), at).await;
        }
        let watching = Watching { inner: &relay, asked: Default::default() };
        let later = Some(now_ms() / 1000 + 3600);
        let got = fetch_channel_history(&watching, &held(), &general, 200, 40, None, later, crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await.unwrap();
        let texts: Vec<String> = got.iter().filter_map(|f| match &f.event { ChatEvent::Message { opened, .. } => Some(opened.rumor.content.clone()), _ => None }).collect();
        assert!(!texts.iter().any(|t| t.starts_with("junk")), "nothing dated into the seal is read");
        assert_eq!(texts.iter().filter(|t| t.starts_with('m')).count(), total, "and all of what it holds is");
        let read_hex = read.pk().to_hex();
        let floor = sealed.until / 1000;
        assert!(watching.asked.lock().unwrap().iter().filter(|q| q.authors.contains(&read_hex)).all(|q| q.since.is_some_and(|s| s >= floor)), "the read address is never asked for anything the seal covers");
    }

    #[tokio::test]
    async fn an_unlocked_channel_still_reads_back_into_the_seal() {
        use crate::community::roles::OverwriteTarget;
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Reopened", vec!["wss://r".into()], None).await.unwrap();
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        activate_roles_v2(&relay, &held(), crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
        let general = community.channels[0].id;
        let read = channel_group_key(&community.community_root, &general, community.root_epoch);
        let start = now_ms() - 600_000;
        for i in 0..20 {
            post_raw(&relay, &held(), &owner, &general, &read, community.root_epoch, None, &format!("old{i}"), start + i * 1000).await;
        }
        let nothing = Permissions::SEND_MESSAGES | Permissions::ADD_REACTIONS | Permissions::CONNECT;
        set_overwrite(&relay, &held(), general.0, OverwriteTarget::Everyone, 0, nothing).await.unwrap();
        sealing::seal_history(&relay, &held(), held().channel(&general).unwrap()).await.unwrap();
        set_overwrite(&relay, &held(), general.0, OverwriteTarget::Everyone, 0, 0).await.unwrap();
        let ch = held().channel(&general).cloned().unwrap();
        assert!(!ch.restricted() && ch.writers.as_ref().unwrap().seal.is_some(), "open again, the seal kept");
        let stranger = Keys::generate();
        post_raw(&relay, &held(), &stranger, &general, &read, community.root_epoch, None, "junk", start + 5_500).await;
        // The Channel is open again: nothing new until someone posts, and whatever comes back is above the seal.
        let texts = |got: Vec<FetchedEvent>| -> Vec<String> { got.into_iter().filter_map(|f| match f.event { ChatEvent::Message { opened, .. } => Some(opened.rumor.content), _ => None }).collect() };
        let got = texts(fetch_channel_history(&relay, &held(), &general, 50, 6, None, None, crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await.unwrap());
        assert_eq!(got.iter().filter(|t| t.starts_with("old")).count(), 20, "an empty read address hands on to the seal: {got:?}");
        assert!(!got.contains(&"junk".to_string()));
        send_chat_message(&relay, &held(), &general, "new", None, &[], vec![]).await.unwrap();
        let got = texts(fetch_channel_history(&relay, &held(), &general, 50, 6, None, None, crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await.unwrap());
        assert!(got.contains(&"new".to_string()) && got.iter().filter(|t| t.starts_with("old")).count() == 20 && !got.contains(&"junk".to_string()), "{got:?}");
    }

    #[tokio::test]
    async fn a_lock_seals_at_once_and_takes_in_its_first_minutes_after() {
        use crate::community::roles::OverwriteTarget;
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Two steps", vec!["wss://r".into()], None).await.unwrap();
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        activate_roles_v2(&relay, &held(), crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
        let general = community.channels[0].id;
        let read = channel_group_key(&community.community_root, &general, community.root_epoch);
        post_raw(&relay, &held(), &owner, &general, &read, community.root_epoch, None, "before", now_ms() - 60_000).await;
        let nothing = Permissions::SEND_MESSAGES | Permissions::ADD_REACTIONS | Permissions::CONNECT;
        set_overwrite(&relay, &held(), general.0, OverwriteTarget::Everyone, 0, nothing).await.unwrap();
        let lock = held().channel(&general).unwrap().writers.as_ref().unwrap().run_start().unwrap();
        // Only a device holding every plane's key seals: what it can't open would be left out for all.
        let ch = held().channel(&general).cloned().unwrap();
        assert!(sealing::reads_whole_history(&held(), &ch, &read_planes(&held(), &ch)));
        assert!(!sealing::reads_whole_history(&held(), &ch, &[]));
        let views: Vec<(ReadPlane, Epoch)> = read_planes(&held(), &ch).into_iter().map(|(p, e)| (ReadPlane::View(p.address(), *p.conv()), e)).collect();
        assert!(!sealing::reads_whole_history(&held(), &ch, &views), "a view holds no key a page could ride");
        assert_eq!(sealing::seal_history_at(&relay, &held(), held().channel(&general).unwrap(), lock).await.unwrap(), Some(1));
        assert!(sealing::seal_history_at(&relay, &held(), &ch, lock).await.is_err(), "a sealer that read the ledger before another's seal adds none");
        assert_eq!(held().channel(&general).unwrap().writers.as_ref().unwrap().seal.as_ref().unwrap().count, 1);
        // Dated into the open past after the seal, in the seal's own second, which is read by date.
        let edge = chat::build_message_rumor(owner.public_key(), &general, community.root_epoch, "edge", None, &[], vec![], lock - 1);
        let (edge, _) = chat::seal_chat_rumor(&edge, &read, &owner, Timestamp::from_secs((lock - 1) / 1000), false).unwrap();
        relay.publish(&edge, &community.relays).await.unwrap();
        assert!(matches!(crate::community::v2::inbound::dispatch_wrap(&edge, &held(), &owner.public_key(), &crate::NoOpEventHandler), crate::community::v2::inbound::DispatchedV2::Ignored), "nor live");
        let texts = || async { fetch_channel_history(&relay, &held(), &general, 50, 6, None, Some(now_ms() / 1000 + 3600), crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await.unwrap().into_iter().filter_map(|f| match f.event { ChatEvent::Message { opened, .. } => Some(opened.rumor.content), _ => None }).collect::<Vec<_>>() };
        assert_eq!(texts().await, vec!["before"], "below the seal only what it names stands");
        // In the lock's first minutes a manager's client that hadn't read it still posts at the read
        // address; a stranger's post there stands nowhere.
        post_raw(&relay, &held(), &owner, &general, &read, community.root_epoch, None, "late", lock + 1).await;
        post_raw(&relay, &held(), &Keys::generate(), &general, &read, community.root_epoch, None, "junk", lock + 2).await;
        let after_grace = lock + crate::community::v2::writers::ENTRY_SKEW_MS;
        assert_eq!(sealing::seal_history_at(&relay, &held(), held().channel(&general).unwrap(), after_grace).await.unwrap(), Some(1), "the late post, not the junk");
        let sealed = held().channel(&general).unwrap().writers.clone().unwrap().seal.unwrap();
        assert_eq!((sealed.until, sealed.run, sealed.count), (after_grace, lock, 2));
        let mut texts = texts().await;
        texts.sort();
        assert_eq!(texts, vec!["before", "late"]);
    }

    #[tokio::test]
    async fn a_seal_takes_in_a_second_holding_more_than_a_page() {
        use crate::community::roles::OverwriteTarget;
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Busy second", vec!["wss://r".into()], None).await.unwrap();
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        activate_roles_v2(&relay, &held(), crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
        let general = community.channels[0].id;
        let read = channel_group_key(&community.community_root, &general, community.root_epoch);
        let second = (now_ms() - 120_000) / 1000 * 1000;
        for i in 0..250 {
            post_raw(&relay, &held(), &owner, &general, &read, community.root_epoch, None, &format!("m{i}"), second + i).await;
        }
        let nothing = Permissions::SEND_MESSAGES | Permissions::ADD_REACTIONS | Permissions::CONNECT;
        set_overwrite(&relay, &held(), general.0, OverwriteTarget::Everyone, 0, nothing).await.unwrap();
        assert_eq!(sealing::seal_history(&relay, &held(), held().channel(&general).unwrap()).await.unwrap(), Some(250));
    }

    /// Serves what `inner` does, less the read-address wraps dated in `gone` (unix seconds).
    struct Forgetting<'a> {
        inner: &'a MemoryRelay,
        address: PublicKey,
        gone: std::ops::Range<u64>,
    }
    impl Forgetting<'_> {
        fn keep(&self, evs: Vec<Event>) -> Vec<Event> {
            evs.into_iter().filter(|e| e.pubkey != self.address || !self.gone.contains(&e.created_at.as_secs())).collect()
        }
    }
    #[async_trait::async_trait]
    impl Transport for Forgetting<'_> {
        async fn fetch_plane(&self, plane: &Keys, query: &Query, relays: &[String]) -> Result<crate::community::transport::PlaneFetch, String> {
            let mut f = self.inner.fetch_plane(plane, query, relays).await?;
            f.events = self.keep(f.events);
            Ok(f)
        }
        async fn publish(&self, e: &Event, r: &[String]) -> Result<(), String> {
            self.inner.publish(e, r).await
        }
        async fn publish_durable(&self, e: &Event, r: &[String]) -> Result<(), String> {
            self.inner.publish_durable(e, r).await
        }
        async fn fetch(&self, q: &Query, r: &[String]) -> Result<Vec<Event>, String> {
            Ok(self.keep(self.inner.fetch(q, r).await?))
        }
    }

    #[tokio::test]
    async fn sealed_ids_no_relay_serves_any_more_page_on_to_what_lies_past_them() {
        use crate::community::roles::OverwriteTarget;
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Forgotten", vec!["wss://r".into()], None).await.unwrap();
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        activate_roles_v2(&relay, &held(), crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
        let general = community.channels[0].id;
        let read = channel_group_key(&community.community_root, &general, community.root_epoch);
        let total = crate::community::v2::seal::MAX_SEAL_IDS + 20;
        let start = (now_ms() - (total as u64 + 100) * 1000) / 1000 * 1000;
        for i in 0..total {
            post_raw(&relay, &held(), &owner, &general, &read, community.root_epoch, None, &format!("m{i}"), start + i as u64 * 1000).await;
        }
        let nothing = Permissions::SEND_MESSAGES | Permissions::ADD_REACTIONS | Permissions::CONNECT;
        set_overwrite(&relay, &held(), general.0, OverwriteTarget::Everyone, 0, nothing).await.unwrap();
        assert_eq!(sealing::seal_history(&relay, &held(), held().channel(&general).unwrap()).await.unwrap(), Some(total));
        // A page no relay serves leaves what lies past it unread, not absent.
        let lock = held().channel(&general).unwrap().writers.as_ref().unwrap().seal.as_ref().unwrap().until;
        let pageless = Forgetting { inner: &relay, address: read.pk(), gone: (lock - 1) / 1000..(lock - 1) / 1000 + 1 };
        let (_, _, complete) = fetch_channel_history_paged(&pageless, &held(), &general, 50, 40, None, Some(now_ms() / 1000 + 3600), crate::community::transport::Evidence::Quorum, |_, _, _| true, |_| Default::default()).await.unwrap();
        assert!(!complete);
        // Every post the newest page names has expired from the relay.
        let first_gone = start / 1000 + 20;
        let forgetting = Forgetting { inner: &relay, address: read.pk(), gone: first_gone..first_gone + crate::community::v2::seal::MAX_SEAL_IDS as u64 };
        let got = fetch_channel_history(&forgetting, &held(), &general, 50, 40, None, Some(now_ms() / 1000 + 3600), crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await.unwrap();
        let texts: std::collections::BTreeSet<String> = got.into_iter().filter_map(|f| match f.event { ChatEvent::Message { opened, .. } => Some(opened.rumor.content), _ => None }).collect();
        assert_eq!(texts, (0..20).map(|i| format!("m{i}")).collect(), "the older page still reads");
    }

    #[tokio::test]
    async fn a_second_lock_chains_its_seal_onto_the_first() {
        use crate::community::roles::OverwriteTarget;
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Twice", vec!["wss://r".into()], None).await.unwrap();
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        activate_roles_v2(&relay, &held(), crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
        let general = community.channels[0].id;
        let read = channel_group_key(&community.community_root, &general, community.root_epoch);
        let nothing = Permissions::SEND_MESSAGES | Permissions::ADD_REACTIONS | Permissions::CONNECT;
        let start = now_ms() - 900_000;
        for i in 0..5 {
            post_raw(&relay, &held(), &owner, &general, &read, community.root_epoch, None, &format!("first{i}"), start + i * 1000).await;
        }
        set_overwrite(&relay, &held(), general.0, OverwriteTarget::Everyone, 0, nothing).await.unwrap();
        assert_eq!(sealing::seal_history(&relay, &held(), held().channel(&general).unwrap()).await.unwrap(), Some(5));
        let first = held().channel(&general).unwrap().writers.clone().unwrap().seal.unwrap();
        set_overwrite(&relay, &held(), general.0, OverwriteTarget::Everyone, 0, 0).await.unwrap();
        for i in 0..3 {
            send_chat_message(&relay, &held(), &general, &format!("second{i}"), None, &[], vec![]).await.unwrap();
        }
        set_overwrite(&relay, &held(), general.0, OverwriteTarget::Everyone, 0, nothing).await.unwrap();
        assert!(held().channel(&general).unwrap().writers.as_ref().unwrap().seal_target(now_ms()).is_some(), "a new run");
        assert_eq!(sealing::seal_history(&relay, &held(), held().channel(&general).unwrap()).await.unwrap(), Some(3), "only what came since the first");
        let second = held().channel(&general).unwrap().writers.clone().unwrap().seal.unwrap();
        assert_eq!(second.count, 8);
        assert!(second.until > first.until && second.page != first.page);
        // Junk dated anywhere before the second seal stays out of reach.
        let stranger = Keys::generate();
        for at in [start - 1_000, start + 2_500, first.until + 1] {
            post_raw(&relay, &held(), &stranger, &general, &read, community.root_epoch, None, "junk", at).await;
        }
        let got = fetch_channel_history(&relay, &held(), &general, 3, 20, None, Some(now_ms() / 1000 + 3600), crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await.unwrap();
        let mut texts: Vec<String> = got.into_iter().filter_map(|f| match f.event { ChatEvent::Message { opened, .. } => Some(opened.rumor.content), _ => None }).collect();
        texts.sort();
        assert_eq!(texts, vec!["first0", "first1", "first2", "first3", "first4", "second0", "second1", "second2"], "one chain, both seals, read in small pages");
    }

    #[tokio::test]
    async fn a_post_held_on_rules_this_device_hadnt_read_stands_once_it_reads_them() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, member, community, general) = restricted_bed(false).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let read = channel_group_key(&community.community_root, &general, community.root_epoch);
        bed.swap_to(&owner);
        let (live, secret, _) = writing::live_writer(&held(), held().channel(&general).unwrap()).unwrap();
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, 0).await.unwrap();
        assert!(!held().channel(&general).unwrap().restricted(), "the owner reopened it");
        let p = Keys::generate();
        post_raw(&bed.relay, &held(), &p, &general, &read, community.root_epoch, None, "after the reopen", now_ms()).await;
        // Once it is open anyone may post at the read address, so a post at a writer's takes nothing new.
        let writer = GroupKey::from_parts(crate::community::v2::derive::channel_writer_group_key(&secret, &general, live).keys().clone(), read.conv_key().clone());
        post_raw(&bed.relay, &held(), &p, &general, &writer, community.root_epoch, Some(live), "at the old writer address", now_ms() + 1).await;

        bed.swap_to(&member);
        let texts = channel_texts(&bed.relay, &held(), &general).await;
        assert!(!texts.iter().any(|t| t == "after the reopen" || t == "at the old writer address"), "judged on the ledger this device holds: {texts:?}");
        let waiting = crate::db::community::held_wraps(&cid_hex).unwrap();
        assert_eq!(waiting.len(), 2, "held, not dropped");
        let ids: Vec<String> = waiting.iter().map(|w| w.0.clone()).collect();
        assert_eq!(crate::db::events::community_wraps_settled(&ids).len(), 2, "a catch-up takes held wraps as settled");
        let shown = Shown::default();
        assert_eq!(writing::rejudge_held(&held(), &shown).await, 0, "nothing stands on the old rules");
        assert!(shown.take().is_empty());

        follow_control(&bed.relay, &held()).await.unwrap();
        assert_eq!(writing::rejudge_held(&held(), &shown).await, 2);
        assert_eq!(sorted(shown.take().into_iter().map(|(t, rang)| { assert!(!rang, "a late arrival never rings"); t }).collect()), vec!["after the reopen".to_string(), "at the old writer address".to_string()]);
        assert!(crate::db::community::held_wraps(&cid_hex).unwrap().is_empty(), "let go once they stand");
        assert_eq!(writing::rejudge_held(&held(), &shown).await, 0);
    }

    #[tokio::test]
    async fn a_post_at_a_writer_address_can_be_pinned() {
        let (bed, owner, _member, community, general) = restricted_bed(false).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        bed.swap_to(&owner);
        let rumor = send_chat_message(&bed.relay, &held(), &general, "pin me", None, &[], vec![]).await.unwrap();
        let far = now_ms() / 1000 + 100;
        let got = fetch_channel_history(&bed.relay, &held(), &general, 50, 4, None, Some(far), crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await.unwrap();
        let wrap = got.iter().find(|e| e.event.opened().rumor_id.to_hex() == rumor).and_then(|e| e.wrap.clone()).expect("the post reads back");
        let read = channel_group_key(&held().community_root, &general, held().root_epoch);
        assert_ne!(wrap.pubkey, read.pk(), "posted at its writer's address, not the read one");
        let chan = crate::simd::hex::bytes_to_hex_32(&general.0);
        let wrap_of = crate::db::events::get_event_wrap_context(&rumor).unwrap().and_then(|(w, _)| w);
        assert_eq!(wrap_of, Some(wrap.id.to_hex()), "the send recorded the wrap it went out in");
        pin_message(&bed.relay, &held(), &general, &rumor).await.unwrap();
        let pinned = writable_pin_entries(&held(), &general).unwrap();
        assert!(pinned.iter().filter_map(|e| super::super::pins::verify_pin_entry(e, &chan)).any(|v| v.rumor_id == rumor), "and its pin verifies");
    }

    #[tokio::test]
    async fn a_writer_in_flight_across_the_restrict_stands_only_while_a_member() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, member, community, general) = restricted_bed(false).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let read = channel_group_key(&community.community_root, &general, community.root_epoch);
        bed.swap_to(&owner);
        let (w, z) = (Keys::generate(), Keys::generate());
        let plain = create_role_v2(&bed.relay, &held(), "Plain", 0, 0).await.unwrap();
        for k in [&w, &z] {
            set_member_roles(&bed.relay, &held(), &k.public_key(), vec![plain.clone()]).await.unwrap();
            set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(k.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
        }
        let ledger = held().channel(&general).unwrap().writers.clone().unwrap();
        let start = ledger.writer_start(ledger.current_writer().unwrap().0).unwrap();
        // Sent before its client read the restrict, at the read address.
        post_raw(&bed.relay, &held(), &w, &general, &read, community.root_epoch, None, "in flight", start + 1_000).await;
        post_raw(&bed.relay, &held(), &w, &general, &read, community.root_epoch, None, "long after", start + crate::community::v2::writers::ENTRY_SKEW_MS + 1_000).await;
        post_raw(&bed.relay, &held(), &z, &general, &read, community.root_epoch, None, "banned in flight", start + 1_500).await;
        bed.swap_to(&member);
        follow_control(&bed.relay, &held()).await.unwrap();
        let texts = channel_texts(&bed.relay, &held(), &general).await;
        assert!(texts.contains(&"in flight".to_string()) && texts.contains(&"banned in flight".to_string()), "a writer whose client lagged the move keeps its post: {texts:?}");
        assert!(!texts.contains(&"long after".to_string()), "past the skew, a writer posts at its own address");

        bed.swap_to(&owner);
        kick_member(&bed.relay, &held(), &w.public_key()).await.unwrap();
        set_members_banned(&bed.relay, community.id(), &[z.public_key()], true).await.unwrap();
        post_raw(&bed.relay, &held(), &w, &general, &read, community.root_epoch, None, "kicked in flight", start + 2_000).await;
        bed.swap_to(&member);
        follow_control(&bed.relay, &held()).await.unwrap();
        sync_guestbook(&bed.relay, &held()).await.unwrap();
        let texts = channel_texts(&bed.relay, &held(), &general).await;
        assert!(!texts.contains(&"kicked in flight".to_string()), "a writer no longer a member vouches for nothing: {texts:?}");
        assert!(!texts.contains(&"banned in flight".to_string()), "nor one banned");
    }

    #[tokio::test]
    async fn a_member_let_into_a_private_channel_finds_its_key_on_its_own_next_sweep() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, member) = TestBed::new();
        let held = |c: &CommunityV2| crate::db::community::load_community_v2(c.id()).unwrap().unwrap();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Prompt", bed.relays.clone(), None).await.unwrap();
        activate_roles_v2(&bed.relay, &community, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
        follow_control(&bed.relay, &community).await.unwrap();
        let m = member.keys.public_key();
        let ch = create_private_channel(&bed.relay, &held(&community), "staff").await.unwrap();
        send_direct_invite(&bed.relay, &held(&community), &m, None, None).await.unwrap();
        bed.swap_to(&member);
        accept_direct_invite(&bed.relay, &fetch_direct_invite(&bed.relay, &bed.relays, &m).await).await.unwrap();
        follow_control(&bed.relay, &held(&community)).await.unwrap();
        bed.swap_to(&owner);
        set_overwrite(&bed.relay, &held(&community), ch.0, OverwriteTarget::Member(m.to_hex()), Permissions::VIEW_CHANNEL, 0).await.unwrap();
        // No holder's duty runs: the change itself put the key where the member's client looks.
        bed.swap_to(&member);
        follow_control(&bed.relay, &held(&community)).await.unwrap();
        assert_eq!(collect_access(&bed.relay, &held(&community)).await.unwrap(), 1);
    }

    #[tokio::test]
    async fn an_action_reads_an_access_plane_once_and_afresh_after_writing_to_it() {
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Once", bed.relays.clone(), None).await.unwrap();
        activate_roles_v2(&bed.relay, &community, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
        follow_control(&bed.relay, &community).await.unwrap();
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let ch = create_private_channel(&bed.relay, &held, "staff").await.unwrap();
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let (m, other) = (member.keys.public_key(), Keys::generate().public_key());
        let room = held.channel(&ch).unwrap();
        let (key, epoch) = (room.key.unwrap(), room.epoch);
        // Someone else's delivery, sealed ahead of the action and published while it runs.
        let theirs = build_deliveries(&held, &ch, rekey::RekeyScope::Channel(ch), epoch, None, &key, &[other], &Default::default(), false).await.unwrap();
        let count = || async { fetch_access_deliveries(&bed.relay, &held, &ch).await.unwrap().len() };
        let before = count().await;
        reading_planes_once(async {
            assert_eq!(count().await, before);
            for wrap in &theirs {
                bed.relay.publish(wrap, &held.relays).await.unwrap();
            }
            assert_eq!(count().await, before, "the plane was read once: a second look asks no relay");
            deliver_access(&bed.relay, &held, &ch, &[m]).await.unwrap();
            assert_eq!(count().await, before + 2, "after its own delivery the action reads the plane afresh");
        })
        .await;
        assert_eq!(count().await, before + 2);
        // Outside an action every read is the relays' own.
        deliver_access(&bed.relay, &held, &ch, &[other]).await.unwrap();
        assert_eq!(count().await, before + 3);
    }

    #[tokio::test]
    async fn a_holder_never_cuts_someone_a_fresh_read_lets_in() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, member) = TestBed::new();
        let held = |c: &CommunityV2| crate::db::community::load_community_v2(c.id()).unwrap().unwrap();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Race", bed.relays.clone(), None).await.unwrap();
        activate_roles_v2(&bed.relay, &community, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
        follow_control(&bed.relay, &community).await.unwrap();
        let ch = create_private_channel(&bed.relay, &held(&community), "staff").await.unwrap();
        let (m, chan) = (member.keys.public_key(), crate::simd::hex::bytes_to_hex_32(&ch.0));
        let owner_hex = owner.keys.public_key().to_hex();
        assert_eq!(still_left_out(&bed.relay, &held(&community), &chan, &owner_hex, vec![m]).await, vec![m], "not let in: cut");
        set_overwrite(&bed.relay, &held(&community), ch.0, OverwriteTarget::Member(m.to_hex()), Permissions::VIEW_CHANNEL, 0).await.unwrap();
        assert!(still_left_out(&bed.relay, &held(&community), &chan, &owner_hex, vec![m]).await.is_empty(), "let in since the duty's read: kept");
    }

    #[tokio::test]
    async fn a_member_back_after_leaving_opens_its_key_delivery_again() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, member) = TestBed::new();
        let held = |c: &CommunityV2| crate::db::community::load_community_v2(c.id()).unwrap().unwrap();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Return", bed.relays.clone(), None).await.unwrap();
        activate_roles_v2(&bed.relay, &community, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
        follow_control(&bed.relay, &community).await.unwrap();
        let m = member.keys.public_key();
        let ch = create_private_channel(&bed.relay, &held(&community), "staff").await.unwrap();
        send_direct_invite(&bed.relay, &held(&community), &m, None, None).await.unwrap();
        bed.swap_to(&member);
        let invite = fetch_direct_invite(&bed.relay, &bed.relays, &m).await;
        accept_direct_invite(&bed.relay, &invite).await.unwrap();
        follow_control(&bed.relay, &held(&community)).await.unwrap();
        bed.swap_to(&owner);
        set_overwrite(&bed.relay, &held(&community), ch.0, OverwriteTarget::Member(m.to_hex()), Permissions::VIEW_CHANNEL, 0).await.unwrap();
        bed.swap_to(&member);
        follow_control(&bed.relay, &held(&community)).await.unwrap();
        assert_eq!(collect_access(&bed.relay, &held(&community)).await.unwrap(), 1);
        assert_eq!(absorb_parked_channel_keys(&held(&community), &crate::db::current_session()), vec![ch]);

        // Gone and back without the session ending: the seat is new, the delivery is the same one.
        leave_community(&bed.relay, &held(&community)).await.unwrap();
        accept_direct_invite(&bed.relay, &invite).await.unwrap();
        follow_control(&bed.relay, &held(&community)).await.unwrap();
        assert!(held(&community).channel(&ch).is_some_and(|c| c.key.is_none()), "back without the key");
        assert_eq!(collect_access(&bed.relay, &held(&community)).await.unwrap(), 1, "the delivery it opened before is opened again");
        assert_eq!(absorb_parked_channel_keys(&held(&community), &crate::db::current_session()), vec![ch]);
    }

    #[tokio::test]
    async fn a_member_given_the_right_to_post_moments_after_joining_gets_the_key() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, member) = TestBed::new();
        let held = |c: &CommunityV2| crate::db::community::load_community_v2(c.id()).unwrap().unwrap();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Gate", bed.relays.clone(), None).await.unwrap();
        activate_roles_v2(&bed.relay, &community, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
        follow_control(&bed.relay, &community).await.unwrap();
        let general = community.channels[0].id;
        set_overwrite(&bed.relay, &held(&community), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
        let m = member.keys.public_key();
        send_direct_invite(&bed.relay, &held(&community), &m, None, None).await.unwrap();
        bed.swap_to(&member);
        accept_direct_invite(&bed.relay, &fetch_direct_invite(&bed.relay, &bed.relays, &m).await).await.unwrap();
        follow_control(&bed.relay, &held(&community)).await.unwrap();
        // The owner lets them post before its Guestbook has read their Join.
        bed.swap_to(&owner);
        set_overwrite(&bed.relay, &held(&community), general.0, OverwriteTarget::Member(m.to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
        bed.swap_to(&member);
        follow_control(&bed.relay, &held(&community)).await.unwrap();
        assert_eq!(collect_writers(&bed.relay, &held(&community)).await.unwrap(), 1);
        assert!(can_post(&held(&community), &general));
    }

    #[tokio::test]
    async fn a_writers_certificate_the_ledger_disowns_is_collected_again() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, member, community, general) = restricted_bed(false).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        bed.swap_to(&owner);
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(member.keys.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
        bed.swap_to(&member);
        follow_control(&bed.relay, &held()).await.unwrap();
        assert_eq!(collect_writers(&bed.relay, &held()).await.unwrap(), 1);
        assert!(can_post(&held(), &general));
        let ch = held().channel(&general).unwrap().clone();
        let live = ch.writers.as_ref().unwrap().current_writer().unwrap().0;
        let real = writing::my_cert(&held(), &ch, live).unwrap();
        // A mint that lost its race left a certificate its certifier never stood behind.
        let key = format!("writer_cert:{}:{}:{}", crate::simd::hex::bytes_to_hex_32(&community.id().0), crate::simd::hex::bytes_to_hex_32(&general.0), live.0);
        crate::db::settings::set_sql_setting(key.clone(), "77".repeat(64)).unwrap();
        assert!(!can_post(&held(), &general), "a post it would carry could never stand");
        assert!(crate::db::settings::get_sql_setting(key).unwrap().is_none(), "dropped for a fresh one");
        collect_writers(&bed.relay, &held()).await.unwrap();
        assert_eq!(writing::my_cert(&held(), &ch, live), Some(real), "the real one, collected again");
        assert!(can_post(&held(), &general));
    }

    #[tokio::test]
    async fn a_certified_delivery_past_one_event_keeps_each_writers_key_beside_their_certificate() {
        let (bed, owner, _member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Many", bed.relays.clone(), None).await.unwrap();
        let general = community.channels[0].id;
        let scope = crate::community::v2::writers::writer_rekey_scope(&general);
        let writers: Vec<PublicKey> = (0..rekey::MAX_CERTIFIED_BLOBS_PER_EVENT + 2).map(|_| Keys::generate().public_key()).collect();
        let certs: std::collections::HashMap<PublicKey, chat::WriterCert> = writers.iter().enumerate().map(|(i, w)| (*w, chat::WriterCert::Full([i as u8; 64]))).collect();
        deliver_certified(&bed.relay, &community, &general, scope, Epoch(1), Some([0x42; 32]), &[0x5e; 32], &writers, &certs).await.unwrap();
        let deliveries = fetch_plane_deliveries(&bed.relay, &community, &general, scope).await.unwrap();
        assert_eq!(deliveries.len(), 2, "split at the certified cap");
        assert!(deliveries.iter().all(|d| d.blobs.len() <= rekey::MAX_CERTIFIED_BLOBS_PER_EVENT));
        for w in &writers {
            let with_blob: Vec<&rekey::AccessDelivery> = deliveries.iter().filter(|d| rekey::find_my_blob(&d.blobs, &d.deliverer.to_bytes(), &w.to_bytes(), scope, Epoch(1)).is_some()).collect();
            assert_eq!(with_blob.len(), 1);
            assert!(matches!(certs[w], chat::WriterCert::Full(c) if with_blob[0].certs.contains(&(w.to_bytes(), c))), "a writer's certificate rides with its key");
        }
    }

    #[tokio::test]
    async fn leaving_keeps_the_keys_a_self_scrub_needs_and_drops_the_writers() {
        let (bed, owner, _member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Leave", bed.relays.clone(), None).await.unwrap();
        let general = community.channels[0].id;
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let chan_hex = crate::simd::hex::bytes_to_hex_32(&general.0);
        for scope in [crate::community::v2::writers::secret_scope(&general), crate::community::v2::writers::minted_scope(&general), crate::community::v2::writers::certifier_scope(&general), chan_hex.clone()] {
            crate::db::community::store_epoch_key(&cid_hex, &scope, 1, &[0x5e; 32]).unwrap();
        }
        crate::db::community::hold_wrap(&cid_hex, &chan_hex, &"ab".repeat(32), "{}", "", 1).unwrap();
        crate::db::community::delete_community_retain_keys(&cid_hex).unwrap();
        assert!(crate::db::community::held_epoch_key(&cid_hex, &chan_hex, 1).unwrap().is_some(), "a self-scrub signs with the read keys");
        for scope in [crate::community::v2::writers::secret_scope(&general), crate::community::v2::writers::minted_scope(&general), crate::community::v2::writers::certifier_scope(&general)] {
            assert!(crate::db::community::held_epoch_key(&cid_hex, &scope, 1).unwrap().is_none(), "nothing that posts or vouches outlives membership: {scope}");
        }
        assert!(crate::db::community::held_wraps(&cid_hex).unwrap().is_empty());
    }

    #[tokio::test]
    async fn a_writer_who_left_vouches_for_nothing_whatever_role_lingers() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, member, community, general) = restricted_bed(false).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let read = channel_group_key(&community.community_root, &general, community.root_epoch);
        bed.swap_to(&owner);
        let w = Keys::generate();
        set_member_roles(&bed.relay, &held(), &w.public_key(), vec![create_role_v2(&bed.relay, &held(), "Plain", 0, 0).await.unwrap()]).await.unwrap();
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
        let ledger = held().channel(&general).unwrap().writers.clone().unwrap();
        let start = ledger.writer_start(ledger.current_writer().unwrap().0).unwrap();
        let gb = crate::community::v2::derive::guestbook_group_key(&held().community_root, community.id(), held().root_epoch);
        let leave = guestbook::build_leave_rumor(w.public_key(), now_ms());
        let (wrap, _) = guestbook::seal_guestbook_rumor(&leave, &gb, &w, Timestamp::from_secs(now_ms() / 1000)).unwrap();
        bed.relay.publish(&wrap, &held().relays).await.unwrap();
        post_raw(&bed.relay, &held(), &w, &general, &read, community.root_epoch, None, "after leaving", start + 1_000).await;
        bed.swap_to(&member);
        follow_control(&bed.relay, &held()).await.unwrap();
        sync_guestbook(&bed.relay, &held()).await.unwrap();
        crate::rt::time::sleep(std::time::Duration::from_millis(1_100)).await;
        assert!(!channel_texts(&bed.relay, &held(), &general).await.contains(&"after leaving".to_string()), "a Role they still hold is no membership once they left");
    }

    #[tokio::test]
    async fn a_writer_who_leaves_posts_nothing_that_stands_and_costs_no_ledger_line() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, member, community, general) = restricted_bed(false).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let read = channel_group_key(&community.community_root, &general, community.root_epoch);
        bed.swap_to(&owner);
        let w = Keys::generate();
        set_member_roles(&bed.relay, &held(), &w.public_key(), vec![create_role_v2(&bed.relay, &held(), "Plain", 0, 0).await.unwrap()]).await.unwrap();
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
        let (live, _, writer) = writing::live_writer(&held(), held().channel(&general).unwrap()).unwrap();
        let cert = cert_for(&held(), &general, live, &w.public_key());
        let signed = GroupKey::from_parts(writer.keys().clone(), read.conv_key().clone());
        post_certified(&bed.relay, &held(), &w, &general, &signed, community.root_epoch, Some((live, Some(cert))), "before leaving", now_ms()).await;
        crate::rt::time::sleep(std::time::Duration::from_millis(1_100)).await;
        let gb = crate::community::v2::derive::guestbook_group_key(&held().community_root, community.id(), held().root_epoch);
        let leave = guestbook::build_leave_rumor(w.public_key(), now_ms());
        let (wrap, _) = guestbook::seal_guestbook_rumor(&leave, &gb, &w, Timestamp::from_secs(now_ms() / 1000)).unwrap();
        bed.relay.publish(&wrap, &held().relays).await.unwrap();
        crate::rt::time::sleep(std::time::Duration::from_millis(1_100)).await;
        // Their key and certificate still sign, and a Role still says they may post.
        post_certified(&bed.relay, &held(), &w, &general, &signed, community.root_epoch, Some((live, Some(cert))), "after leaving", now_ms()).await;
        let ledger = held().channel(&general).unwrap().writers.clone().unwrap();
        sync_guestbook(&bed.relay, &held()).await.unwrap();
        assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().writers.cut, 0, "the Guestbook is the stop: no ledger line");
        assert_eq!(held().channel(&general).unwrap().writers, Some(ledger));
        bed.swap_to(&member);
        follow_control(&bed.relay, &held()).await.unwrap();
        sync_guestbook(&bed.relay, &held()).await.unwrap();
        let texts = channel_texts(&bed.relay, &held(), &general).await;
        assert!(texts.contains(&"before leaving".to_string()), "what they posted while here stays theirs");
        assert!(!texts.contains(&"after leaving".to_string()), "a member who left posts nothing that stands");
        // Nor does a fresh epoch for others reach them.
        bed.swap_to(&owner);
        let wr = create_role_v2(&bed.relay, &held(), "W", 0, 0).await.unwrap();
        let (y1, y2) = (Keys::generate(), Keys::generate());
        for y in [&y1, &y2] {
            set_member_roles(&bed.relay, &held(), &y.public_key(), vec![wr.clone()]).await.unwrap();
        }
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Role(wr.clone()), Permissions::SEND_MESSAGES, 0).await.unwrap();
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Role(wr), 0, 0).await.unwrap();
        let fresh = held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0;
        assert!(fresh > live, "two lost Send at once");
        let scope = crate::community::v2::writers::writer_rekey_scope(&general);
        let plane = fetch_plane_deliveries(&bed.relay, &held(), &general, scope).await.unwrap();
        assert!(!served_at(&plane, &w.public_key(), scope, fresh, &|_| true), "one who left is no writer");
    }

    #[tokio::test]
    async fn a_leave_read_later_takes_back_what_was_shown_since() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, member, community, general) = restricted_bed(false).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let read = channel_group_key(&community.community_root, &general, community.root_epoch);
        let (cid_hex, chan_hex) = (crate::simd::hex::bytes_to_hex_32(&community.id().0), crate::simd::hex::bytes_to_hex_32(&general.0));
        bed.swap_to(&owner);
        let w = Keys::generate();
        set_member_roles(&bed.relay, &held(), &w.public_key(), vec![create_role_v2(&bed.relay, &held(), "Plain", 0, 0).await.unwrap()]).await.unwrap();
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
        let (live, _, writer) = writing::live_writer(&held(), held().channel(&general).unwrap()).unwrap();
        let cert = cert_for(&held(), &general, live, &w.public_key());
        let signed = GroupKey::from_parts(writer.keys().clone(), read.conv_key().clone());
        let gb = crate::community::v2::derive::guestbook_group_key(&held().community_root, community.id(), held().root_epoch);
        let leave = guestbook::build_leave_rumor(w.public_key(), now_ms());
        let (wrap, _) = guestbook::seal_guestbook_rumor(&leave, &gb, &w, Timestamp::from_secs(now_ms() / 1000)).unwrap();
        bed.relay.publish(&wrap, &held().relays).await.unwrap();
        post_certified(&bed.relay, &held(), &w, &general, &signed, community.root_epoch, Some((live, Some(cert))), "after leaving", now_ms() + 2_000).await;
        // The member shows it before its Guestbook holds the Leave.
        bed.swap_to(&member);
        follow_control(&bed.relay, &held()).await.unwrap();
        let page = fetch_channel_history(&bed.relay, &held(), &general, 50, 2, None, None, crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await.unwrap();
        let shown = page.iter().find(|f| f.event.opened().rumor.content == "after leaving").expect("stood before the Leave was read");
        crate::community::v2::inbound::persist_routed_chat_event(&shown.event, &chan_hex, &community.id().0, &member.keys.public_key()).await.expect("stored");
        let id = shown.event.opened().rumor_id.to_hex();
        clear_owed(&cid_hex);
        sync_guestbook(&bed.relay, &held()).await.unwrap();
        let owed = crate::db::community::owed_author_retractions(&cid_hex).unwrap();
        assert_eq!(owed.iter().map(|(c, a, ..)| (c.clone(), a.clone())).collect::<Vec<_>>(), vec![(chan_hex.clone(), w.public_key().to_hex())], "the Leave owes their posts a take-back, nobody else's");
        writing::retract_by(&bed.relay, &held(), held().channel(&general).unwrap(), &w.public_key(), owed[0].2, owed[0].3, &Shown::default()).await.unwrap();
        assert!(crate::db::events::get_message_by_id(&id).await.unwrap().is_none());
    }

    #[tokio::test]
    async fn a_guestbook_longer_than_one_pass_is_still_read_whole() {
        let (bed, owner, _member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Big", bed.relays.clone(), None).await.unwrap();
        let gb = crate::community::v2::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
        let base = now_ms() / 1000 - 100_000;
        let joiners: Vec<Keys> = (0..6_100).map(|_| Keys::generate()).collect();
        for (i, k) in joiners.iter().enumerate() {
            let at = base + i as u64;
            let join = guestbook::build_join_rumor(k.public_key(), None, at * 1000);
            let (wrap, _) = guestbook::seal_guestbook_rumor(&join, &gb, k, Timestamp::from_secs(at)).unwrap();
            bed.relay.publish(&wrap, &community.relays).await.unwrap();
        }
        super::control_sync::set_budget_for_test(Some(6_000));
        sync_guestbook(&bed.relay, &community).await.unwrap();
        assert!(!guestbook_walked_this_session(&community), "one pass's worth falls short");
        sync_guestbook(&bed.relay, &community).await.unwrap();
        super::control_sync::set_budget_for_test(None);
        assert!(guestbook_walked_this_session(&community), "the next goes on from where it stopped");
        let (_, cursor) = crate::db::community::get_guestbook(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap();
        assert!(cursor + 600 >= now_ms() / 1000, "the cursor reaches the newest the whole walk saw, not only its last pass");
        let members = stored_memberlist_strict(&crate::db::community::load_community_v2(community.id()).unwrap().unwrap()).unwrap();
        assert!(members.contains(&joiners[0].public_key()) && members.contains(&joiners[6_099].public_key()), "oldest and newest both");
    }

    #[tokio::test]
    async fn a_writer_nobody_saw_leave_is_never_stopped_for_an_absence() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, _member, community, general) = restricted_bed(false).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        bed.swap_to(&owner);
        let w = Keys::generate();
        set_member_roles(&bed.relay, &held(), &w.public_key(), vec![create_role_v2(&bed.relay, &held(), "Plain", 0, 0).await.unwrap()]).await.unwrap();
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
        // The role that made them a member goes; no Leave, no Kick, no ban says they left.
        set_member_roles(&bed.relay, &held(), &w.public_key(), vec![]).await.unwrap();
        sync_guestbook(&bed.relay, &held()).await.unwrap();
        assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().writers.cut, 0, "an absence is no departure");
    }

    #[tokio::test]
    async fn a_stopped_writer_who_now_manages_costs_no_fresh_epoch() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, _member, community, general) = restricted_bed(false).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        bed.swap_to(&owner);
        let w = Keys::generate();
        let plain = create_role_v2(&bed.relay, &held(), "Plain", 0, 0).await.unwrap();
        set_member_roles(&bed.relay, &held(), &w.public_key(), vec![plain.clone()]).await.unwrap();
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), 0, 0).await.unwrap();
        assert!(held().channel(&general).unwrap().writers.as_ref().unwrap().stopped(Epoch(1), &w.public_key().to_bytes(), u64::MAX));
        // Let back as a manager without a settle: their posts stand by the Roster whatever the key.
        let mods = create_role_v2(&bed.relay, &held(), "Mods", 0, Permissions::MANAGE_CHANNELS).await.unwrap();
        set_member_roles(&bed.relay, &held(), &w.public_key(), vec![plain, mods]).await.unwrap();
        publish_overwrite_raw(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await;
        follow_control(&bed.relay, &held()).await.unwrap();
        sync_guestbook(&bed.relay, &held()).await.unwrap();
        assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().writers.moved, 0);
        assert_eq!(held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0, Epoch(1));
    }

    #[tokio::test]
    async fn a_manager_without_the_certifier_lets_a_fresh_epoch_land_before_minting_over_it() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, member, community, general) = restricted_bed(false).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        bed.swap_to(&owner);
        let mods = create_role_v2(&bed.relay, &held(), "Mods", 0, Permissions::MANAGE_CHANNELS).await.unwrap();
        let plain = create_role_v2(&bed.relay, &held(), "Plain", 0, 0).await.unwrap();
        set_member_roles(&bed.relay, &held(), &member.keys.public_key(), vec![plain.clone(), mods]).await.unwrap();
        let w = Keys::generate();
        set_member_roles(&bed.relay, &held(), &w.public_key(), vec![plain]).await.unwrap();
        publish_overwrite_raw(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await;
        bed.swap_to(&member);
        follow_control(&bed.relay, &held()).await.unwrap();
        assert!(writing::certifier_held(&held(), held().channel(&general).unwrap(), Epoch(1)).is_none());
        assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().writers.moved, 0, "a fresh epoch's own deliveries get their while");
    }

    #[tokio::test]
    async fn taking_back_never_reads_a_reopened_channel_stricter_than_judging() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, member, community, general) = restricted_bed(false).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let read = channel_group_key(&community.community_root, &general, community.root_epoch);
        let chan_hex = crate::simd::hex::bytes_to_hex_32(&general.0);
        bed.swap_to(&owner);
        let z = Keys::generate();
        set_member_roles(&bed.relay, &held(), &z.public_key(), vec![create_role_v2(&bed.relay, &held(), "Plain", 0, 0).await.unwrap()]).await.unwrap();
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(z.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, 0).await.unwrap();
        bed.swap_to(&member);
        follow_control(&bed.relay, &held()).await.unwrap();
        // Restricted again and reopened while this member wasn't looking; z posted at the read
        // address in between, in flight across the restrict.
        bed.swap_to(&owner);
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
        let start = held().channel(&general).unwrap().writers.as_ref().unwrap().entries.last().unwrap().at;
        post_raw(&bed.relay, &held(), &z, &general, &read, community.root_epoch, None, "in flight", start + 300).await;
        crate::rt::time::sleep(std::time::Duration::from_millis(1_200)).await;
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, 0).await.unwrap();
        bed.swap_to(&member);
        let page = fetch_channel_history(&bed.relay, &held(), &general, 50, 2, None, None, crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await.unwrap();
        for f in page.iter().filter(|f| f.event.opened().rumor.content == "in flight") {
            crate::community::v2::inbound::persist_routed_chat_event(&f.event, &chan_hex, &community.id().0, &member.keys.public_key()).await.expect("it stood on the open ledger");
        }
        follow_control(&bed.relay, &held()).await.unwrap();
        let ledger = held().channel(&general).unwrap().writers.clone().unwrap();
        let added: Vec<_> = ledger.entries[ledger.entries.len() - 2..].to_vec();
        let shown = Shown::default();
        assert_eq!(writing::retract_after(&bed.relay, &held(), held().channel(&general).unwrap(), &added, &shown).await, 0, "a writer in flight keeps the post");
    }

    #[tokio::test]
    async fn a_held_post_whose_author_is_banned_since_is_let_go() {
        let (bed, owner, _member, community, general) = restricted_bed(false).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let read = channel_group_key(&community.community_root, &general, community.root_epoch);
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        bed.swap_to(&owner);
        let p = Keys::generate();
        post_raw(&bed.relay, &held(), &p, &general, &read, community.root_epoch, None, "spam", now_ms()).await;
        assert!(marked_texts(&bed.relay, &held(), &general).await.contains(&"spam".to_string()));
        assert_eq!(crate::db::community::held_wraps(&cid_hex).unwrap().len(), 1);
        crate::db::community::set_community_banlist(&cid_hex, &[p.public_key().to_hex()], 1).unwrap();
        let shown = Shown::default();
        writing::rejudge_held(&held(), &shown).await;
        assert!(crate::db::community::held_wraps(&cid_hex).unwrap().is_empty(), "nothing to wait for");
    }

    #[tokio::test]
    async fn a_writer_served_without_a_certificate_is_served_again_with_one() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, member, community, general) = restricted_bed(false).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let m = member.keys.public_key();
        bed.swap_to(&owner);
        publish_overwrite_raw(&bed.relay, &held(), general.0, OverwriteTarget::Member(m.to_hex()), Permissions::SEND_MESSAGES, 0).await;
        follow_control(&bed.relay, &held()).await.unwrap();
        // An older client hands over the key alone.
        let (live, secret, writer) = writing::live_writer(&held(), held().channel(&general).unwrap()).unwrap();
        deliver_on_plane(&bed.relay, &held(), &general, crate::community::v2::writers::writer_rekey_scope(&general), live, Some(writer.pk().to_bytes()), &secret, &[m]).await.unwrap();
        bed.swap_to(&member);
        follow_control(&bed.relay, &held()).await.unwrap();
        assert_eq!(collect_writers(&bed.relay, &held()).await.unwrap(), 1, "the key");
        assert!(!can_post(&held(), &general), "but no proof to post with");
        bed.swap_to(&owner);
        assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().writers.delivered, 1, "a key without its certificate serves nobody");
        assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().writers.delivered, 0, "once");
        bed.swap_to(&member);
        collect_writers(&bed.relay, &held()).await.unwrap();
        assert!(can_post(&held(), &general));
    }

    #[tokio::test]
    async fn what_waits_shows_marked_to_a_new_manager_and_leaves_a_former_one() {
        let (bed, owner, member, community, general) = restricted_bed(false).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let read = channel_group_key(&community.community_root, &general, community.root_epoch);
        bed.swap_to(&owner);
        let p = Keys::generate();
        post_raw(&bed.relay, &held(), &p, &general, &read, community.root_epoch, None, "spam", now_ms()).await;
        bed.swap_to(&member);
        assert!(!channel_texts(&bed.relay, &held(), &general).await.contains(&"spam".to_string()));
        let shown = Shown::default();
        assert_eq!(writing::rejudge_held(&held(), &shown).await, 0);
        assert!(shown.take().is_empty(), "a member is shown nothing");

        bed.swap_to(&owner);
        let mods = create_role_v2(&bed.relay, &held(), "Mods", 0, Permissions::MANAGE_CHANNELS).await.unwrap();
        set_member_roles(&bed.relay, &held(), &member.keys.public_key(), vec![mods]).await.unwrap();
        bed.swap_to(&member);
        follow_control(&bed.relay, &held()).await.unwrap();
        assert_eq!(writing::rejudge_held(&held(), &shown).await, 0, "still held");
        assert_eq!(shown.take(), vec![("spam".to_string(), false)], "a new manager sees it, unrung");
        let id = crate::db::community::held_wraps(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap();
        assert_eq!(id.len(), 1, "it still waits");

        bed.swap_to(&owner);
        set_member_roles(&bed.relay, &held(), &member.keys.public_key(), vec![]).await.unwrap();
        bed.swap_to(&member);
        follow_control(&bed.relay, &held()).await.unwrap();
        writing::rejudge_held(&held(), &shown).await;
        let gone = shown.take();
        assert_eq!(gone.len(), 1);
        assert!(gone[0].0.starts_with('-'), "a former manager stops seeing it: {gone:?}");
        assert!(channel_texts(&bed.relay, &held(), &general).await.iter().all(|t| t != "spam"));
    }

    #[tokio::test]
    async fn a_held_post_dated_ahead_never_dates_a_managers_entry() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, _member, community, general) = restricted_bed(false).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let read = channel_group_key(&community.community_root, &general, community.root_epoch);
        bed.swap_to(&owner);
        let p = Keys::generate();
        post_raw(&bed.relay, &held(), &p, &general, &read, community.root_epoch, None, "from the future", now_ms() + 5 * 60_000).await;
        let page = fetch_channel_history(&bed.relay, &held(), &general, 50, 2, None, None, crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await.unwrap();
        assert!(!page.iter().any(|f| f.event.opened().rumor.content == "from the future"), "it waits for its time, before the writers' rules judge it");
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, 0).await.unwrap();
        let at = held().channel(&general).unwrap().writers.as_ref().unwrap().entries.last().unwrap().at;
        assert!(at < now_ms() + 60_000, "the reopen is dated now, not by a post the rules held");
    }

    #[tokio::test]
    async fn writers_lost_together_take_one_fresh_epoch_and_one_alone_a_stop() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, _member, community, general) = restricted_bed(false).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        bed.swap_to(&owner);
        let (a, b, c) = (Keys::generate(), Keys::generate(), Keys::generate());
        let writers = create_role_v2(&bed.relay, &held(), "Writers", 0, 0).await.unwrap();
        let plain = create_role_v2(&bed.relay, &held(), "Plain", 0, 0).await.unwrap();
        for k in [&a, &b, &c] {
            set_member_roles(&bed.relay, &held(), &k.public_key(), vec![plain.clone(), writers.clone()]).await.unwrap();
        }
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Role(writers.clone()), Permissions::SEND_MESSAGES, 0).await.unwrap();
        assert_eq!(held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0, Epoch(1), "gained, not minted");
        set_member_roles(&bed.relay, &held(), &a.public_key(), vec![plain.clone()]).await.unwrap();
        let l = held().channel(&general).unwrap().writers.clone().unwrap();
        assert_eq!(l.current_writer().unwrap().0, Epoch(1));
        assert!(l.stopped(Epoch(1), &a.public_key().to_bytes(), u64::MAX), "one writer lost is a stop");
        set_member_roles(&bed.relay, &held(), &a.public_key(), vec![plain.clone(), writers.clone()]).await.unwrap();
        assert_eq!(held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0, Epoch(2), "let back in after a stop, a writer takes a fresh epoch");
        // Everyone the role let post loses it in one change.
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Role(writers), 0, 0).await.unwrap();
        let l = held().channel(&general).unwrap().writers.clone().unwrap();
        assert_eq!(l.current_writer().unwrap().0, Epoch(3), "several lost at once take a fresh epoch");
        let plane = fetch_plane_deliveries(&bed.relay, &held(), &general, crate::community::v2::writers::writer_rekey_scope(&general)).await.unwrap();
        assert!(plane.iter().filter(|d| d.epoch == Epoch(3)).all(|d| d.certs.iter().all(|(w, _)| *w != b.public_key().to_bytes() && *w != c.public_key().to_bytes())), "without them");
    }

    #[tokio::test]
    async fn a_demoted_manager_who_writes_takes_a_fresh_epoch_not_a_stop() {
        use crate::community::roles::OverwriteTarget;
        let (bed, _owner, x, community) = v2_bed_with_admin("Demoted writer").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let general = held().channels[0].id;
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
        // x manages and writes through one role, and loses both in one change.
        let lead = create_role_v2(&bed.relay, &held(), "Lead", 0, Permissions::MANAGE_CHANNELS).await.unwrap();
        let plain = create_role_v2(&bed.relay, &held(), "Plain", 0, 0).await.unwrap();
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Role(lead.clone()), Permissions::SEND_MESSAGES, 0).await.unwrap();
        set_member_roles(&bed.relay, &held(), &x.public_key(), vec![plain.clone(), lead]).await.unwrap();
        assert_eq!(held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0, Epoch(1));
        set_member_roles(&bed.relay, &held(), &x.public_key(), vec![plain]).await.unwrap();
        let l = held().channel(&general).unwrap().writers.clone().unwrap();
        assert_eq!(l.current_writer().unwrap().0, Epoch(2), "the certifier x held goes with a fresh epoch");
        assert!(!l.stopped(Epoch(1), &x.public_key().to_bytes(), u64::MAX));
    }

    #[tokio::test]
    async fn a_stop_fits_only_while_the_live_entry_stays_and_the_writer_isnt_stopped() {
        use crate::community::v2::writers::{writer_address, Ledger, Spell};
        let (bed, owner, _member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Full", bed.relays.clone(), None).await.unwrap();
        let mut ch = community.channels[0].clone();
        let mut l = Ledger::new(&ch.id).appended(1_000, Spell::Writer { epoch: Epoch(1), pk: writer_address(&[1; 32], &ch.id, Epoch(1)), root: Epoch(0), by: [0x0b; 32], certifier: None }).unwrap();
        let w = Keys::generate().public_key();
        for _ in 1..crate::community::v2::writers::MAX_LEDGER - 1 {
            l = l.appended(2_000, Spell::Stop { writer: Keys::generate().public_key().to_bytes() }).unwrap();
        }
        ch.writers = Some(l.clone());
        assert!(writing::stop_fits(&ch, &w), "one slot left");
        ch.writers = Some(l.appended(2_000, Spell::Stop { writer: w.to_bytes() }).unwrap());
        assert!(!writing::stop_fits(&ch, &w), "stopped already");
        assert!(!writing::stop_fits(&ch, &Keys::generate().public_key()), "full: a stop would retire the live entry");
    }

    #[tokio::test]
    async fn an_epoch_from_before_certificates_is_replaced_by_one_with_a_certifier() {
        use crate::community::roles::OverwriteTarget;
        use crate::community::v2::writers::{writer_address, Ledger, Spell};
        let (bed, owner, _x, community) = v2_bed_with_admin("Legacy").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let general = held().channels[0].id;
        let eid = crate::community::v2::derive::writers_locator(community.id(), &general);
        let old = Ledger::new(&general).appended(2_001_000, Spell::Writer { epoch: Epoch(1), pk: writer_address(&[0x77; 32], &general, Epoch(1)), root: Epoch(0), by: owner.keys.public_key().to_bytes(), certifier: None }).unwrap();
        publish_overwrite_raw(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await;
        publish_marked(&bed.relay, &held(), &owner.keys, vsk::WRITERS, &eid, 1, None, &old.to_json()).await;
        follow_control(&bed.relay, &held()).await.unwrap();
        assert!(held().channel(&general).unwrap().writers.as_ref().is_some_and(|l| l.certifier(Epoch(1)).is_none()), "folded the old ledger");
        assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().writers.moved, 1);
        let l = held().channel(&general).unwrap().writers.clone().unwrap();
        assert_eq!(l.current_writer().unwrap().0, Epoch(2));
        assert!(l.certifier(Epoch(2)).is_some(), "anyone handed the old key could post");
    }

    #[tokio::test]
    async fn a_manager_promoted_since_the_mint_is_handed_the_certifier() {
        let (bed, owner, member, community, general) = restricted_bed(false).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        bed.swap_to(&owner);
        let mods = create_role_v2(&bed.relay, &held(), "Mods", 0, Permissions::MANAGE_CHANNELS).await.unwrap();
        set_member_roles(&bed.relay, &held(), &member.keys.public_key(), vec![mods]).await.unwrap();
        access_duty(&bed.relay, &held()).await.unwrap();
        bed.swap_to(&member);
        follow_control(&bed.relay, &held()).await.unwrap();
        collect_writers(&bed.relay, &held()).await.unwrap();
        let ch = held().channel(&general).unwrap().clone();
        let live = ch.writers.as_ref().unwrap().current_writer().unwrap().0;
        assert!(writing::certifier_held(&held(), &ch, live).is_some(), "a manager can let a writer in without a new epoch");
        assert!(writing::live_writer(&held(), &ch).is_some(), "and holds the key to hand on");
        assert_eq!(live, Epoch(1));
    }

    #[tokio::test]
    async fn a_manager_who_leaves_takes_the_certifier_with_them_so_a_fresh_epoch_replaces_it() {
        let (bed, owner, member, community, general) = restricted_bed(true).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        bed.swap_to(&member);
        collect_writers(&bed.relay, &held()).await.unwrap();
        let ch = held().channel(&general).unwrap().clone();
        assert!(writing::certifier_held(&held(), &ch, Epoch(1)).is_some());
        let gb = crate::community::v2::derive::guestbook_group_key(&held().community_root, community.id(), held().root_epoch);
        // A role they still hold never reads as newer than leaving.
        let left_at = now_ms();
        let leave = guestbook::build_leave_rumor(member.keys.public_key(), left_at);
        let (wrap, _) = guestbook::seal_guestbook_rumor(&leave, &gb, &member.keys, Timestamp::from_secs(left_at / 1000)).unwrap();
        bed.relay.publish(&wrap, &held().relays).await.unwrap();
        bed.swap_to(&owner);
        sync_guestbook(&bed.relay, &held()).await.unwrap();
        crate::rt::time::sleep(std::time::Duration::from_millis(1_100)).await;
        assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().writers.moved, 1);
        assert_eq!(held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0, Epoch(2));
        assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().writers, WriterDuty::default(), "once");
    }

    #[tokio::test]
    async fn a_post_shown_before_its_writers_stop_was_read_is_taken_back() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, member, community, general) = restricted_bed(false).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let read = channel_group_key(&community.community_root, &general, community.root_epoch);
        let chan_hex = crate::simd::hex::bytes_to_hex_32(&general.0);
        bed.swap_to(&owner);
        let w = Keys::generate();
        let plain = create_role_v2(&bed.relay, &held(), "Plain", 0, 0).await.unwrap();
        set_member_roles(&bed.relay, &held(), &w.public_key(), vec![plain]).await.unwrap();
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
        let (live, _, writer) = writing::live_writer(&held(), held().channel(&general).unwrap()).unwrap();
        let signed = GroupKey::from_parts(writer.keys().clone(), read.conv_key().clone());
        let cert = cert_for(&held(), &general, live, &w.public_key());
        post_certified(&bed.relay, &held(), &w, &general, &signed, community.root_epoch, Some((live, Some(cert))), "before", now_ms() - 5_000).await;
        post_certified(&bed.relay, &held(), &w, &general, &signed, community.root_epoch, Some((live, Some(cert))), "after", now_ms() + 3_000).await;
        // A member reads both while w may still post.
        bed.swap_to(&member);
        follow_control(&bed.relay, &held()).await.unwrap();
        let page = fetch_channel_history(&bed.relay, &held(), &general, 50, 2, None, None, crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await.unwrap();
        let ids: std::collections::HashMap<String, String> = page.iter().map(|f| (f.event.opened().rumor.content.clone(), f.event.opened().rumor_id.to_hex())).collect();
        for f in page.iter().filter(|f| ids.contains_key(&f.event.opened().rumor.content)) {
            crate::community::v2::inbound::persist_routed_chat_event(&f.event, &chan_hex, &community.id().0, &member.keys.public_key()).await;
        }
        bed.swap_to(&owner);
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), 0, 0).await.unwrap();
        bed.swap_to(&member);
        follow_control(&bed.relay, &held()).await.unwrap();
        let ledger = held().channel(&general).unwrap().writers.clone().unwrap();
        let added = vec![ledger.entries.last().unwrap().clone()];
        let shown = Shown::default();
        assert_eq!(writing::retract_after(&bed.relay, &held(), held().channel(&general).unwrap(), &added, &shown).await, 1);
        assert_eq!(shown.take(), vec![(format!("-{}", ids["after"]), false)], "only what the stop undoes");
        assert!(crate::db::events::get_message_by_id(&ids["after"]).await.unwrap().is_none());
        assert!(crate::db::events::get_message_by_id(&ids["before"]).await.unwrap().is_some(), "a writer's past posts stay theirs");
        // The read after the move holds it again, for a later judgment.
        assert!(!channel_texts(&bed.relay, &held(), &general).await.contains(&"after".to_string()));
        assert_eq!(crate::db::community::held_wraps(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap().len(), 1);
    }

    #[tokio::test]
    async fn an_edit_a_stopped_writer_made_after_the_stop_is_undone() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, member, community, general) = restricted_bed(false).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let read = channel_group_key(&community.community_root, &general, community.root_epoch);
        let chan_hex = crate::simd::hex::bytes_to_hex_32(&general.0);
        bed.swap_to(&owner);
        let w = Keys::generate();
        set_member_roles(&bed.relay, &held(), &w.public_key(), vec![create_role_v2(&bed.relay, &held(), "Plain", 0, 0).await.unwrap()]).await.unwrap();
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
        let (live, _, writer) = writing::live_writer(&held(), held().channel(&general).unwrap()).unwrap();
        let signed = GroupKey::from_parts(writer.keys().clone(), read.conv_key().clone());
        let cert = cert_for(&held(), &general, live, &w.public_key());
        post_certified(&bed.relay, &held(), &w, &general, &signed, community.root_epoch, Some((live, Some(cert))), "original", now_ms() - 5_000).await;
        let original = fetch_channel_history(&bed.relay, &held(), &general, 50, 2, None, None, crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await.unwrap()
            .into_iter().find(|f| f.event.opened().rumor.content == "original").unwrap().event.opened().rumor_id.to_hex();
        let edit = chat::with_writer(chat::build_edit_rumor(w.public_key(), &general, community.root_epoch, &original, "rewritten", &[], None, now_ms() + 3_000), live, Some(&cert));
        let (wrap, _) = chat::seal_chat_rumor(&edit, &signed, &w, Timestamp::from_secs(now_ms() / 1000 + 3), false).unwrap();
        bed.relay.publish(&wrap, &held().relays).await.unwrap();
        bed.swap_to(&member);
        follow_control(&bed.relay, &held()).await.unwrap();
        let page = fetch_channel_history(&bed.relay, &held(), &general, 50, 2, None, None, crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await.unwrap();
        for f in &page {
            crate::community::v2::inbound::persist_routed_chat_event(&f.event, &chan_hex, &community.id().0, &member.keys.public_key()).await;
        }
        assert_eq!(crate::db::events::get_message_by_id(&original).await.unwrap().unwrap().1.content, "rewritten");
        bed.swap_to(&owner);
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), 0, 0).await.unwrap();
        bed.swap_to(&member);
        follow_control(&bed.relay, &held()).await.unwrap();
        let ledger = held().channel(&general).unwrap().writers.clone().unwrap();
        let added = vec![ledger.entries.last().unwrap().clone()];
        let shown = Shown::default();
        assert_eq!(writing::retract_after(&bed.relay, &held(), held().channel(&general).unwrap(), &added, &shown).await, 1);
        assert_eq!(crate::db::events::get_message_by_id(&original).await.unwrap().unwrap().1.content, "original", "the edit is undone");
        assert_eq!(shown.take(), vec![("~original".to_string(), false)]);
        assert_eq!(crate::db::community::held_wraps(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap().len(), 1, "and its wrap waits");
    }

    #[tokio::test]
    async fn a_read_address_post_shown_before_the_restrict_was_read_is_taken_back() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, member, community, general) = restricted_bed(false).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let read = channel_group_key(&community.community_root, &general, community.root_epoch);
        let chan_hex = crate::simd::hex::bytes_to_hex_32(&general.0);
        bed.swap_to(&owner);
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, 0).await.unwrap();
        let p = Keys::generate();
        post_raw(&bed.relay, &held(), &p, &general, &read, community.root_epoch, None, "while open", now_ms() - 5_000).await;
        post_raw(&bed.relay, &held(), &p, &general, &read, community.root_epoch, None, "after the restrict", now_ms() + 3_000).await;
        bed.swap_to(&member);
        follow_control(&bed.relay, &held()).await.unwrap();
        let page = fetch_channel_history(&bed.relay, &held(), &general, 50, 2, None, None, crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await.unwrap();
        let ids: std::collections::HashMap<String, String> = page.iter().map(|f| (f.event.opened().rumor.content.clone(), f.event.opened().rumor_id.to_hex())).collect();
        for f in &page {
            crate::community::v2::inbound::persist_routed_chat_event(&f.event, &chan_hex, &community.id().0, &member.keys.public_key()).await;
        }
        bed.swap_to(&owner);
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
        bed.swap_to(&member);
        follow_control(&bed.relay, &held()).await.unwrap();
        let ledger = held().channel(&general).unwrap().writers.clone().unwrap();
        let added = vec![ledger.entries.last().unwrap().clone()];
        assert!(matches!(added[0].spell, crate::community::v2::writers::Spell::Writer { .. }));
        let shown = Shown::default();
        assert_eq!(writing::retract_after(&bed.relay, &held(), held().channel(&general).unwrap(), &added, &shown).await, 1);
        assert_eq!(shown.take(), vec![(format!("-{}", ids["after the restrict"]), false)]);
        assert!(crate::db::events::get_message_by_id(&ids["while open"]).await.unwrap().is_some(), "what was said while open stays");
    }

    #[tokio::test]
    async fn a_post_dated_past_the_horizon_or_by_a_banned_author_is_never_held() {
        let (bed, owner, _member, community, general) = restricted_bed(false).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let read = channel_group_key(&community.community_root, &general, community.root_epoch);
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        bed.swap_to(&owner);
        let (far, banned) = (Keys::generate(), Keys::generate());
        crate::db::community::set_community_banlist(&cid_hex, &[banned.public_key().to_hex()], 1).unwrap();
        post_raw(&bed.relay, &held(), &far, &general, &read, community.root_epoch, None, "from next week", now_ms() + 7 * 86_400_000).await;
        post_raw(&bed.relay, &held(), &banned, &general, &read, community.root_epoch, None, "banned", now_ms()).await;
        let page = fetch_channel_history(&bed.relay, &held(), &general, 50, 2, None, None, crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await.unwrap();
        assert!(page.iter().all(|f| !f.event.opened().held), "a manager keeps no copy of either");
        assert!(crate::db::community::held_wraps(&cid_hex).unwrap().is_empty(), "and nothing waits");
    }

    #[tokio::test]
    async fn a_backstop_acting_on_one_writer_checks_them_on_the_roster_it_reads_again() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, member, community, general) = restricted_bed(false).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let m = member.keys.public_key();
        bed.swap_to(&owner);
        let before = crate::db::community::get_community_roles(&cid_hex).unwrap();
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(m.to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
        let ledger = held().channel(&general).unwrap().writers.clone();
        // A pass whose roster predates the grant would stop a writer who may post.
        assert_eq!(writing::backstop_act_on(&bed.relay, &held(), &general, &before, writing::Act::Stop(m, writing::Rights::Full)).await.unwrap(), writing::Backstop::StoodDown);
        assert_eq!(held().channel(&general).unwrap().writers, ledger);
        // And one whose roster still lets a stopped writer post can't let them back once it doesn't.
        let after = crate::db::community::get_community_roles(&cid_hex).unwrap();
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(m.to_hex()), 0, 0).await.unwrap();
        let ledger = held().channel(&general).unwrap().writers.clone();
        assert!(ledger.as_ref().unwrap().stopped(Epoch(1), &m.to_bytes(), u64::MAX));
        assert_eq!(writing::backstop_act_on(&bed.relay, &held(), &general, &after, writing::Act::Restart(m)).await.unwrap(), writing::Backstop::StoodDown);
        assert_eq!(held().channel(&general).unwrap().writers, ledger);
    }

    #[tokio::test]
    async fn demoting_a_manager_who_never_held_the_certifier_spends_nothing() {
        let (bed, owner, member, community, general) = restricted_bed(false).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        bed.swap_to(&owner);
        let mods = create_role_v2(&bed.relay, &held(), "Mods", 0, Permissions::MANAGE_CHANNELS).await.unwrap();
        let plain = create_role_v2(&bed.relay, &held(), "Plain", 0, 0).await.unwrap();
        set_member_roles(&bed.relay, &held(), &member.keys.public_key(), vec![plain.clone(), mods]).await.unwrap();
        set_member_roles(&bed.relay, &held(), &member.keys.public_key(), vec![plain]).await.unwrap();
        assert_eq!(held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0, Epoch(1), "promoted and demoted before anyone handed them the certifier");
    }

    #[tokio::test]
    async fn losing_send_again_after_a_stop_spends_nothing() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, member, community, general) = restricted_bed(false).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let m = member.keys.public_key();
        bed.swap_to(&owner);
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(m.to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
        publish_overwrite_raw(&bed.relay, &held(), general.0, OverwriteTarget::Member(m.to_hex()), 0, 0).await;
        follow_control(&bed.relay, &held()).await.unwrap();
        sync_guestbook(&bed.relay, &held()).await.unwrap();
        assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().writers.cut, 1);
        // Let back without a settle, then taken away by one: the stop already stands.
        publish_overwrite_raw(&bed.relay, &held(), general.0, OverwriteTarget::Member(m.to_hex()), Permissions::SEND_MESSAGES, 0).await;
        follow_control(&bed.relay, &held()).await.unwrap();
        let entries = held().channel(&general).unwrap().writers.as_ref().unwrap().entries.len();
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(m.to_hex()), 0, 0).await.unwrap();
        let l = held().channel(&general).unwrap().writers.clone().unwrap();
        assert_eq!((l.current_writer().unwrap().0, l.entries.len()), (Epoch(1), entries), "no fresh epoch, no second stop");
    }

    #[tokio::test]
    async fn a_member_who_left_and_came_back_is_judged_on_a_memberlist_read_whole() {
        let (bed, owner, member, community, general) = restricted_bed(true).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        bed.swap_to(&member);
        collect_writers(&bed.relay, &held()).await.unwrap();
        let gb = crate::community::v2::derive::guestbook_group_key(&held().community_root, community.id(), held().root_epoch);
        let left_at = now_ms();
        let leave = guestbook::build_leave_rumor(member.keys.public_key(), left_at);
        let (wrap, _) = guestbook::seal_guestbook_rumor(&leave, &gb, &member.keys, Timestamp::from_secs(left_at / 1000)).unwrap();
        bed.relay.publish(&wrap, &held().relays).await.unwrap();
        bed.swap_to(&owner);
        sync_guestbook(&bed.relay, &held()).await.unwrap();
        // They come back; this device starts again and hasn't read the plane whole yet.
        crate::rt::time::sleep(std::time::Duration::from_millis(1_100)).await;
        let join = guestbook::build_join_rumor(member.keys.public_key(), None, now_ms());
        bed.swap_to(&member);
        let (wrap, _) = guestbook::seal_guestbook_rumor(&join, &gb, &member.keys, Timestamp::from_secs(now_ms() / 1000)).unwrap();
        bed.relay.publish(&wrap, &held().relays).await.unwrap();
        bed.swap_to(&owner);
        assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().writers.moved, 0, "the stored memberlist says they left, but it isn't the whole story");
        sync_guestbook(&bed.relay, &held()).await.unwrap();
        assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().writers.moved, 0, "read whole, they're back");
        assert_eq!(held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0, Epoch(1));
    }

    /// Loses the `nth` distinct event sent to one plane, every time it is sent.
    struct LosesOne<'a> {
        inner: &'a MemoryRelay,
        plane: String,
        nth: usize,
        seen: std::sync::Mutex<Vec<nostr_sdk::prelude::EventId>>,
    }
    #[async_trait::async_trait]
    impl Transport for LosesOne<'_> {
        async fn fetch_plane(&self, plane: &Keys, query: &Query, relays: &[String]) -> Result<crate::community::transport::PlaneFetch, String> {
            self.inner.fetch_plane(plane, query, relays).await
        }
        async fn publish(&self, e: &Event, r: &[String]) -> Result<(), String> {
            if e.pubkey.to_hex() == self.plane {
                let mut seen = self.seen.lock().unwrap();
                if !seen.contains(&e.id) {
                    seen.push(e.id);
                }
                if seen.iter().position(|id| *id == e.id) == Some(self.nth - 1) {
                    return Err("dropped".into());
                }
            }
            self.inner.publish(e, r).await
        }
        async fn publish_durable(&self, e: &Event, r: &[String]) -> Result<(), String> {
            self.publish(e, r).await
        }
        async fn fetch(&self, q: &Query, r: &[String]) -> Result<Vec<Event>, String> {
            self.inner.fetch(q, r).await
        }
    }

    #[tokio::test]
    async fn a_mint_whose_delivery_lost_a_part_leaves_nobody_out() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, _member, community, general) = restricted_bed(false).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        bed.swap_to(&owner);
        let role = create_role_v2(&bed.relay, &held(), "Writers", 0, 0).await.unwrap();
        // Three parts, so the one dropped holds writers whatever order its recipients sort in.
        let writers: Vec<Keys> = (0..2 * rekey::MAX_CERTIFIED_BLOBS_PER_EVENT + 2).map(|_| Keys::generate()).collect();
        for w in &writers {
            set_member_roles(&bed.relay, &held(), &w.public_key(), vec![role.clone()]).await.unwrap();
        }
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Role(role.clone()), Permissions::SEND_MESSAGES, 0).await.unwrap();
        // Two lose Send at once: a fresh epoch, whose second part a relay drops.
        let lossy = LosesOne { inner: &bed.relay, plane: access_group(&held(), &general).pk_hex(), nth: 2, seen: Default::default() };
        for w in &writers[..2] {
            publish_overwrite_raw(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), 0, Permissions::SEND_MESSAGES).await;
        }
        let before = crate::db::community::get_community_roles(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        let after = crate::db::community::get_community_roles(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap();
        let _ = writing::settle_for_test(&lossy, &held(), &before, &after).await;
        let live = held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0;
        assert_eq!(live, Epoch(2));
        let scope = crate::community::v2::writers::writer_rekey_scope(&general);
        let plane = fetch_plane_deliveries(&bed.relay, &held(), &general, scope).await.unwrap();
        let stranded: Vec<&Keys> = writers[2..].iter().filter(|w| !served_at(&plane, &w.public_key(), scope, live, &|_| true)).collect();
        assert!(!stranded.is_empty(), "the part a relay dropped served nobody");
        sync_guestbook(&bed.relay, &held()).await.unwrap();
        access_duty(&bed.relay, &held()).await.unwrap();
        let plane = fetch_plane_deliveries(&bed.relay, &held(), &general, scope).await.unwrap();
        assert!(writers[2..].iter().all(|w| served_at(&plane, &w.public_key(), scope, live, &|_| true)), "the next pass serves those the lost part left out");
        assert!(writers[..2].iter().all(|w| !served_at(&plane, &w.public_key(), scope, live, &|_| true)), "and never those the change took out");
    }

    #[tokio::test]
    async fn a_mint_with_no_part_in_view_cuts_nobody_whatever_the_minter_tops_up() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, _member, community, general) = restricted_bed(false).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        bed.swap_to(&owner);
        let role = create_role_v2(&bed.relay, &held(), "Writers", 0, 0).await.unwrap();
        let writers: Vec<Keys> = (0..4).map(|_| Keys::generate()).collect();
        for w in &writers {
            set_member_roles(&bed.relay, &held(), &w.public_key(), vec![role.clone()]).await.unwrap();
        }
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Role(role.clone()), Permissions::SEND_MESSAGES, 0).await.unwrap();
        // Two lose Send at once: a fresh epoch, whose only part a relay drops for good.
        let lossy = LosesOne { inner: &bed.relay, plane: access_group(&held(), &general).pk_hex(), nth: 1, seen: Default::default() };
        for w in &writers[..2] {
            publish_overwrite_raw(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), 0, Permissions::SEND_MESSAGES).await;
        }
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let before = crate::db::community::get_community_roles(&cid_hex).unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        let after = crate::db::community::get_community_roles(&cid_hex).unwrap();
        let _ = writing::settle_for_test(&lossy, &held(), &before, &after).await;
        let live = held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0;
        assert_eq!(live, Epoch(2));
        // The minter tops up a writer the Channel gains: untagged, never the mint.
        let fresh = Keys::generate();
        set_member_roles(&bed.relay, &held(), &fresh.public_key(), vec![role]).await.unwrap();
        sync_guestbook(&bed.relay, &held()).await.unwrap();
        access_duty(&bed.relay, &held()).await.unwrap();
        let scope = crate::community::v2::writers::writer_rekey_scope(&general);
        let plane = fetch_plane_deliveries(&bed.relay, &held(), &general, scope).await.unwrap();
        assert!(writers[2..].iter().all(|w| served_at(&plane, &w.public_key(), scope, live, &|_| true)), "those the lost mint carried are served, not cut");
    }

    #[tokio::test]
    async fn taking_back_judges_the_wrap_as_it_came_whatever_its_date_says() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, member, community, general) = restricted_bed(false).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let read = channel_group_key(&community.community_root, &general, community.root_epoch);
        let chan_hex = crate::simd::hex::bytes_to_hex_32(&general.0);
        bed.swap_to(&owner);
        let w = Keys::generate();
        let plain = create_role_v2(&bed.relay, &held(), "Plain", 0, 0).await.unwrap();
        set_member_roles(&bed.relay, &held(), &w.public_key(), vec![plain]).await.unwrap();
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
        let (e1, _, writer1) = writing::live_writer(&held(), held().channel(&general).unwrap()).unwrap();
        let cert1 = cert_for(&held(), &general, e1, &w.public_key());
        let at1 = GroupKey::from_parts(writer1.keys().clone(), read.conv_key().clone());
        bed.swap_to(&member);
        follow_control(&bed.relay, &held()).await.unwrap();
        // w is stopped, then two lose Send at once and a fresh epoch begins; w keeps posting at e1.
        bed.swap_to(&owner);
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), 0, 0).await.unwrap();
        let (y1, y2) = (Keys::generate(), Keys::generate());
        let wr = create_role_v2(&bed.relay, &held(), "W", 0, 0).await.unwrap();
        for y in [&y1, &y2] {
            set_member_roles(&bed.relay, &held(), &y.public_key(), vec![wr.clone()]).await.unwrap();
        }
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Role(wr.clone()), Permissions::SEND_MESSAGES, 0).await.unwrap();
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Role(wr), 0, 0).await.unwrap();
        let ledger = held().channel(&general).unwrap().writers.clone().unwrap();
        assert!(ledger.current_writer().unwrap().0 > e1, "a fresh epoch began");
        post_certified(&bed.relay, &held(), &w, &general, &at1, community.root_epoch, Some((e1, Some(cert1))), "at the old address", now_ms() + 2_000).await;
        // The member stores it on the ledger it holds, then folds what moved.
        bed.swap_to(&member);
        let stale = held();
        let page = fetch_channel_history(&bed.relay, &stale, &general, 50, 2, None, None, crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await.unwrap();
        for f in page.iter().filter(|f| f.event.opened().rumor.content == "at the old address") {
            crate::community::v2::inbound::persist_routed_chat_event(&f.event, &chan_hex, &community.id().0, &member.keys.public_key()).await.expect("stood on the stale ledger");
        }
        follow_control(&bed.relay, &held()).await.unwrap();
        let now_ledger = held().channel(&general).unwrap().writers.clone().unwrap();
        let added: Vec<_> = now_ledger.entries.iter().filter(|e| !stale.channel(&general).unwrap().writers.as_ref().unwrap().entries.contains(e)).cloned().collect();
        let shown = Shown::default();
        writing::retract_after(&bed.relay, &held(), held().channel(&general).unwrap(), &added, &shown).await;
        assert!(!channel_texts(&bed.relay, &held(), &general).await.contains(&"at the old address".to_string()));
        let ids: Vec<String> = page.iter().filter(|f| f.event.opened().rumor.content == "at the old address").map(|f| f.event.opened().rumor_id.to_hex()).collect();
        assert!(crate::db::events::get_message_by_id(&ids[0]).await.unwrap().is_none(), "a stopped writer's post at the old address goes, however late it is dated");
    }

    #[tokio::test]
    async fn a_read_address_rewrite_made_after_the_restrict_is_undone_once_it_is_read() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, member, community, general) = restricted_bed(false).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let read = channel_group_key(&community.community_root, &general, community.root_epoch);
        let chan_hex = crate::simd::hex::bytes_to_hex_32(&general.0);
        bed.swap_to(&owner);
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, 0).await.unwrap();
        let z = Keys::generate();
        set_member_roles(&bed.relay, &held(), &z.public_key(), vec![create_role_v2(&bed.relay, &held(), "Plain", 0, 0).await.unwrap()]).await.unwrap();
        bed.swap_to(&member);
        follow_control(&bed.relay, &held()).await.unwrap();
        let stale = held();
        assert!(!stale.channel(&general).unwrap().restricted());
        bed.swap_to(&owner);
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
        let target_post = chat::build_message_rumor(z.public_key(), &general, community.root_epoch, "z original", None, &[], vec![], now_ms() - 60_000);
        let target = target_post.id.unwrap().to_hex();
        let (tw, _) = chat::seal_chat_rumor(&target_post, &read, &z, Timestamp::from_secs(now_ms() / 1000 - 60), false).unwrap();
        bed.relay.publish(&tw, &held().relays).await.unwrap();
        let edit = chat::build_edit_rumor(z.public_key(), &general, community.root_epoch, &target, "z rewritten", &[], None, now_ms() + 2_000);
        let (ew, _) = chat::seal_chat_rumor(&edit, &read, &z, Timestamp::from_secs(now_ms() / 1000 + 2), false).unwrap();
        bed.relay.publish(&ew, &held().relays).await.unwrap();
        bed.swap_to(&member);
        let ch = stale.channel(&general).unwrap().clone();
        let judge = writing::Judge::of(&stale, &ch);
        for wrap in [&tw, &ew] {
            let ev = chat::open_chat_event(wrap, &read, &general, community.root_epoch).unwrap();
            if let Some(ev) = writing::judge_arrival(judge.as_ref(), &community.id().0, &general, wrap, ev, None) {
                crate::community::v2::inbound::persist_routed_chat_event(&ev, &chan_hex, &community.id().0, &member.keys.public_key()).await;
            }
        }
        assert_eq!(crate::db::events::get_message_by_id(&target).await.unwrap().unwrap().1.content, "z rewritten", "stood on the open ledger");
        follow_control(&bed.relay, &held()).await.unwrap();
        let now_ledger = held().channel(&general).unwrap().writers.clone().unwrap();
        let added: Vec<_> = now_ledger.entries.iter().filter(|e| !stale.channel(&general).unwrap().writers.as_ref().map_or(false, |l| l.entries.contains(e))).cloned().collect();
        let shown = Shown::default();
        writing::retract_after(&bed.relay, &held(), held().channel(&general).unwrap(), &added, &shown).await;
        assert_eq!(crate::db::events::get_message_by_id(&target).await.unwrap().unwrap().1.content, "z original", "a non-writer's rewrite after the restrict is undone");
        assert_eq!(crate::state::STATE.lock().await.find_message(&target).map(|(_, m)| m.content), Some("z original".to_string()), "on screen too");
    }

    #[tokio::test]
    async fn taking_back_keeps_what_it_has_no_room_to_hold_and_lets_go_what_is_dated_past_the_hour() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, member, community, general) = restricted_bed(false).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let read = channel_group_key(&community.community_root, &general, community.root_epoch);
        let chan_hex = crate::simd::hex::bytes_to_hex_32(&general.0);
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        bed.swap_to(&owner);
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, 0).await.unwrap();
        bed.swap_to(&member);
        follow_control(&bed.relay, &held()).await.unwrap();
        let p = Keys::generate();
        post_raw(&bed.relay, &held(), &p, &general, &read, community.root_epoch, None, "soon", now_ms() + 30 * 60_000).await;
        post_raw(&bed.relay, &held(), &p, &general, &read, community.root_epoch, None, "far", now_ms() + 2 * 60 * 60_000).await;
        // Shown once their time came, read here as a device whose clock has reached them.
        crate::clock::shift_for_test(3 * 60 * 60_000);
        let page = fetch_channel_history(&bed.relay, &held(), &general, 50, 2, None, None, crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await.unwrap();
        let mut ids = std::collections::HashMap::new();
        for f in page.iter().filter(|f| ["soon", "far"].contains(&f.event.opened().rumor.content.as_str())) {
            crate::community::v2::inbound::persist_routed_chat_event(&f.event, &chan_hex, &community.id().0, &member.keys.public_key()).await.expect("stood while open");
            ids.insert(f.event.opened().rumor.content.clone(), f.event.opened().rumor_id.to_hex());
        }
        crate::clock::shift_for_test(0);
        assert_eq!(ids.len(), 2);
        bed.swap_to(&owner);
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
        bed.swap_to(&member);
        follow_control(&bed.relay, &held()).await.unwrap();
        // The Channel's held store is full of posts dated nearer now.
        for a in 0..crate::db::community::MAX_HELD_WRAPS / crate::db::community::MAX_HELD_PER_AUTHOR {
            let author = Keys::generate().public_key().to_hex();
            for i in 0..crate::db::community::MAX_HELD_PER_AUTHOR {
                crate::db::community::hold_wrap(&cid_hex, &chan_hex, &format!("{a:02}{i:062}"), "{}", &author, now_ms()).unwrap();
            }
        }
        let ledger = held().channel(&general).unwrap().writers.clone().unwrap();
        let added = vec![ledger.entries.last().unwrap().clone()];
        writing::retract_after(&bed.relay, &held(), held().channel(&general).unwrap(), &added, &Shown::default()).await;
        assert!(crate::db::events::get_message_by_id(&ids["soon"]).await.unwrap().is_some(), "with no room to hold it, it stays");
        assert!(crate::db::events::get_message_by_id(&ids["far"]).await.unwrap().is_none(), "past the hour the relays keep it until its date nears");
    }

    /// Fails each event's first send to one plane.
    struct FailsFirst<'a> {
        inner: &'a MemoryRelay,
        plane: String,
        tried: std::sync::Mutex<std::collections::HashSet<nostr_sdk::prelude::EventId>>,
    }
    #[async_trait::async_trait]
    impl Transport for FailsFirst<'_> {
        async fn fetch_plane(&self, plane: &Keys, query: &Query, relays: &[String]) -> Result<crate::community::transport::PlaneFetch, String> {
            self.inner.fetch_plane(plane, query, relays).await
        }
        async fn publish(&self, e: &Event, r: &[String]) -> Result<(), String> {
            if e.pubkey.to_hex() == self.plane && self.tried.lock().unwrap().insert(e.id) {
                return Err("flaked".into());
            }
            self.inner.publish(e, r).await
        }
        async fn publish_durable(&self, e: &Event, r: &[String]) -> Result<(), String> {
            self.publish(e, r).await
        }
        async fn fetch(&self, q: &Query, r: &[String]) -> Result<Vec<Event>, String> {
            self.inner.fetch(q, r).await
        }
    }

    #[tokio::test]
    async fn a_mint_sends_each_part_again_when_a_send_fails() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, _member, community, general) = restricted_bed(false).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        bed.swap_to(&owner);
        let role = create_role_v2(&bed.relay, &held(), "Writers", 0, 0).await.unwrap();
        let writers: Vec<Keys> = (0..4).map(|_| Keys::generate()).collect();
        for w in &writers {
            set_member_roles(&bed.relay, &held(), &w.public_key(), vec![role.clone()]).await.unwrap();
        }
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Role(role), Permissions::SEND_MESSAGES, 0).await.unwrap();
        let flaky = FailsFirst { inner: &bed.relay, plane: access_group(&held(), &general).pk_hex(), tried: Default::default() };
        for w in &writers[..2] {
            publish_overwrite_raw(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), 0, Permissions::SEND_MESSAGES).await;
        }
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let before = crate::db::community::get_community_roles(&cid_hex).unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        let after = crate::db::community::get_community_roles(&cid_hex).unwrap();
        writing::settle_for_test(&flaky, &held(), &before, &after).await.unwrap();
        let live = held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0;
        let scope = crate::community::v2::writers::writer_rekey_scope(&general);
        let plane = fetch_plane_deliveries(&bed.relay, &held(), &general, scope).await.unwrap();
        assert!(writers[2..].iter().all(|w| served_at(&plane, &w.public_key(), scope, live, &|_| true)), "a send that failed once is sent again");
    }

    #[tokio::test]
    async fn a_mint_the_backstop_finds_owed_to_one_writer_only_stops_that_one() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, _member, community, general) = restricted_bed(false).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        bed.swap_to(&owner);
        let role = create_role_v2(&bed.relay, &held(), "Writers", 0, 0).await.unwrap();
        let writers: Vec<Keys> = (0..3).map(|_| Keys::generate()).collect();
        for w in &writers {
            set_member_roles(&bed.relay, &held(), &w.public_key(), vec![role.clone()]).await.unwrap();
        }
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Role(role), Permissions::SEND_MESSAGES, 0).await.unwrap();
        let live = held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0;
        // The pass judged two gone; by the backstop only one still is.
        publish_overwrite_raw(&bed.relay, &held(), general.0, OverwriteTarget::Member(writers[0].public_key().to_hex()), 0, Permissions::SEND_MESSAGES).await;
        follow_control(&bed.relay, &held()).await.unwrap();
        let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
        let cut = [(writers[0].public_key(), writing::Rights::Full), (writers[1].public_key(), writing::Rights::Full)];
        writing::backstop_act_on(&bed.relay, &held(), &general, &roster, writing::Act::Mint(&cut)).await.unwrap();
        let ledger = held().channel(&general).unwrap().writers.clone().unwrap();
        assert_eq!(ledger.current_writer().unwrap().0, live, "one left: a stop, not a fresh epoch");
        assert!(ledger.stopped(live, &writers[0].public_key().to_bytes(), u64::MAX));
        assert!(!ledger.stopped(live, &writers[1].public_key().to_bytes(), u64::MAX));
    }

    #[tokio::test]
    async fn the_backstop_reads_the_guestbook_again_before_it_stops_anyone() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, _member, community, general) = restricted_bed(false).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        bed.swap_to(&owner);
        let w = Keys::generate();
        set_member_roles(&bed.relay, &held(), &w.public_key(), vec![create_role_v2(&bed.relay, &held(), "Plain", 0, 0).await.unwrap()]).await.unwrap();
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
        let live = held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0;
        let gb = crate::community::v2::derive::guestbook_group_key(&held().community_root, community.id(), held().root_epoch);
        let leave = guestbook::build_leave_rumor(w.public_key(), now_ms());
        let (wrap, _) = guestbook::seal_guestbook_rumor(&leave, &gb, &w, Timestamp::from_secs(now_ms() / 1000)).unwrap();
        bed.relay.publish(&wrap, &held().relays).await.unwrap();
        sync_guestbook(&bed.relay, &held()).await.unwrap();
        crate::rt::time::sleep(std::time::Duration::from_millis(1_100)).await;
        // They come back after the pass read the Leave.
        let join = guestbook::build_join_rumor(w.public_key(), None, now_ms());
        let (wrap, _) = guestbook::seal_guestbook_rumor(&join, &gb, &w, Timestamp::from_secs(now_ms() / 1000)).unwrap();
        bed.relay.publish(&wrap, &held().relays).await.unwrap();
        let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
        writing::backstop_act_on(&bed.relay, &held(), &general, &roster, writing::Act::Stop(w.public_key(), writing::Rights::Full)).await.unwrap();
        assert!(!held().channel(&general).unwrap().writers.as_ref().unwrap().stopped(live, &w.public_key().to_bytes(), u64::MAX), "a Join since stands it down");
    }

    #[tokio::test]
    async fn a_writer_a_whole_mint_left_out_who_may_post_again_gets_a_fresh_epoch() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, _member, community, general) = restricted_bed(false).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        bed.swap_to(&owner);
        let role = create_role_v2(&bed.relay, &held(), "Writers", 0, 0).await.unwrap();
        let writers: Vec<Keys> = (0..4).map(|_| Keys::generate()).collect();
        for w in &writers {
            set_member_roles(&bed.relay, &held(), &w.public_key(), vec![role.clone()]).await.unwrap();
        }
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Role(role), Permissions::SEND_MESSAGES, 0).await.unwrap();
        for w in &writers[..2] {
            publish_overwrite_raw(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), 0, Permissions::SEND_MESSAGES).await;
        }
        let before = crate::db::community::get_community_roles(&cid_hex).unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        let after = crate::db::community::get_community_roles(&cid_hex).unwrap();
        writing::settle_for_test(&bed.relay, &held(), &before, &after).await.unwrap();
        let minted = held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0;
        // Let back by an edit settled elsewhere: the epoch's whole mint left them out, so nobody may serve them this epoch.
        publish_overwrite_raw(&bed.relay, &held(), general.0, OverwriteTarget::Member(writers[0].public_key().to_hex()), 0, 0).await;
        follow_control(&bed.relay, &held()).await.unwrap();
        sync_guestbook(&bed.relay, &held()).await.unwrap();
        access_duty(&bed.relay, &held()).await.unwrap();
        let now = held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0;
        assert!(now > minted, "a fresh epoch takes them back");
        let scope = crate::community::v2::writers::writer_rekey_scope(&general);
        let plane = fetch_plane_deliveries(&bed.relay, &held(), &general, scope).await.unwrap();
        assert!(served_at(&plane, &writers[0].public_key(), scope, now, &|_| true));
        assert!(!served_at(&plane, &writers[1].public_key(), scope, now, &|_| true));
    }

    #[tokio::test]
    async fn edits_made_within_one_second_fold_in_the_order_they_were_made() {
        let (bed, owner, _member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Edits", bed.relays.clone(), None).await.unwrap();
        let general = community.channels[0].id;
        let read = channel_group_key(&community.community_root, &general, community.root_epoch);
        let chan_hex = crate::simd::hex::bytes_to_hex_32(&general.0);
        let z = Keys::generate();
        let second = (now_ms() / 1000 - 30) * 1000;
        let post = chat::build_message_rumor(z.public_key(), &general, community.root_epoch, "first", None, &[], vec![], second - 5_000);
        let target = post.id.unwrap().to_hex();
        let edits = [("third", 900), ("second", 100)].map(|(text, ms)| chat::build_edit_rumor(z.public_key(), &general, community.root_epoch, &target, text, &[], None, second + ms));
        for rumor in std::iter::once(&post).chain(edits.iter()) {
            let (wrap, _) = chat::seal_chat_rumor(rumor, &read, &z, Timestamp::from_secs(second / 1000), false).unwrap();
            let opened = chat::open_chat_event(&wrap, &read, &general, community.root_epoch).unwrap();
            crate::community::v2::inbound::persist_routed_chat_event(&opened, &chan_hex, &community.id().0, &owner.keys.public_key()).await.expect("stored");
        }
        let (_, message) = crate::db::events::get_message_by_id(&target).await.unwrap().unwrap();
        assert_eq!(message.content, "third", "the later edit wins whichever arrived last");
    }

    #[tokio::test]
    async fn a_stop_any_read_folds_is_owed_its_retraction() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, member, community, general) = restricted_bed(false).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let (cid_hex, chan_hex) = (crate::simd::hex::bytes_to_hex_32(&community.id().0), crate::simd::hex::bytes_to_hex_32(&general.0));
        bed.swap_to(&owner);
        let w = Keys::generate();
        set_member_roles(&bed.relay, &held(), &w.public_key(), vec![create_role_v2(&bed.relay, &held(), "Plain", 0, 0).await.unwrap()]).await.unwrap();
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
        bed.swap_to(&member);
        follow_control(&bed.relay, &held()).await.unwrap();
        clear_owed(&cid_hex);
        bed.swap_to(&owner);
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), 0, 0).await.unwrap();
        let stop_at = held().channel(&general).unwrap().writers.as_ref().unwrap().entries.last().unwrap().at;
        // A backstop's read of the Control Plane, not the live follow, is what folds it here.
        bed.swap_to(&member);
        follow_fresh(&bed.relay, community.id()).await.unwrap();
        let owed = crate::db::community::owed_author_retractions(&cid_hex).unwrap();
        assert_eq!(owed.iter().map(|(c, a, s, ..)| (c.clone(), a.clone(), *s)).collect::<Vec<_>>(), vec![(chan_hex.clone(), w.public_key().to_hex(), stop_at)], "a stop owes its writer's posts alone");
        assert!(crate::db::community::owed_retractions(&cid_hex).unwrap().is_empty());
        // What is owed while a drain runs survives its clear.
        let author = w.public_key().to_hex();
        crate::db::community::owe_author_retraction(&cid_hex, &chan_hex, &author, stop_at + 1, None).unwrap();
        crate::db::community::settle_author_retraction(&cid_hex, &chan_hex, &author, owed[0].2, owed[0].3, owed[0].4).unwrap();
        assert_eq!(crate::db::community::owed_author_retractions(&cid_hex).unwrap().len(), 1);
    }

    #[tokio::test]
    async fn a_page_stored_after_its_ledger_moved_owes_a_retraction() {
        let (_bed, _owner, _member, community, general) = restricted_bed(false).await;
        let (cid_hex, chan_hex) = (crate::simd::hex::bytes_to_hex_32(&community.id().0), crate::simd::hex::bytes_to_hex_32(&general.0));
        clear_owed(&cid_hex);
        let judged_on = writing::writers_head(&chan_hex).unwrap();
        writing::owe_if_moved(&chan_hex, Some(judged_on.clone()), 5_000);
        assert!(crate::db::community::owed_retractions(&cid_hex).unwrap().is_empty(), "judged on the ledger it landed under");
        // A move that only reopens takes nothing back.
        let ledger = crate::community::v2::writers::Ledger::parse(&judged_on).unwrap();
        let reopened = ledger.appended(now_ms(), crate::community::v2::writers::Spell::Open).unwrap();
        crate::db::community::set_community_writers(&cid_hex, &chan_hex, &reopened.to_json(), 99, true).unwrap();
        writing::owe_if_moved(&chan_hex, Some(judged_on.clone()), 5_000);
        assert!(crate::db::community::owed_retractions(&cid_hex).unwrap().is_empty(), "an open owes nothing");
        // A stop owes from its own entry, never from a post's earlier date.
        let stop_at = now_ms() + 1;
        let stopped_writer = Keys::generate().public_key();
        let stopped = ledger.appended(stop_at, crate::community::v2::writers::Spell::Stop { writer: stopped_writer.to_bytes() }).unwrap();
        crate::db::community::set_community_writers(&cid_hex, &chan_hex, &stopped.to_json(), 100, true).unwrap();
        clear_owed(&cid_hex);
        writing::owe_if_moved(&chan_hex, Some(judged_on), 5_000);
        assert_eq!(crate::db::community::owed_author_retractions(&cid_hex).unwrap().iter().map(|(c, a, s, ..)| (c.clone(), a.clone(), *s)).collect::<Vec<_>>(), vec![(chan_hex, stopped_writer.to_hex(), stop_at)]);
    }

    #[tokio::test]
    async fn an_edition_no_reader_folds_never_holds_a_mint_back() {
        use crate::community::roles::OverwriteTarget;
        use crate::community::v2::writers::Spell;
        let (bed, owner, x, community) = v2_bed_with_admin("Orphaned").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let general = held().channels[0].id;
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
        let eid = crate::community::v2::derive::writers_locator(community.id(), &general);
        let theirs = held().channel(&general).unwrap().writers.clone().unwrap().appended(now_ms(), Spell::Open).unwrap();
        // Built on a sibling every reader refuses: nothing folds it.
        let cite = cite_on_relay(&bed.relay, &held(), &x).await;
        let rumor = control::build_edition_rumor_bound(x.public_key(), vsk::WRITERS, &eid, 3, Some(&[7u8; 32]), &theirs.to_json(), now_ms() / 1000, cite.as_ref(), Some(crate::community::v2::derive::edition_binding(community.id())));
        let group = control::ControlPlane::of(&held()).write_group().unwrap();
        let (wrap, _) = control::seal_control_edition(&rumor, &group, &x, Timestamp::from_secs(now_ms() / 1000)).unwrap();
        bed.relay.publish(&wrap, &held().relays).await.unwrap();
        act_as(&owner.keys);
        let roster = crate::db::community::get_community_roles(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap();
        let before = held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0;
        writing::mint_for_test(&bed.relay, &held(), &general, &roster).await.unwrap();
        assert!(held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0 > before);
    }

    #[tokio::test]
    async fn a_sibling_that_wins_the_tie_over_the_held_head_holds_a_mint_back() {
        use crate::community::roles::OverwriteTarget;
        use crate::community::v2::writers::{Ledger, Spell};
        let (bed, owner, x, community) = v2_bed_with_admin("Sibling").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let general = held().channels[0].id;
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let eid = crate::community::v2::derive::writers_locator(community.id(), &general);
        let mine = crate::db::community::get_edition_head_inner_id(&cid_hex, &crate::simd::hex::bytes_to_hex_32(&eid)).unwrap().unwrap();
        let cite = cite_on_relay(&bed.relay, &held(), &x).await;
        // x restricted it at the same moment: a first edition of its own, ground until it sorts ahead.
        let secs = now_ms() / 1000;
        let rumor = (0..1000u64)
            .map(|i| {
                let (secret, certifying) = (crate::community::random_32(), crate::community::random_32());
                let spell = Spell::Writer { epoch: Epoch(1), pk: crate::community::v2::writers::writer_address(&secret, &general, Epoch(1)), root: community.root_epoch, by: x.public_key().to_bytes(), certifier: crate::community::v2::writers::certifier_of(&certifying) };
                let theirs = Ledger::new(&general).appended(secs * 1000 + i, spell).unwrap();
                control::build_edition_rumor_bound(x.public_key(), vsk::WRITERS, &eid, 1, None, &theirs.to_json(), secs, cite.as_ref(), Some(crate::community::v2::derive::edition_binding(community.id())))
            })
            .find(|r| r.id.unwrap().to_bytes() < mine)
            .unwrap();
        let group = control::ControlPlane::of(&held()).write_group().unwrap();
        let (wrap, _) = control::seal_control_edition(&rumor, &group, &x, Timestamp::from_secs(secs)).unwrap();
        bed.relay.publish(&wrap, &held().relays).await.unwrap();
        act_as(&owner.keys);
        let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
        assert_eq!(writing::mint_for_test(&bed.relay, &held(), &general, &roster).await, Err(writing::LEDGER_MOVED_FOR_TEST.to_string()));
    }

    #[tokio::test]
    async fn a_manager_who_left_posts_nothing_that_stands_whatever_role_lingers() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, member, community, general) = restricted_bed(false).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        bed.swap_to(&owner);
        let w = Keys::generate();
        let plain = create_role_v2(&bed.relay, &held(), "Plain", 0, 0).await.unwrap();
        set_member_roles(&bed.relay, &held(), &w.public_key(), vec![plain.clone()]).await.unwrap();
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
        let live = held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0;
        // Promoted, then gone before anyone handed them the certifier.
        let mods = create_role_v2(&bed.relay, &held(), "Mods", 0, Permissions::MANAGE_CHANNELS).await.unwrap();
        set_member_roles(&bed.relay, &held(), &w.public_key(), vec![plain, mods]).await.unwrap();
        let gb = crate::community::v2::derive::guestbook_group_key(&held().community_root, community.id(), held().root_epoch);
        let leave = guestbook::build_leave_rumor(w.public_key(), now_ms());
        let (wrap, _) = guestbook::seal_guestbook_rumor(&leave, &gb, &w, Timestamp::from_secs(now_ms() / 1000)).unwrap();
        bed.relay.publish(&wrap, &held().relays).await.unwrap();
        let (_, _, writer) = writing::live_writer(&held(), held().channel(&general).unwrap()).unwrap();
        let read = channel_group_key(&community.community_root, &general, community.root_epoch);
        let cert = cert_for(&held(), &general, live, &w.public_key());
        let signed = GroupKey::from_parts(writer.keys().clone(), read.conv_key().clone());
        post_certified(&bed.relay, &held(), &w, &general, &signed, community.root_epoch, Some((live, Some(cert))), "after leaving", now_ms() + 2_000).await;
        bed.swap_to(&member);
        follow_control(&bed.relay, &held()).await.unwrap();
        sync_guestbook(&bed.relay, &held()).await.unwrap();
        assert!(!channel_texts(&bed.relay, &held(), &general).await.contains(&"after leaving".to_string()), "one who left is no manager, whatever a Role still says");
    }

    #[tokio::test]
    async fn a_mint_reads_the_memberlist_whole_before_it_leaves_anyone_out() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, _member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Unread", bed.relays.clone(), None).await.unwrap();
        activate_roles_v2(&bed.relay, &community, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let general = held().channels[0].id;
        // A writer by their own overwrite, whose Join only the relays hold so far.
        let w = Keys::generate();
        let gb = crate::community::v2::derive::guestbook_group_key(&held().community_root, community.id(), held().root_epoch);
        let join = guestbook::build_join_rumor(w.public_key(), None, now_ms());
        let (wrap, _) = guestbook::seal_guestbook_rumor(&join, &gb, &w, Timestamp::from_secs(now_ms() / 1000)).unwrap();
        bed.relay.publish(&wrap, &held().relays).await.unwrap();
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
        let live = held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0;
        let scope = crate::community::v2::writers::writer_rekey_scope(&general);
        let plane = fetch_plane_deliveries(&bed.relay, &held(), &general, scope).await.unwrap();
        assert!(served_at(&plane, &w.public_key(), scope, live, &|_| true), "the mint read the Guestbook whole first");
    }

    #[tokio::test]
    async fn letting_back_a_writer_the_whole_mint_left_out_takes_a_fresh_epoch() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, _member, community, general) = restricted_bed(false).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        bed.swap_to(&owner);
        let role = create_role_v2(&bed.relay, &held(), "Writers", 0, 0).await.unwrap();
        let writers: Vec<Keys> = (0..4).map(|_| Keys::generate()).collect();
        for w in &writers {
            set_member_roles(&bed.relay, &held(), &w.public_key(), vec![role.clone()]).await.unwrap();
        }
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Role(role), Permissions::SEND_MESSAGES, 0).await.unwrap();
        for w in &writers[..2] {
            publish_overwrite_raw(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), 0, Permissions::SEND_MESSAGES).await;
        }
        let before = crate::db::community::get_community_roles(&cid_hex).unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        let after = crate::db::community::get_community_roles(&cid_hex).unwrap();
        writing::settle_for_test(&bed.relay, &held(), &before, &after).await.unwrap();
        let minted = held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0;
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(writers[0].public_key().to_hex()), 0, 0).await.unwrap();
        let now = held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0;
        assert!(now > minted, "the change itself mints them back in");
        let scope = crate::community::v2::writers::writer_rekey_scope(&general);
        let plane = fetch_plane_deliveries(&bed.relay, &held(), &general, scope).await.unwrap();
        assert!(!served_at(&plane, &writers[0].public_key(), scope, minted, &|_| true), "never handed the epoch that left them out");
        assert!(served_at(&plane, &writers[0].public_key(), scope, now, &|_| true));
    }

    #[tokio::test]
    async fn a_refounding_starts_the_memberlist_read_again() {
        let (bed, owner, _member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Read again", bed.relays.clone(), None).await.unwrap();
        while !guestbook_walked_this_session(&community) {
            sync_guestbook(&bed.relay, &community).await.unwrap();
        }
        let gb = crate::community::v2::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
        let mut moved = community.clone();
        moved.root_epoch = Epoch(community.root_epoch.0 + 1);
        assert_ne!(crate::community::v2::derive::guestbook_group_key(&moved.community_root, moved.id(), moved.root_epoch).pk(), gb.pk());
        assert!(!guestbook_walked_this_session(&moved), "a new plane is read whole again");
    }

    #[tokio::test]
    async fn an_edit_at_a_writer_address_is_no_sign_of_presence() {
        let (bed, owner, member, community, general) = restricted_bed(false).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let read = channel_group_key(&community.community_root, &general, community.root_epoch);
        let chan_hex = crate::simd::hex::bytes_to_hex_32(&general.0);
        bed.swap_to(&owner);
        let (e1, _, writer1) = writing::live_writer(&held(), held().channel(&general).unwrap()).unwrap();
        let at1 = GroupKey::from_parts(writer1.keys().clone(), read.conv_key().clone());
        // A key handed to someone who never joined.
        let w = Keys::generate();
        let post = chat::with_writer_epoch(chat::build_message_rumor(w.public_key(), &general, community.root_epoch, "at the writer address", None, &[], vec![], now_ms()), e1);
        let target = post.id.unwrap().to_hex();
        let edit = chat::with_writer_epoch(chat::build_edit_rumor(w.public_key(), &general, community.root_epoch, &target, "edited there", &[], None, now_ms() + 1_000), e1);
        bed.swap_to(&member);
        for rumor in [&post, &edit] {
            let (wrap, _) = chat::seal_chat_rumor(rumor, &at1, &w, Timestamp::from_secs(now_ms() / 1000), false).unwrap();
            let opened = chat::open_writer_chat_event(&wrap, &wrap.pubkey, e1, read.conv_key(), &general, community.root_epoch).unwrap();
            crate::community::v2::inbound::persist_routed_chat_event(&opened, &chan_hex, &community.id().0, &member.keys.public_key()).await.expect("stored");
        }
        assert_eq!(crate::db::events::get_message_by_id(&target).await.unwrap().unwrap().1.content, "edited there");
        assert!(!stored_memberlist_strict(&held()).unwrap().contains(&w.public_key()), "neither the post nor its edit there is a sign of presence");
    }

    #[tokio::test]
    async fn a_managers_copy_of_a_post_dated_past_the_hour_goes_rather_than_waits_flagged() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, member, community, general) = restricted_bed(true).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let read = channel_group_key(&community.community_root, &general, community.root_epoch);
        let chan_hex = crate::simd::hex::bytes_to_hex_32(&general.0);
        bed.swap_to(&owner);
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, 0).await.unwrap();
        bed.swap_to(&member);
        follow_control(&bed.relay, &held()).await.unwrap();
        let p = Keys::generate();
        post_raw(&bed.relay, &held(), &p, &general, &read, community.root_epoch, None, "far", now_ms() + 2 * 60 * 60_000).await;
        // Shown once its time came, read here as a device whose clock has reached it.
        crate::clock::shift_for_test(3 * 60 * 60_000);
        let page = fetch_channel_history(&bed.relay, &held(), &general, 50, 2, None, None, crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await.unwrap();
        let far = page.iter().find(|f| f.event.opened().rumor.content == "far").unwrap();
        crate::community::v2::inbound::persist_routed_chat_event(&far.event, &chan_hex, &community.id().0, &member.keys.public_key()).await.expect("stood while open");
        crate::clock::shift_for_test(0);
        let id = far.event.opened().rumor_id.to_hex();
        bed.swap_to(&owner);
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
        bed.swap_to(&member);
        follow_control(&bed.relay, &held()).await.unwrap();
        let ledger = held().channel(&general).unwrap().writers.clone().unwrap();
        writing::retract_since(&bed.relay, &held(), held().channel(&general).unwrap(), ledger.entries.last().unwrap().at, &Shown::default()).await.unwrap();
        assert!(crate::db::events::get_message_by_id(&id).await.unwrap().is_none(), "no flag without a held wrap: the relays keep it until its date nears");
    }

    #[tokio::test]
    async fn a_post_at_an_address_the_ledger_names_nowhere_is_taken_back() {
        let (bed, _owner, member, community, general) = restricted_bed(false).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let chan_hex = crate::simd::hex::bytes_to_hex_32(&general.0);
        bed.swap_to(&member);
        let elsewhere = channel_group_key(&[9u8; 32], &general, community.root_epoch);
        let at = now_ms();
        let mut ids = Vec::new();
        // One that came to a writer address the ledger no longer names, one this device has no key for.
        for (i, writer) in [(0u8, true), (1, false)] {
            let author = Keys::generate();
            let rumor = chat::build_message_rumor(author.public_key(), &general, community.root_epoch, "sealed elsewhere", None, &[], vec![], at + i as u64);
            let (wrap, _) = chat::seal_chat_rumor(&rumor, &elsewhere, &author, Timestamp::from_secs(at / 1000), false).unwrap();
            bed.relay.publish(&wrap, &held().relays).await.unwrap();
            let msg = crate::types::Message {
                id: format!("{i:x}").repeat(64),
                content: "unreadable here".into(),
                at: at + i as u64,
                npub: Some(nostr_sdk::prelude::ToBech32::to_bech32(&author.public_key()).unwrap()),
                wrapper_event_id: Some(wrap.id.to_hex()),
                writer,
                ..Default::default()
            };
            crate::db::events::save_message(&chan_hex, &msg).await.unwrap();
            ids.push(msg.id);
        }
        writing::retract_since(&bed.relay, &held(), held().channel(&general).unwrap(), at - 1_000, &Shown::default()).await.unwrap();
        assert!(crate::db::events::get_message_by_id(&ids[0]).await.unwrap().is_none(), "a writer-address post the ledger names nowhere stands nowhere");
        assert!(crate::db::events::get_message_by_id(&ids[1]).await.unwrap().is_some(), "one without its key stays");
    }

    #[tokio::test]
    async fn a_retraction_whose_reads_fail_leaves_the_rest_owed() {
        let (bed, _owner, member, community, general) = restricted_bed(false).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let chan_hex = crate::simd::hex::bytes_to_hex_32(&general.0);
        bed.swap_to(&member);
        let msg = crate::types::Message { id: "e".repeat(64), content: "owed".into(), at: now_ms(), npub: Some(nostr_sdk::prelude::ToBech32::to_bech32(&Keys::generate().public_key()).unwrap()), wrapper_event_id: Some("d".repeat(64)), ..Default::default() };
        crate::db::events::save_message(&chan_hex, &msg).await.unwrap();
        let down = FetchErrors(MemoryRelay::new());
        assert!(writing::retract_since(&down, &held(), held().channel(&general).unwrap(), msg.at - 1, &Shown::default()).await.is_err(), "a read that failed is no answer");
        assert_eq!(writing::retract_since(&NoIds(&bed.relay), &held(), held().channel(&general).unwrap(), msg.at - 1, &Shown::default()).await, Ok(0), "answered without it: done");
    }

    #[tokio::test]
    async fn a_banned_managers_edition_never_holds_a_mint_back() {
        use crate::community::roles::OverwriteTarget;
        use crate::community::v2::writers::Spell;
        let (bed, owner, x, community) = v2_bed_with_admin("Banned").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let general = held().channels[0].id;
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
        // Banned, with the Grant still standing.
        set_banlist(&bed.relay, &held(), &[x.public_key().to_hex()]).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let eid = crate::community::v2::derive::writers_locator(community.id(), &general);
        let (v, head) = crate::db::community::get_edition_head(&cid_hex, &crate::simd::hex::bytes_to_hex_32(&eid)).unwrap().unwrap();
        let theirs = held().channel(&general).unwrap().writers.clone().unwrap().appended(now_ms(), Spell::Open).unwrap();
        let cite = cite_on_relay(&bed.relay, &held(), &x).await;
        let rumor = control::build_edition_rumor_bound(x.public_key(), vsk::WRITERS, &eid, v + 1, Some(&head), &theirs.to_json(), now_ms() / 1000, cite.as_ref(), Some(crate::community::v2::derive::edition_binding(community.id())));
        let group = control::ControlPlane::of(&held()).write_group().unwrap();
        let (wrap, _) = control::seal_control_edition(&rumor, &group, &x, Timestamp::from_secs(now_ms() / 1000)).unwrap();
        bed.relay.publish(&wrap, &held().relays).await.unwrap();
        act_as(&owner.keys);
        let before = held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0;
        let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
        writing::mint_for_test(&bed.relay, &held(), &general, &roster).await.unwrap();
        assert!(held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0 > before, "an edition every reader refuses moves nothing");
    }

    /// Answers each read after a pause, as a slow relay does.
    struct Paused<'a>(&'a MemoryRelay);
    #[async_trait::async_trait]
    impl Transport for Paused<'_> {
        async fn fetch_plane(&self, plane: &Keys, query: &Query, relays: &[String]) -> Result<crate::community::transport::PlaneFetch, String> {
            crate::rt::time::sleep(std::time::Duration::from_millis(50)).await;
            self.0.fetch_plane(plane, query, relays).await
        }
        async fn publish(&self, e: &Event, r: &[String]) -> Result<(), String> {
            self.0.publish(e, r).await
        }
        async fn publish_durable(&self, e: &Event, r: &[String]) -> Result<(), String> {
            self.0.publish_durable(e, r).await
        }
        async fn fetch(&self, q: &Query, r: &[String]) -> Result<Vec<Event>, String> {
            crate::rt::time::sleep(std::time::Duration::from_millis(50)).await;
            self.0.fetch(q, r).await
        }
    }

    #[tokio::test]
    async fn two_guestbook_reads_at_once_both_keep_what_they_found() {
        let (bed, owner, _member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Two reads", bed.relays.clone(), None).await.unwrap();
        let gb = crate::community::v2::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
        // Each relay holds a Join the other doesn't.
        let other = MemoryRelay::new();
        let (a, b) = (Keys::generate(), Keys::generate());
        for (relay, k) in [(&bed.relay, &a), (&other, &b)] {
            let join = guestbook::build_join_rumor(k.public_key(), None, now_ms());
            let (wrap, _) = guestbook::seal_guestbook_rumor(&join, &gb, k, Timestamp::from_secs(now_ms() / 1000)).unwrap();
            relay.publish(&wrap, &community.relays).await.unwrap();
        }
        let (first, second) = (Paused(&bed.relay), Paused(&other));
        let (one, two) = tokio::join!(sync_guestbook(&first, &community), sync_guestbook(&second, &community));
        one.unwrap();
        two.unwrap();
        let (events, _) = crate::db::community::get_guestbook(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap();
        let joined = |k: &Keys| events.iter().any(|e| matches!(e.entry, guestbook::GuestbookEntry::Join { member, .. } if member == k.public_key()));
        assert!(joined(&a) && joined(&b), "neither write drops what the other stored");
    }

    #[tokio::test]
    async fn a_manager_whose_grant_sits_past_a_page_still_moves_the_ledger() {
        use crate::community::roles::OverwriteTarget;
        use crate::community::v2::writers::Spell;
        let (bed, owner, x, community) = v2_bed_with_admin("Buried").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let general = held().channels[0].id;
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
        let cite = cite_on_relay(&bed.relay, &held(), &x).await;
        // A page's worth of editions nobody folds, newer than the admin's Grant, a second apart (a
        // flood inside one second is a wall no read steps past, and reads as short).
        let group = control::ControlPlane::of(&held()).write_group().unwrap();
        let binding = Some(crate::community::v2::derive::edition_binding(community.id()));
        let base = now_ms() / 1000;
        for i in 0..600u32 {
            let mut eid = [0u8; 32];
            eid[..4].copy_from_slice(&i.to_be_bytes());
            let at = base + 1 + i as u64;
            let rumor = control::build_edition_rumor_bound(owner.keys.public_key(), "99", &eid, 1, None, "{}", at, None, binding);
            let (wrap, _) = control::seal_control_edition(&rumor, &group, &owner.keys, Timestamp::from_secs(at)).unwrap();
            bed.relay.publish(&wrap, &held().relays).await.unwrap();
        }
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let eid = crate::community::v2::derive::writers_locator(community.id(), &general);
        let (v, head) = crate::db::community::get_edition_head(&cid_hex, &crate::simd::hex::bytes_to_hex_32(&eid)).unwrap().unwrap();
        let theirs = held().channel(&general).unwrap().writers.clone().unwrap().appended(now_ms(), Spell::Open).unwrap();
        let rumor = control::build_edition_rumor_bound(x.public_key(), vsk::WRITERS, &eid, v + 1, Some(&head), &theirs.to_json(), now_ms() / 1000, cite.as_ref(), binding);
        let (wrap, _) = control::seal_control_edition(&rumor, &group, &x, Timestamp::from_secs(now_ms() / 1000)).unwrap();
        bed.relay.publish(&wrap, &held().relays).await.unwrap();
        act_as(&owner.keys);
        let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
        assert_eq!(writing::mint_for_test(&bed.relay, &held(), &general, &roster).await, Err(writing::LEDGER_MOVED_FOR_TEST.to_string()), "read as deep as a follow, the admin's edition is seen");
    }

    #[test]
    fn a_fork_switch_owes_from_what_it_dropped() {
        use crate::community::v2::writers::{Ledger, Spell};
        let ch = ChannelId([4; 32]);
        let w = Keys::generate().public_key().to_bytes();
        let writer = Spell::Writer { epoch: Epoch(1), pk: crate::community::v2::writers::writer_address(&[1; 32], &ch, Epoch(1)), root: Epoch(0), by: w, certifier: None };
        let base = Ledger::new(&ch).appended(1_000, writer).unwrap();
        let losing = base.appended(2_000, Spell::Open).unwrap();
        let winning = base.appended(2_500, Spell::Stop { writer: w }).unwrap();
        assert_eq!(crate::db::community::retraction_since(Some(&losing.to_json()), &winning.to_json()), Some(2_000), "the open the switch dropped admitted posts from 2_000");
        assert_eq!(crate::db::community::retraction_since(Some(&base.to_json()), &winning.to_json()), None, "a stop is its writer's alone");
        assert_eq!(crate::db::community::stop_owes(Some(&base.to_json()), &winning.to_json()), vec![(w, 2_500)]);
        assert_eq!(crate::db::community::retraction_since(Some(&base.to_json()), &losing.to_json()), None, "an open added takes nothing back");
        let dated = base.appended_from(3_000, Spell::Stop { writer: w }, Some(1_500)).unwrap();
        assert_eq!(crate::db::community::stop_owes(Some(&base.to_json()), &dated.to_json()), vec![(w, 1_500)], "a stop that records a departure owes from it");
    }

    #[tokio::test]
    async fn a_leave_arriving_live_owes_only_that_members_posts() {
        let (_bed, _owner, _member, community, general) = restricted_bed(false).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let (cid_hex, chan_hex) = (crate::simd::hex::bytes_to_hex_32(&community.id().0), crate::simd::hex::bytes_to_hex_32(&general.0));
        let (w, stranger) = (Keys::generate(), Keys::generate());
        let at = now_ms();
        let event = |id: u8, entry| guestbook::GuestbookEvent { rumor_id: [id; 32], entry, epoch: Some(held().root_epoch.0), observed_at: None };
        ingest_guestbook_event(&held(), event(1, guestbook::GuestbookEntry::Join { member: w.public_key(), invited_by: None, at_ms: at - 5_000 }), at / 1000 - 5).unwrap();
        let shown = crate::types::Message { id: "a".repeat(64), content: "since".into(), at: at + 1_000, npub: Some(nostr_sdk::prelude::ToBech32::to_bech32(&w.public_key()).unwrap()), wrapper_event_id: Some("b".repeat(64)), writer: true, ..Default::default() };
        crate::db::events::save_message(&chan_hex, &shown).await.unwrap();
        clear_owed(&cid_hex);
        // A Leave from a key that never posted, dated as early as it likes, owes nothing.
        ingest_guestbook_event(&held(), event(2, guestbook::GuestbookEntry::Leave { member: stranger.public_key(), at_ms: 1 }), at / 1000).unwrap();
        assert!(crate::db::community::owed_author_retractions(&cid_hex).unwrap().is_empty());
        ingest_guestbook_event(&held(), event(3, guestbook::GuestbookEntry::Leave { member: w.public_key(), at_ms: at }), at / 1000).unwrap();
        assert_eq!(crate::db::community::owed_author_retractions(&cid_hex).unwrap().iter().map(|(c, a, s, ..)| (c.clone(), a.clone(), *s)).collect::<Vec<_>>(), vec![(chan_hex, w.public_key().to_hex(), at)]);
        assert!(crate::db::community::owed_retractions(&cid_hex).unwrap().is_empty(), "nobody else's posts are read again");
        clear_owed(&cid_hex);
        owe_new_departures(&held());
        assert!(crate::db::community::owed_author_retractions(&cid_hex).unwrap().is_empty(), "a departure is owed once");
    }

    #[tokio::test]
    async fn a_kick_holds_its_date_whatever_leave_follows_and_a_join_ends_it() {
        let (_bed, _owner, _member, community, _general) = restricted_bed(false).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let owner_pk = community.owner().unwrap();
        let w = Keys::generate();
        let at = now_ms();
        let event = |id: u8, entry| guestbook::GuestbookEvent { rumor_id: [id; 32], entry, epoch: Some(held().root_epoch.0), observed_at: None };
        ingest_guestbook_event(&held(), event(1, guestbook::GuestbookEntry::Join { member: w.public_key(), invited_by: None, at_ms: at - 60_000 }), at / 1000 - 60).unwrap();
        ingest_guestbook_event(&held(), event(2, guestbook::GuestbookEntry::Kick { actor: owner_pk, target: w.public_key(), citation: None, at_ms: at - 50_000 }), at / 1000 - 50).unwrap();
        // Their own Leave dated later never moves the Kick.
        ingest_guestbook_event(&held(), event(3, guestbook::GuestbookEntry::Leave { member: w.public_key(), at_ms: at + 50 * 60_000 }), at / 1000).unwrap();
        let away = stored_departure_windows(&held());
        assert_eq!(away.get(&w.public_key()).map(|s| s.to_vec()), Some(vec![(at - 50_000, None, true)]));
        ingest_guestbook_event(&held(), event(4, guestbook::GuestbookEntry::Join { member: w.public_key(), invited_by: None, at_ms: at - 10_000 }), at / 1000 - 10).unwrap();
        let away = stored_departure_windows(&held());
        assert_eq!(away.get(&w.public_key()).map(|w| w[0]), Some((at - 50_000, Some(at - 10_000), true)), "a Join ends the span, it doesn't erase it");
    }

    #[tokio::test]
    async fn a_kick_that_stands_only_once_its_kicker_is_read_is_owed_then() {
        let (bed, owner, _member, community, general) = restricted_bed(false).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let (cid_hex, chan_hex) = (crate::simd::hex::bytes_to_hex_32(&community.id().0), crate::simd::hex::bytes_to_hex_32(&general.0));
        bed.swap_to(&owner);
        let (m, w) = (Keys::generate(), Keys::generate());
        let at = now_ms();
        let event = |id: u8, entry| guestbook::GuestbookEvent { rumor_id: [id; 32], entry, epoch: Some(held().root_epoch.0), observed_at: None };
        ingest_guestbook_event(&held(), event(1, guestbook::GuestbookEntry::Join { member: w.public_key(), invited_by: None, at_ms: at - 60_000 }), at / 1000 - 60).unwrap();
        let shown = crate::types::Message { id: "a".repeat(64), content: "since".into(), at: at + 1_000, npub: Some(nostr_sdk::prelude::ToBech32::to_bech32(&w.public_key()).unwrap()), wrapper_event_id: Some("b".repeat(64)), writer: true, ..Default::default() };
        crate::db::events::save_message(&chan_hex, &shown).await.unwrap();
        // A Kick from one who may kick only once a Role edit this device hasn't read lands.
        let mods = create_role_v2(&bed.relay, &held(), "Mods", 0, 0).await.unwrap();
        set_member_roles(&bed.relay, &held(), &m.public_key(), vec![mods.clone()]).await.unwrap();
        let citation = required_authority_citation(&held(), &m.public_key()).unwrap();
        ingest_guestbook_event(&held(), event(2, guestbook::GuestbookEntry::Kick { actor: m.public_key(), target: w.public_key(), citation, at_ms: at }), at / 1000).unwrap();
        clear_owed(&cid_hex);
        assert!(crate::db::community::owed_author_retractions(&cid_hex).unwrap().is_empty());
        edit_role_v2(&bed.relay, &held(), &mods, "Mods", 0, Permissions::KICK, false, false).await.unwrap();
        owe_new_departures(&held());
        assert_eq!(crate::db::community::owed_author_retractions(&cid_hex).unwrap().iter().map(|(c, a, s, ..)| (c.clone(), a.clone(), *s)).collect::<Vec<_>>(), vec![(chan_hex, w.public_key().to_hex(), at)], "the follow that reads the kicker owes it");
    }

    #[tokio::test]
    async fn a_refounding_stops_its_kicked_writers_from_when_they_were_kicked() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, _member, community, general) = restricted_bed(false).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        bed.swap_to(&owner);
        let w = Keys::generate();
        set_member_roles(&bed.relay, &held(), &w.public_key(), vec![create_role_v2(&bed.relay, &held(), "Plain", 0, 0).await.unwrap()]).await.unwrap();
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
        let live = held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0;
        let gb = crate::community::v2::derive::guestbook_group_key(&held().community_root, community.id(), held().root_epoch);
        let left_at = now_ms();
        let kick = guestbook::build_kick_rumor(owner.keys.public_key(), w.public_key(), None, left_at);
        let (wrap, _) = guestbook::seal_guestbook_rumor(&kick, &gb, &owner.keys, Timestamp::from_secs(left_at / 1000)).unwrap();
        bed.relay.publish(&wrap, &held().relays).await.unwrap();
        sync_guestbook(&bed.relay, &held()).await.unwrap();
        // They post on after leaving; this device holds what it can't stand behind.
        let read = channel_group_key(&community.community_root, &general, community.root_epoch);
        let (_, _, writer) = writing::live_writer(&held(), held().channel(&general).unwrap()).unwrap();
        let cert = cert_for(&held(), &general, live, &w.public_key());
        let signed = GroupKey::from_parts(writer.keys().clone(), read.conv_key().clone());
        post_certified(&bed.relay, &held(), &w, &general, &signed, community.root_epoch, Some((live, Some(cert))), "after leaving", left_at + 500).await;
        channel_texts(&bed.relay, &held(), &general).await;
        assert!(crate::db::community::holds_wraps_at(&crate::simd::hex::bytes_to_hex_32(&community.id().0), &crate::simd::hex::bytes_to_hex_32(&general.0), &w.public_key().to_hex(), &writer.pk().to_bytes()));
        crate::rt::time::sleep(std::time::Duration::from_millis(1_100)).await;
        refound_community(&bed.relay, &held(), &[]).await.unwrap();
        let ledger = held().channel(&general).unwrap().writers.clone().unwrap();
        assert!(ledger.current_writer().unwrap().0 > live, "the Refounding re-minted");
        assert!(ledger.stopped(live, &w.public_key().to_bytes(), left_at), "a reader who never reads the old Guestbook still sees them stopped from when they left");
        assert!(!ledger.stopped(live, &w.public_key().to_bytes(), left_at - 1));
    }

    #[tokio::test]
    async fn a_page_stored_after_a_departure_owes_that_members_posts() {
        let (_bed, _owner, _member, community, general) = restricted_bed(false).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let (cid_hex, chan_hex) = (crate::simd::hex::bytes_to_hex_32(&community.id().0), crate::simd::hex::bytes_to_hex_32(&general.0));
        let (w, stayer) = (Keys::generate(), Keys::generate());
        let at = now_ms();
        let event = |id: u8, entry| guestbook::GuestbookEvent { rumor_id: [id; 32], entry, epoch: Some(held().root_epoch.0), observed_at: None };
        ingest_guestbook_event(&held(), event(1, guestbook::GuestbookEntry::Join { member: w.public_key(), invited_by: None, at_ms: at - 5_000 }), at / 1000 - 5).unwrap();
        ingest_guestbook_event(&held(), event(2, guestbook::GuestbookEntry::Leave { member: w.public_key(), at_ms: at }), at / 1000).unwrap();
        clear_owed(&cid_hex);
        writing::owe_if_departed(&chan_hex, &[(w.public_key(), at - 1_000), (stayer.public_key(), at + 1_000)]);
        assert!(crate::db::community::owed_author_retractions(&cid_hex).unwrap().is_empty(), "posted while here, or by one who stayed");
        writing::owe_if_departed(&chan_hex, &[(w.public_key(), at + 1_000)]);
        assert_eq!(crate::db::community::owed_author_retractions(&cid_hex).unwrap().iter().map(|(c, a, s, ..)| (c.clone(), a.clone(), *s)).collect::<Vec<_>>(), vec![(chan_hex, w.public_key().to_hex(), at + 1_000)]);
    }

    #[tokio::test]
    async fn departure_spans_are_folded_once_per_change() {
        let (_bed, _owner, _member, community, _general) = restricted_bed(false).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let first = stored_departure_windows(&held());
        assert!(std::sync::Arc::ptr_eq(&first, &stored_departure_windows(&held())), "judging a post folds nothing again");
        let w = Keys::generate();
        let leave = guestbook::GuestbookEvent { rumor_id: [7; 32], entry: guestbook::GuestbookEntry::Leave { member: w.public_key(), at_ms: now_ms() }, epoch: Some(held().root_epoch.0), observed_at: None };
        ingest_guestbook_event(&held(), leave, now_ms() / 1000).unwrap();
        assert!(stored_departure_windows(&held()).contains_key(&w.public_key()), "a Guestbook write refolds");
    }

    #[tokio::test]
    async fn a_guestbook_entry_that_moves_no_departure_keeps_the_folded_spans() {
        let (_bed, _owner, _member, community, _general) = restricted_bed(false).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let at = now_ms();
        let event = |id: u8, entry| guestbook::GuestbookEvent { rumor_id: [id; 32], entry, epoch: Some(held().root_epoch.0), observed_at: None };
        let (gone, stayer, fresh) = (Keys::generate().public_key(), Keys::generate().public_key(), Keys::generate().public_key());
        ingest_guestbook_event(&held(), event(1, guestbook::GuestbookEntry::Join { member: gone, invited_by: None, at_ms: at - 10_000 }), at / 1000).unwrap();
        ingest_guestbook_event(&held(), event(2, guestbook::GuestbookEntry::Leave { member: gone, at_ms: at - 5_000 }), at / 1000).unwrap();
        ingest_guestbook_event(&held(), event(3, guestbook::GuestbookEntry::Join { member: stayer, invited_by: None, at_ms: at - 4_000 }), at / 1000).unwrap();
        let folded = stored_departure_windows(&held());
        ingest_guestbook_event(&held(), event(4, guestbook::GuestbookEntry::Join { member: fresh, invited_by: None, at_ms: at - 3_000 }), at / 1000).unwrap();
        let carried = stored_departure_windows(&held());
        assert!(std::sync::Arc::ptr_eq(&folded, &carried), "a newcomer's Join opens or closes nothing");
        departure_cache().lock().unwrap().clear();
        assert_eq!(*carried, *stored_departure_windows(&held()), "what was carried is what a fold from scratch finds");
        ingest_guestbook_event(&held(), event(5, guestbook::GuestbookEntry::Join { member: gone, invited_by: None, at_ms: at - 1_000 }), at / 1000).unwrap();
        let back = stored_departure_windows(&held());
        assert_eq!(back.get(&gone).map(|s| s.to_vec()), Some(vec![(at - 5_000, Some(at - 1_000), false)]), "a departed member's Join closes their span");
        departure_cache().lock().unwrap().clear();
        assert_eq!(*back, *stored_departure_windows(&held()));
    }

    #[tokio::test]
    async fn folded_spans_are_not_carried_over_a_write_they_did_not_judge() {
        let (_bed, _owner, _member, community, _general) = restricted_bed(false).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let at = now_ms();
        let join = guestbook::GuestbookEvent { rumor_id: [9; 32], entry: guestbook::GuestbookEntry::Join { member: Keys::generate().public_key(), invited_by: None, at_ms: at }, epoch: Some(held().root_epoch.0), observed_at: None };
        let folded = stored_departure_windows(&held());
        let after = departures_after(&cid_hex, [&join.entry]);
        assert!(matches!(&after, DeparturesAfter::Members(_, moved) if moved.is_empty()), "a newcomer's Join moves nothing");
        crate::db::community::bump_membership_generation();
        crate::db::community::store_guestbook_events(&cid_hex, std::slice::from_ref(&join), at / 1000).unwrap();
        departures_stored(&held(), &cid_hex, after, [at]);
        assert!(!std::sync::Arc::ptr_eq(&folded, &stored_departure_windows(&held())), "a write landing in between is folded");
        // Nor windows some slower fold put back, read before the generation the Join was judged at.
        let join = guestbook::GuestbookEvent { rumor_id: [10; 32], ..join };
        let DeparturesAfter::Members(judged, _) = departures_after(&cid_hex, [&join.entry]) else { panic!("a newcomer's Join moves nothing") };
        let stale = std::sync::Arc::new(DepartureSpans::from([(Keys::generate().public_key(), vec![(1, None, false)].into())]));
        departure_cache().lock().unwrap().insert(cid_hex.clone(), HeldDepartures { generation: judged - 1, spans: stale.clone(), due: None });
        crate::db::community::store_guestbook_events(&cid_hex, std::slice::from_ref(&join), at / 1000).unwrap();
        departures_stored(&held(), &cid_hex, DeparturesAfter::Members(judged, Vec::new()), [at]);
        assert!(!std::sync::Arc::ptr_eq(&stale, &stored_departure_windows(&held())));
    }

    #[tokio::test]
    async fn departure_windows_kept_across_writes_match_a_fold_from_scratch() {
        let (_bed, owner, _member, community, _general) = restricted_bed(false).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let pool: Vec<PublicKey> = (0..5).map(|_| Keys::generate().public_key()).collect();
        let stranger = Keys::generate().public_key();
        let base = now_ms() - 100_000;
        let mut seed = 0x2545_f491_4f6c_dd1du64;
        let mut next = move |n: u64| {
            seed ^= seed << 13;
            seed ^= seed >> 7;
            seed ^= seed << 17;
            seed % n
        };
        let mut event = |i: u32| {
            let member = pool[next(5) as usize];
            // Few distinct times, so ties are common; some too far ahead to count yet.
            let at_ms = if next(12) == 0 { now_ms() + guestbook::MAX_FUTURE_MS + 60_000 + next(1_000) } else { base + next(40) * 1_000 };
            let entry = match next(6) {
                0 | 1 => guestbook::GuestbookEntry::Join { member, invited_by: None, at_ms },
                2 => guestbook::GuestbookEntry::Leave { member, at_ms },
                3 => guestbook::GuestbookEntry::Kick { actor: owner.keys.public_key(), target: member, citation: None, at_ms },
                4 => guestbook::GuestbookEntry::Kick { actor: stranger, target: member, citation: None, at_ms },
                _ => guestbook::GuestbookEntry::Nickname { actor: member, target: member, nick: "n".into(), citation: None, at_ms },
            };
            let mut rumor_id = [next(256) as u8; 32];
            rumor_id[..4].copy_from_slice(&i.to_le_bytes());
            (guestbook::GuestbookEvent { rumor_id, entry, epoch: Some(held().root_epoch.0), observed_at: None }, next(12) as u32 + 1)
        };
        for i in 0..300u32 {
            ingest_guestbook_event(&held(), event(i).0, now_ms() / 1000).unwrap();
            let c = held();
            assert_eq!(*stored_departure_windows(&c), fold_departure_windows(&c, &cid_hex).0, "after write {i}");
        }
        // A walk stores a batch at once.
        let mut i = 300u32;
        for round in 0..60 {
            let size = event(0).1;
            let batch: Vec<_> = (0..size).map(|_| { i += 1; event(i).0 }).collect();
            store_guestbook_and_departures(&held(), &cid_hex, &batch, now_ms() / 1000).unwrap();
            let c = held();
            assert_eq!(*stored_departure_windows(&c), fold_departure_windows(&c, &cid_hex).0, "after batch {round}");
        }
        assert!(stored_departure_windows(&held()).values().any(|w| w.iter().any(|s| s.2)), "an honoured Kick was folded");
    }

    #[tokio::test]
    async fn an_entry_too_far_ahead_brought_over_is_due_later() {
        let (_bed, _owner, _member, community, _general) = restricted_bed(false).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let event = |id: u8, entry| guestbook::GuestbookEvent { rumor_id: [id; 32], entry, epoch: Some(held().root_epoch.0), observed_at: None };
        let folded = stored_departure_windows(&held());
        assert_eq!(departure_cache().lock().unwrap()[&cid_hex].due, None);
        let ahead = now_ms() + guestbook::MAX_FUTURE_MS + 60_000;
        ingest_guestbook_event(&held(), event(1, guestbook::GuestbookEntry::Join { member: Keys::generate().public_key(), invited_by: None, at_ms: ahead }), now_ms() / 1000).unwrap();
        assert!(std::sync::Arc::ptr_eq(&folded, &stored_departure_windows(&held())));
        assert_eq!(departure_cache().lock().unwrap()[&cid_hex].due, Some(ahead), "folded again once it is due");
        let sooner = ahead - 1_000;
        let batch = [event(2, guestbook::GuestbookEntry::Join { member: Keys::generate().public_key(), invited_by: None, at_ms: now_ms() }), event(3, guestbook::GuestbookEntry::Join { member: Keys::generate().public_key(), invited_by: None, at_ms: sooner })];
        store_guestbook_and_departures(&held(), &cid_hex, &batch, now_ms() / 1000).unwrap();
        assert_eq!(departure_cache().lock().unwrap()[&cid_hex].due, Some(sooner), "whichever entry of a batch comes due first");
    }

    #[tokio::test]
    async fn the_owed_record_lets_go_of_members_the_windows_no_longer_hold() {
        let (_bed, _owner, _member, community, _general) = restricted_bed(false).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let at = now_ms();
        let w = Keys::generate().public_key();
        let event = |id: u8, entry| guestbook::GuestbookEvent { rumor_id: [id; 32], entry, epoch: Some(held().root_epoch.0), observed_at: None };
        ingest_guestbook_event(&held(), event(1, guestbook::GuestbookEntry::Join { member: w, invited_by: None, at_ms: at - 5_000 }), at / 1000).unwrap();
        ingest_guestbook_event(&held(), event(2, guestbook::GuestbookEntry::Leave { member: w, at_ms: at - 1_000 }), at / 1000).unwrap();
        // Ahead of every member in key order, then behind them all.
        for extra in [[0u8; 32], [0xff; 32]] {
            let mut seen = (*stored_departure_windows(&held())).clone();
            seen.insert(PublicKey::from_byte_array(extra), vec![(1, None, false)].into());
            crate::db::community::set_departures_seen(&cid_hex, std::sync::Arc::new(seen)).unwrap();
            owe_new_departures(&held());
            assert_eq!(*crate::db::community::departures_seen(&cid_hex).unwrap().spans, *stored_departure_windows(&held()));
        }
    }

    #[tokio::test]
    async fn a_nickname_or_timeout_write_folds_no_departure_again() {
        let (bed, owner, member, community, _general) = restricted_bed(false).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        bed.swap_to(&owner);
        let at = now_ms();
        let event = |id: u8, entry| guestbook::GuestbookEvent { rumor_id: [id; 32], entry, epoch: Some(held().root_epoch.0), observed_at: None };
        let gone = Keys::generate().public_key();
        ingest_guestbook_event(&held(), event(1, guestbook::GuestbookEntry::Leave { member: gone, at_ms: at - 1_000 }), at / 1000).unwrap();
        let folded = stored_departure_windows(&held());
        set_nickname(&bed.relay, &held(), &owner.keys.public_key(), "Boss").await.unwrap();
        assert!(std::sync::Arc::ptr_eq(&folded, &stored_departure_windows(&held())), "a Nickname moves nobody's departure");
        timeout_member(&bed.relay, &held(), &member.keys.public_key(), 60).await.unwrap();
        assert!(std::sync::Arc::ptr_eq(&folded, &stored_departure_windows(&held())), "nor does a Timeout");
    }

    #[tokio::test]
    async fn folded_spans_are_never_carried_past_an_entry_coming_due() {
        let (_bed, _owner, _member, community, _general) = restricted_bed(false).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let at = now_ms();
        let event = |id: u8, entry| guestbook::GuestbookEvent { rumor_id: [id; 32], entry, epoch: Some(held().root_epoch.0), observed_at: None };
        let ahead = Keys::generate().public_key();
        ingest_guestbook_event(&held(), event(1, guestbook::GuestbookEntry::Leave { member: ahead, at_ms: at + guestbook::MAX_FUTURE_MS + 60_000 }), at / 1000).unwrap();
        let folded = stored_departure_windows(&held());
        assert!(!folded.contains_key(&ahead), "too far ahead to count yet");
        ingest_guestbook_event(&held(), event(2, guestbook::GuestbookEntry::Join { member: Keys::generate().public_key(), invited_by: None, at_ms: at }), at / 1000).unwrap();
        assert!(std::sync::Arc::ptr_eq(&folded, &stored_departure_windows(&held())));
        departure_cache().lock().unwrap().get_mut(&cid_hex).unwrap().due = Some(at);
        ingest_guestbook_event(&held(), event(3, guestbook::GuestbookEntry::Join { member: Keys::generate().public_key(), invited_by: None, at_ms: at }), at / 1000).unwrap();
        assert!(!std::sync::Arc::ptr_eq(&folded, &stored_departure_windows(&held())), "folded again once what it left out comes due");
    }

    #[tokio::test]
    async fn a_ban_stops_a_writer_and_an_unban_takes_them_back_on_a_fresh_epoch() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, member, community, general) = restricted_bed(false).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let read = channel_group_key(&community.community_root, &general, community.root_epoch);
        bed.swap_to(&owner);
        let w = Keys::generate();
        set_member_roles(&bed.relay, &held(), &w.public_key(), vec![create_role_v2(&bed.relay, &held(), "Plain", 0, 0).await.unwrap()]).await.unwrap();
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
        let (live, _, writer) = writing::live_writer(&held(), held().channel(&general).unwrap()).unwrap();
        let cert = cert_for(&held(), &general, live, &w.public_key());
        let signed = GroupKey::from_parts(writer.keys().clone(), read.conv_key().clone());
        set_banlist(&bed.relay, &held(), &[w.public_key().to_hex()]).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        sync_guestbook(&bed.relay, &held()).await.unwrap();
        assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().writers.cut, 1, "a ban is a stop on the ledger");
        assert!(held().channel(&general).unwrap().writers.as_ref().unwrap().stopped(live, &w.public_key().to_bytes(), u64::MAX));
        post_certified(&bed.relay, &held(), &w, &general, &signed, community.root_epoch, Some((live, Some(cert))), "while banned", now_ms() + 1_000).await;
        set_banlist(&bed.relay, &held(), &[]).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        bed.swap_to(&member);
        follow_control(&bed.relay, &held()).await.unwrap();
        assert!(!channel_texts(&bed.relay, &held(), &general).await.contains(&"while banned".to_string()), "an un-ban brings nothing back");
        // Un-banned, they rejoin.
        bed.swap_to(&owner);
        crate::rt::time::sleep(std::time::Duration::from_millis(1_100)).await;
        let gb = crate::community::v2::derive::guestbook_group_key(&held().community_root, community.id(), held().root_epoch);
        let join = guestbook::build_join_rumor(w.public_key(), None, now_ms());
        let (wrap, _) = guestbook::seal_guestbook_rumor(&join, &gb, &w, Timestamp::from_secs(now_ms() / 1000)).unwrap();
        bed.relay.publish(&wrap, &held().relays).await.unwrap();
        sync_guestbook(&bed.relay, &held()).await.unwrap();
        access_duty(&bed.relay, &held()).await.unwrap();
        let fresh = held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0;
        let scope = crate::community::v2::writers::writer_rekey_scope(&general);
        let plane = fetch_plane_deliveries(&bed.relay, &held(), &general, scope).await.unwrap();
        assert!(fresh > live && served_at(&plane, &w.public_key(), scope, fresh, &|_| true), "the un-banned writer posts again on a fresh epoch");
    }

    #[tokio::test]
    async fn one_back_from_a_kick_posts_nothing_more_at_that_epoch_whatever_their_join_says() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, member, community, general) = restricted_bed(false).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let read = channel_group_key(&community.community_root, &general, community.root_epoch);
        bed.swap_to(&owner);
        let w = Keys::generate();
        set_member_roles(&bed.relay, &held(), &w.public_key(), vec![create_role_v2(&bed.relay, &held(), "Plain", 0, 0).await.unwrap()]).await.unwrap();
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
        let (live, _, writer) = writing::live_writer(&held(), held().channel(&general).unwrap()).unwrap();
        let cert = cert_for(&held(), &general, live, &w.public_key());
        let signed = GroupKey::from_parts(writer.keys().clone(), read.conv_key().clone());
        let gb = crate::community::v2::derive::guestbook_group_key(&held().community_root, community.id(), held().root_epoch);
        let kicked_at = now_ms();
        let kick = guestbook::build_kick_rumor(owner.keys.public_key(), w.public_key(), None, kicked_at);
        let (wrap, _) = guestbook::seal_guestbook_rumor(&kick, &gb, &owner.keys, Timestamp::from_secs(kicked_at / 1000)).unwrap();
        bed.relay.publish(&wrap, &held().relays).await.unwrap();
        post_certified(&bed.relay, &held(), &w, &general, &signed, community.root_epoch, Some((live, Some(cert))), "while kicked", kicked_at + 500).await;
        // They come back with a Join dated a moment after the Kick.
        let join = guestbook::build_join_rumor(w.public_key(), None, kicked_at + 1);
        let (wrap, _) = guestbook::seal_guestbook_rumor(&join, &gb, &w, Timestamp::from_secs(kicked_at / 1000)).unwrap();
        bed.relay.publish(&wrap, &held().relays).await.unwrap();
        post_certified(&bed.relay, &held(), &w, &general, &signed, community.root_epoch, Some((live, Some(cert))), "after the join", kicked_at + 2_000).await;
        bed.swap_to(&member);
        follow_control(&bed.relay, &held()).await.unwrap();
        sync_guestbook(&bed.relay, &held()).await.unwrap();
        let texts = channel_texts(&bed.relay, &held(), &general).await;
        assert!(!texts.contains(&"while kicked".to_string()) && !texts.contains(&"after the join".to_string()), "back, they post on a fresh epoch, never this one");
        bed.swap_to(&owner);
        sync_guestbook(&bed.relay, &held()).await.unwrap();
        access_duty(&bed.relay, &held()).await.unwrap();
        let fresh = held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0;
        assert!(fresh > live, "the duty restarts them");
    }

    #[tokio::test]
    async fn a_writer_who_left_of_their_own_accord_posts_again_on_rejoining() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, member, community, general) = restricted_bed(false).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let read = channel_group_key(&community.community_root, &general, community.root_epoch);
        bed.swap_to(&owner);
        let w = Keys::generate();
        set_member_roles(&bed.relay, &held(), &w.public_key(), vec![create_role_v2(&bed.relay, &held(), "Plain", 0, 0).await.unwrap()]).await.unwrap();
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
        let (live, _, writer) = writing::live_writer(&held(), held().channel(&general).unwrap()).unwrap();
        let cert = cert_for(&held(), &general, live, &w.public_key());
        let signed = GroupKey::from_parts(writer.keys().clone(), read.conv_key().clone());
        let gb = crate::community::v2::derive::guestbook_group_key(&held().community_root, community.id(), held().root_epoch);
        let left = now_ms();
        for (rumor, at) in [(guestbook::build_leave_rumor(w.public_key(), left), left), (guestbook::build_join_rumor(w.public_key(), None, left + 1_000), left + 1_000)] {
            let (wrap, _) = guestbook::seal_guestbook_rumor(&rumor, &gb, &w, Timestamp::from_secs(at / 1000)).unwrap();
            bed.relay.publish(&wrap, &held().relays).await.unwrap();
        }
        post_certified(&bed.relay, &held(), &w, &general, &signed, community.root_epoch, Some((live, Some(cert))), "back again", left + 2_000).await;
        sync_guestbook(&bed.relay, &held()).await.unwrap();
        access_duty(&bed.relay, &held()).await.unwrap();
        assert_eq!(held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0, live, "a Leave of their own costs no fresh epoch");
        bed.swap_to(&member);
        follow_control(&bed.relay, &held()).await.unwrap();
        sync_guestbook(&bed.relay, &held()).await.unwrap();
        assert!(channel_texts(&bed.relay, &held(), &general).await.contains(&"back again".to_string()));
    }

    #[tokio::test]
    async fn a_kicked_writer_back_again_cannot_post_until_a_fresh_epoch() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, member, community, general) = restricted_bed(false).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        bed.swap_to(&owner);
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(member.keys.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
        bed.swap_to(&member);
        follow_control(&bed.relay, &held()).await.unwrap();
        collect_writers(&bed.relay, &held()).await.unwrap();
        assert!(writing::can_post(&held(), &general), "a writer posts");
        let gb = crate::community::v2::derive::guestbook_group_key(&held().community_root, community.id(), held().root_epoch);
        let at = now_ms();
        let kick = guestbook::build_kick_rumor(owner.keys.public_key(), member.keys.public_key(), None, at);
        let (wrap, _) = guestbook::seal_guestbook_rumor(&kick, &gb, &owner.keys, Timestamp::from_secs(at / 1000)).unwrap();
        bed.relay.publish(&wrap, &held().relays).await.unwrap();
        let join = guestbook::build_join_rumor(member.keys.public_key(), None, at + 1_000);
        let (wrap, _) = guestbook::seal_guestbook_rumor(&join, &gb, &member.keys, Timestamp::from_secs(at / 1000 + 1)).unwrap();
        bed.relay.publish(&wrap, &held().relays).await.unwrap();
        sync_guestbook(&bed.relay, &held()).await.unwrap();
        assert!(!writing::can_post(&held(), &general), "what they'd post at the epoch they were kicked in stands nowhere: the composer waits");
        // Made a manager, their posts stand on the Roster: nothing to wait for.
        bed.swap_to(&owner);
        let mods = create_role_v2(&bed.relay, &held(), "Mods", 0, Permissions::MANAGE_CHANNELS).await.unwrap();
        set_member_roles(&bed.relay, &held(), &member.keys.public_key(), vec![mods]).await.unwrap();
        bed.swap_to(&member);
        follow_control(&bed.relay, &held()).await.unwrap();
        assert!(writing::can_post(&held(), &general), "a manager back from a Kick posts at once");
    }

    #[tokio::test]
    async fn a_departure_owes_only_the_posts_made_while_away() {
        let (_bed, _owner, _member, community, general) = restricted_bed(false).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let (cid_hex, chan_hex) = (crate::simd::hex::bytes_to_hex_32(&community.id().0), crate::simd::hex::bytes_to_hex_32(&general.0));
        let w = Keys::generate();
        let at = now_ms();
        let event = |id: u8, entry| guestbook::GuestbookEvent { rumor_id: [id; 32], entry, epoch: Some(held().root_epoch.0), observed_at: None };
        ingest_guestbook_event(&held(), event(1, guestbook::GuestbookEntry::Join { member: w.public_key(), invited_by: None, at_ms: at - 5_000 }), at / 1000 - 5).unwrap();
        let shown = crate::types::Message { id: "a".repeat(64), content: "while away".into(), at: at + 1_000, npub: Some(nostr_sdk::prelude::ToBech32::to_bech32(&w.public_key()).unwrap()), wrapper_event_id: Some("b".repeat(64)), writer: true, ..Default::default() };
        crate::db::events::save_message(&chan_hex, &shown).await.unwrap();
        clear_owed(&cid_hex);
        ingest_guestbook_event(&held(), event(2, guestbook::GuestbookEntry::Leave { member: w.public_key(), at_ms: at }), at / 1000).unwrap();
        ingest_guestbook_event(&held(), event(3, guestbook::GuestbookEntry::Join { member: w.public_key(), invited_by: None, at_ms: at + 2_000 }), at / 1000 + 2).unwrap();
        let owed = crate::db::community::owed_author_retractions(&cid_hex).unwrap();
        assert!(owed.iter().any(|o| o.3 == Some(at + 2_000)), "a Leave's take-back ends at the Join that ended it: {owed:?}");
        assert!(owed.iter().all(|o| o.3.is_some()), "nothing owed past the span");
        // Away again: only the new span is owed, never the one already taken back.
        clear_owed(&cid_hex);
        ingest_guestbook_event(&held(), event(4, guestbook::GuestbookEntry::Leave { member: w.public_key(), at_ms: at + 3_000 }), at / 1000 + 3).unwrap();
        let again = crate::types::Message { id: "c".repeat(64), at: at + 4_000, wrapper_event_id: Some("d".repeat(64)), ..shown };
        crate::db::events::save_message(&chan_hex, &again).await.unwrap();
        ingest_guestbook_event(&held(), event(5, guestbook::GuestbookEntry::Join { member: w.public_key(), invited_by: None, at_ms: at + 5_000 }), at / 1000 + 5).unwrap();
        let owed = crate::db::community::owed_author_retractions(&cid_hex).unwrap();
        assert!(!owed.is_empty() && owed.iter().all(|o| o.2 >= at + 3_000), "{owed:?}");
    }

    #[tokio::test]
    async fn a_closing_mint_stops_nobody_for_read_address_spam() {
        let (bed, owner, _member, community, general) = restricted_bed(false).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let read = channel_group_key(&community.community_root, &general, community.root_epoch);
        bed.swap_to(&owner);
        let spammer = Keys::generate();
        let gb = crate::community::v2::derive::guestbook_group_key(&held().community_root, community.id(), held().root_epoch);
        let at = now_ms();
        let kick = guestbook::build_kick_rumor(owner.keys.public_key(), spammer.public_key(), None, at);
        let (wrap, _) = guestbook::seal_guestbook_rumor(&kick, &gb, &owner.keys, Timestamp::from_secs(at / 1000)).unwrap();
        bed.relay.publish(&wrap, &held().relays).await.unwrap();
        sync_guestbook(&bed.relay, &held()).await.unwrap();
        post_raw(&bed.relay, &held(), &spammer, &general, &read, community.root_epoch, None, "spam", at + 500).await;
        channel_texts(&bed.relay, &held(), &general).await;
        let roster = crate::db::community::get_community_roles(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap();
        writing::mint_for_test(&bed.relay, &held(), &general, &roster).await.unwrap();
        let ledger = held().channel(&general).unwrap().writers.clone().unwrap();
        assert!(!ledger.entries.iter().any(|e| matches!(e.spell, crate::community::v2::writers::Spell::Stop { writer } if writer == spammer.public_key().to_bytes())), "only posts sent with the closing key earn a stop");
    }

    fn clear_owed(cid_hex: &str) {
        for (chan, since, generation) in crate::db::community::owed_retractions(cid_hex).unwrap() {
            crate::db::community::settle_retraction(cid_hex, &chan, since, generation).unwrap();
        }
        for (chan, author, since, until, generation) in crate::db::community::owed_author_retractions(cid_hex).unwrap() {
            crate::db::community::settle_author_retraction(cid_hex, &chan, &author, since, until, generation).unwrap();
        }
    }

    /// Answers no fetch by id, as a relay that serves a plane only to its own key.
    struct NoIds<'a>(&'a MemoryRelay);
    #[async_trait::async_trait]
    impl Transport for NoIds<'_> {
        async fn fetch_plane(&self, _plane: &Keys, query: &Query, relays: &[String]) -> Result<crate::community::transport::PlaneFetch, String> {
            if !query.ids.is_empty() {
                return Ok(crate::community::transport::PlaneFetch { events: Vec::new(), answered: relays.len(), attempted: relays.len() });
            }
            self.0.fetch_plane(_plane, query, relays).await
        }
        async fn publish(&self, e: &Event, r: &[String]) -> Result<(), String> {
            self.0.publish(e, r).await
        }
        async fn publish_durable(&self, e: &Event, r: &[String]) -> Result<(), String> {
            self.0.publish_durable(e, r).await
        }
        async fn fetch(&self, q: &Query, r: &[String]) -> Result<Vec<Event>, String> {
            if !q.ids.is_empty() {
                return Ok(Vec::new());
            }
            self.0.fetch(q, r).await
        }
    }

    #[tokio::test]
    async fn nothing_is_taken_back_that_could_not_be_held() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, member, community, general) = restricted_bed(false).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let read = channel_group_key(&community.community_root, &general, community.root_epoch);
        let chan_hex = crate::simd::hex::bytes_to_hex_32(&general.0);
        bed.swap_to(&owner);
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, 0).await.unwrap();
        let p = Keys::generate();
        post_raw(&bed.relay, &held(), &p, &general, &read, community.root_epoch, None, "after the restrict", now_ms() + 3_000).await;
        bed.swap_to(&member);
        follow_control(&bed.relay, &held()).await.unwrap();
        let page = fetch_channel_history(&bed.relay, &held(), &general, 50, 2, None, None, crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await.unwrap();
        for f in page.iter().filter(|f| f.event.opened().rumor.content == "after the restrict") {
            crate::community::v2::inbound::persist_routed_chat_event(&f.event, &chan_hex, &community.id().0, &member.keys.public_key()).await.expect("stood while open");
        }
        bed.swap_to(&owner);
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
        bed.swap_to(&member);
        follow_control(&bed.relay, &held()).await.unwrap();
        let ledger = held().channel(&general).unwrap().writers.clone().unwrap();
        let added = vec![ledger.entries.last().unwrap().clone()];
        let shown = Shown::default();
        assert_eq!(writing::retract_after(&NoIds(&bed.relay), &held(), held().channel(&general).unwrap(), &added, &shown).await, 0);
        assert!(shown.take().is_empty(), "the post stays until its wrap can be held");
    }

    #[tokio::test]
    async fn a_mint_whose_ledger_moved_while_it_built_sends_nothing() {
        use crate::community::roles::OverwriteTarget;
        use crate::community::v2::writers::Spell;
        let (bed, owner, x, community) = v2_bed_with_admin("Moved mid-build").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let general = held().channels[0].id;
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
        let eid = crate::community::v2::derive::writers_locator(community.id(), &general);
        let mine = held().channel(&general).unwrap().writers.clone().unwrap();
        // x reopens on the relays; this device hasn't folded it.
        let theirs = mine.appended(now_ms(), Spell::Open).unwrap();
        let cite = cite_on_relay(&bed.relay, &held(), &x).await;
        let prev = crate::db::community::get_edition_head(&crate::simd::hex::bytes_to_hex_32(&community.id().0), &crate::simd::hex::bytes_to_hex_32(&eid)).unwrap().map(|(_, h)| h);
        let rumor = control::build_edition_rumor_bound(x.public_key(), vsk::WRITERS, &eid, 2, prev.as_ref(), &theirs.to_json(), now_ms() / 1000, cite.as_ref(), Some(crate::community::v2::derive::edition_binding(community.id())));
        let group = control::ControlPlane::of(&held()).write_group().unwrap();
        let (wrap, _) = control::seal_control_edition(&rumor, &group, &x, Timestamp::from_secs(now_ms() / 1000)).unwrap();
        bed.relay.publish(&wrap, &held().relays).await.unwrap();
        act_as(&owner.keys);
        let scope = crate::community::v2::writers::writer_rekey_scope(&general);
        let before = fetch_plane_deliveries(&bed.relay, &held(), &general, scope).await.unwrap().len();
        let roster = crate::db::community::get_community_roles(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap();
        assert_eq!(writing::mint_for_test(&bed.relay, &held(), &general, &roster).await, Err(writing::LEDGER_MOVED_FOR_TEST.to_string()));
        assert_eq!(fetch_plane_deliveries(&bed.relay, &held(), &general, scope).await.unwrap().len(), before, "nothing sent over a ledger that moved");
    }

    #[tokio::test]
    async fn a_guestbook_wall_of_one_second_is_stepped_past() {
        let (bed, owner, _member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Wall", bed.relays.clone(), None).await.unwrap();
        let gb = crate::community::v2::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
        let old = Keys::generate();
        let at = now_ms() / 1000 - 10_000;
        let join = guestbook::build_join_rumor(old.public_key(), None, (at - 5) * 1000);
        let (wrap, _) = guestbook::seal_guestbook_rumor(&join, &gb, &old, Timestamp::from_secs(at - 5)).unwrap();
        bed.relay.publish(&wrap, &community.relays).await.unwrap();
        for _ in 0..600 {
            let k = Keys::generate();
            let join = guestbook::build_join_rumor(k.public_key(), None, at * 1000);
            let (wrap, _) = guestbook::seal_guestbook_rumor(&join, &gb, &k, Timestamp::from_secs(at)).unwrap();
            bed.relay.publish(&wrap, &community.relays).await.unwrap();
        }
        while !guestbook_walked_this_session(&community) {
            sync_guestbook(&bed.relay, &community).await.unwrap();
        }
        let members = stored_memberlist_strict(&crate::db::community::load_community_v2(community.id()).unwrap().unwrap()).unwrap();
        assert!(members.contains(&old.public_key()), "what sits below a one-second wall is read too");
    }

    #[tokio::test]
    async fn a_reaction_paged_before_its_target_lands_once_the_target_does() {
        let (bed, owner, _member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Windows", bed.relays.clone(), None).await.unwrap();
        let general = community.channels[0].id;
        let chan_hex = crate::simd::hex::bytes_to_hex_32(&general.0);
        let group = channel_group_key(&community.community_root, &general, community.root_epoch);
        let peer = Keys::generate();
        let at = now_ms() - 60_000;
        let open = |rumor: nostr_sdk::prelude::UnsignedEvent, at: u64| {
            let (wrap, _) = chat::seal_chat_rumor(&rumor, &group, &peer, Timestamp::from_secs(at / 1000), false).unwrap();
            FetchedEvent { event: chat::open_chat_event(&wrap, &group, &general, community.root_epoch).unwrap(), epoch: community.root_epoch, wrap: Some(wrap) }
        };
        let message = open(chat::build_message_rumor(peer.public_key(), &general, community.root_epoch, "first", None, &[], vec![], at), at);
        let target = message.event.opened().rumor_id.to_hex();
        let reaction = open(chat::build_reaction_rumor(peer.public_key(), &general, community.root_epoch, &target, &peer.public_key().to_hex(), super::super::kind::MESSAGE, "+", None, at + 1_000), at + 1_000);
        let me = owner.keys.public_key();
        let session = crate::db::current_session;
        // The newer window first: its reaction has nothing to land on yet.
        let (_, waiting) = crate::VectorCore::v2_ingest_chat_page_keeping(&chan_hex, me, session(), vec![reaction]).await;
        assert_eq!(waiting.len(), 1, "kept back for its target");
        crate::VectorCore::v2_ingest_chat_page(&chan_hex, me, session(), vec![message]).await;
        crate::VectorCore::v2_ingest_chat_page_waiting(&chan_hex, me, session(), waiting).await;
        let (_, landed) = crate::state::STATE.lock().await.find_message(&target).unwrap();
        assert_eq!(landed.reactions.len(), 1, "the reaction lands on its target");
        let (_, none_left) = crate::VectorCore::v2_ingest_chat_page_keeping(&chan_hex, me, session(), Vec::new()).await;
        assert!(none_left.is_empty());
    }

    #[tokio::test]
    async fn a_page_judged_before_a_stop_landed_is_judged_again_as_it_lands() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, member, community, general) = restricted_bed(false).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let read = channel_group_key(&community.community_root, &general, community.root_epoch);
        let chan_hex = crate::simd::hex::bytes_to_hex_32(&general.0);
        bed.swap_to(&owner);
        let w = Keys::generate();
        set_member_roles(&bed.relay, &held(), &w.public_key(), vec![create_role_v2(&bed.relay, &held(), "Plain", 0, 0).await.unwrap()]).await.unwrap();
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
        let (e1, _, writer1) = writing::live_writer(&held(), held().channel(&general).unwrap()).unwrap();
        let cert = cert_for(&held(), &general, e1, &w.public_key());
        let at1 = GroupKey::from_parts(writer1.keys().clone(), read.conv_key().clone());
        post_certified(&bed.relay, &held(), &w, &general, &at1, community.root_epoch, Some((e1, Some(cert))), "late", now_ms() + 3_000).await;
        bed.swap_to(&member);
        follow_control(&bed.relay, &held()).await.unwrap();
        let page = fetch_channel_history(&bed.relay, &held(), &general, 50, 2, None, None, crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await.unwrap();
        assert!(page.iter().any(|f| f.event.opened().rumor.content == "late"));
        bed.swap_to(&owner);
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), 0, 0).await.unwrap();
        bed.swap_to(&member);
        follow_control(&bed.relay, &held()).await.unwrap();
        crate::VectorCore::v2_ingest_chat_page(&chan_hex, member.keys.public_key(), crate::db::current_session(), page).await;
        assert!(crate::db::events::posts_since(&chan_hex, 0).unwrap().iter().all(|p| p.npub.as_deref() != Some(nostr_sdk::prelude::ToBech32::to_bech32(&w.public_key()).unwrap().as_str())), "a page read before the stop keeps nothing the stop undoes");
        assert!(!crate::db::community::held_wraps(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap().is_empty(), "held, to be judged again");
    }

    #[tokio::test]
    async fn a_re_mint_that_fails_waits_before_trying_again() {
        use crate::community::roles::OverwriteTarget;
        use crate::community::v2::writers::{writer_address, Ledger, Spell};
        let (bed, owner, _x, community) = v2_bed_with_admin("Legacy retry").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let general = held().channels[0].id;
        let eid = crate::community::v2::derive::writers_locator(community.id(), &general);
        let old = Ledger::new(&general).appended(2_001_000, Spell::Writer { epoch: Epoch(1), pk: writer_address(&[0x77; 32], &general, Epoch(1)), root: Epoch(0), by: owner.keys.public_key().to_bytes(), certifier: None }).unwrap();
        publish_overwrite_raw(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await;
        publish_marked(&bed.relay, &held(), &owner.keys, vsk::WRITERS, &eid, 1, None, &old.to_json()).await;
        follow_control(&bed.relay, &held()).await.unwrap();
        let refusing = RefusesControl { inner: &bed.relay, control: control::ControlPlane::of(&held()).write_group().unwrap().pk_hex(), allow: 0.into(), tried: 0.into() };
        let _ = access_duty(&refusing, &held()).await;
        let _ = access_duty(&refusing, &held()).await;
        assert_eq!(refusing.tried.load(std::sync::atomic::Ordering::SeqCst), 1, "a refused re-mint waits out its lane");
    }

    #[tokio::test]
    async fn a_managers_marked_copy_loses_its_mark_once_the_post_stands() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, member, community, general) = restricted_bed(true).await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let chan_hex = crate::simd::hex::bytes_to_hex_32(&general.0);
        let read = channel_group_key(&community.community_root, &general, community.root_epoch);
        bed.swap_to(&owner);
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, 0).await.unwrap();
        let p = Keys::generate();
        post_raw(&bed.relay, &held(), &p, &general, &read, community.root_epoch, None, "early", now_ms()).await;

        bed.swap_to(&member);
        let page = fetch_channel_history(&bed.relay, &held(), &general, 50, 2, None, None, crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await.unwrap();
        let copy = page.into_iter().find(|f| f.event.opened().rumor.content == "early").expect("a manager keeps a copy");
        assert!(copy.event.opened().held, "marked");
        let id = copy.event.opened().rumor_id.to_hex();
        crate::community::v2::inbound::persist_routed_chat_event(&copy.event, &chan_hex, &community.id().0, &member.keys.public_key()).await.expect("stored");
        assert!(crate::db::events::get_message_by_id(&id).await.unwrap().unwrap().1.unauthorized);
        assert!(crate::db::community::community_member_activity(&cid_hex).unwrap().iter().all(|(n, _)| PublicKey::parse(n).unwrap() != p.public_key()), "a held post is no sign of membership");

        follow_control(&bed.relay, &held()).await.unwrap();
        let shown = Shown::default();
        assert_eq!(writing::rejudge_held(&held(), &shown).await, 1);
        assert_eq!(shown.take(), vec![("~early".to_string(), false)], "the copy shown loses its mark");
        assert!(!crate::db::events::get_message_by_id(&id).await.unwrap().unwrap().1.unauthorized, "and so does the stored one");
    }

    #[tokio::test]
    async fn a_restricted_channel_takes_posts_only_from_its_writers() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, member) = TestBed::new();
        let held = |c: &CommunityV2| crate::db::community::load_community_v2(c.id()).unwrap().unwrap();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Announce", bed.relays.clone(), None).await.unwrap();
        activate_roles_v2(&bed.relay, &community, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
        follow_control(&bed.relay, &community).await.unwrap();
        let general = community.channels[0].id;
        let read = channel_group_key(&community.community_root, &general, community.root_epoch);
        let m = member.keys.clone();
        let plain = create_role_v2(&bed.relay, &held(&community), "Member", 0, 0).await.unwrap();
        set_member_roles(&bed.relay, &held(&community), &m.public_key(), vec![plain]).await.unwrap();
        send_direct_invite(&bed.relay, &held(&community), &m.public_key(), None, None).await.unwrap();
        bed.swap_to(&member);
        accept_direct_invite(&bed.relay, &fetch_direct_invite(&bed.relay, &bed.relays, &m.public_key()).await).await.unwrap();
        follow_control(&bed.relay, &held(&community)).await.unwrap();
        send_chat_message_at(&bed.relay, &held(&community), &general, "before", None, &[], vec![], now_ms() - 20_000).await.unwrap();

        bed.swap_to(&owner);
        // A mint whose publish failed left this secret behind; the retry reuses it.
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        crate::db::community::store_epoch_key(&cid_hex, &crate::community::v2::writers::minted_scope(&general), 1, &[0x5e; 32]).unwrap();
        set_overwrite(&bed.relay, &held(&community), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
        let ch = held(&community).channel(&general).unwrap().clone();
        assert_eq!(ch.writers.as_ref().unwrap().current_writer().unwrap().1, crate::community::v2::writers::writer_address(&[0x5e; 32], &general, Epoch(1)));
        assert!(ch.restricted() && ch.writers.as_ref().unwrap().current_writer().unwrap().0 == Epoch(1), "restricting mints the ledger");
        assert!(can_post(&held(&community), &general), "the owner writes");
        send_message(&bed.relay, &held(&community), &general, "announcement").await.unwrap();

        bed.swap_to(&member);
        follow_control(&bed.relay, &held(&community)).await.unwrap();
        assert!(held(&community).channel(&general).unwrap().restricted(), "every member folds the ledger");
        assert!(!can_post(&held(&community), &general));
        assert_eq!(collect_writers(&bed.relay, &held(&community)).await.unwrap(), 0, "nothing for a member the channel doesn't let post");
        assert!(send_message(&bed.relay, &held(&community), &general, "denied").await.is_err());
        post_raw(&bed.relay, &held(&community), &m, &general, &read, community.root_epoch, None, "sneaky", now_ms()).await;
        let texts = channel_texts(&bed.relay, &held(&community), &general).await;
        assert!(texts.contains(&"before".to_string()) && texts.contains(&"announcement".to_string()), "a reader without the key reads the writers: {texts:?}");
        assert!(!texts.contains(&"sneaky".to_string()), "a member never sees what the windows don't stand behind");

        // Let the member post: the change's author hands them the live key.
        bed.swap_to(&owner);
        assert_eq!(marked_texts(&bed.relay, &held(&community), &general).await, vec!["sneaky".to_string()], "a manager sees it, marked");
        // A stranger leaves m certificates the certifier never signed, either side of the real one.
        let (live, pk) = held(&community).channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap();
        let forged = std::collections::HashMap::from([(m.public_key(), chat::WriterCert::Full([0x77; 64]))]);
        let stranger = Keys::generate();
        let forge = || async {
            act_as(&stranger);
            deliver_certified(&bed.relay, &held(&community), &general, crate::community::v2::writers::writer_rekey_scope(&general), live, Some(pk), &[0x99; 32], &[m.public_key()], &forged).await.unwrap();
            act_as(&owner.keys);
        };
        forge().await;
        set_overwrite(&bed.relay, &held(&community), general.0, OverwriteTarget::Member(m.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
        forge().await;
        bed.swap_to(&member);
        follow_control(&bed.relay, &held(&community)).await.unwrap();
        assert_eq!(collect_writers(&bed.relay, &held(&community)).await.unwrap(), 1);
        assert_eq!(collect_writers(&bed.relay, &held(&community)).await.unwrap(), 0, "held now");
        assert!(can_post(&held(&community), &general));
        send_message(&bed.relay, &held(&community), &general, "from m").await.unwrap();
        let (_, old_secret, old_writer) = writing::live_writer(&held(&community), held(&community).channel(&general).unwrap()).unwrap();
        bed.swap_to(&owner);
        assert!(channel_texts(&bed.relay, &held(&community), &general).await.contains(&"from m".to_string()));

        // Take it back: a stop voids their certificate from then on, with no new key to hand out.
        set_overwrite(&bed.relay, &held(&community), general.0, OverwriteTarget::Member(m.public_key().to_hex()), 0, 0).await.unwrap();
        let ledger = held(&community).channel(&general).unwrap().writers.clone().unwrap();
        assert_eq!(ledger.current_writer().unwrap().0, Epoch(1), "no fresh epoch");
        let last = ledger.entries.last().unwrap();
        assert!(matches!(last.spell, crate::community::v2::writers::Spell::Stop { writer } if writer == m.public_key().to_bytes()));
        let closed_at = last.at;
        let stale = GroupKey::from_parts(old_writer.keys().clone(), read.conv_key().clone());
        assert_eq!(crate::community::v2::derive::channel_writer_group_key(&old_secret, &general, Epoch(1)).pk(), stale.pk());
        let m_cert = cert_for(&held(&community), &general, Epoch(1), &m.public_key());
        post_certified(&bed.relay, &held(&community), &m, &general, &stale, community.root_epoch, Some((Epoch(1), Some(m_cert))), "late", closed_at + 5_000).await;
        post_certified(&bed.relay, &held(&community), &m, &general, &stale, community.root_epoch, Some((Epoch(1), Some(m_cert))), "in time", closed_at - 1).await;
        post_raw(&bed.relay, &held(&community), &m, &general, &stale, community.root_epoch, Some(Epoch(2)), "wrong epoch", closed_at - 2).await;
        send_message(&bed.relay, &held(&community), &general, "second").await.unwrap();
        let texts = channel_texts(&bed.relay, &held(&community), &general).await;
        assert!(texts.contains(&"in time".to_string()) && texts.contains(&"from m".to_string()), "a writer's past posts stay theirs: {texts:?}");
        assert_eq!(marked_texts(&bed.relay, &held(&community), &general).await, vec!["sneaky".to_string(), "late".to_string()], "nothing new through a key they kept stands");
        assert!(!texts.contains(&"wrong epoch".to_string()), "a post commits the epoch whose address served it");
        assert!(texts.contains(&"second".to_string()));
        let (live, live_secret, _) = writing::live_writer(&held(&community), held(&community).channel(&general).unwrap()).unwrap();
        // Even handed the live key, a member the channel doesn't let post never takes it.
        deliver_on_plane(&bed.relay, &held(&community), &general, crate::community::v2::writers::writer_rekey_scope(&general), live, Some(crate::community::v2::writers::writer_address(&live_secret, &general, live)), &live_secret, &[m.public_key()]).await.unwrap();
        bed.swap_to(&member);
        follow_control(&bed.relay, &held(&community)).await.unwrap();
        assert_eq!(collect_writers(&bed.relay, &held(&community)).await.unwrap(), 0, "the channel no longer lets them post");
        crate::db::community::store_epoch_key(&cid_hex, &crate::community::v2::writers::secret_scope(&general), live.0, &[0x42; 32]).unwrap();
        assert!(!can_post(&held(&community), &general), "a held secret that doesn't derive to the ledger's address writes nothing");
        crate::db::community::store_epoch_key(&cid_hex, &crate::community::v2::writers::secret_scope(&general), live.0, &live_secret).unwrap();
        assert!(!can_post(&held(&community), &general), "and the right key is no licence once the channel stops letting them post");
        assert!(send_message(&bed.relay, &held(&community), &general, "kept the key").await.is_err());
        assert!(!can_post(&held(&community), &general) && send_message(&bed.relay, &held(&community), &general, "denied").await.is_err());
        assert!(channel_texts(&bed.relay, &held(&community), &general).await.contains(&"second".to_string()), "still a reader");

        // Reopen: posts move back to the read address.
        bed.swap_to(&owner);
        set_overwrite(&bed.relay, &held(&community), general.0, OverwriteTarget::Everyone, 0, 0).await.unwrap();
        assert!(!held(&community).channel(&general).unwrap().restricted());
        bed.swap_to(&member);
        follow_control(&bed.relay, &held(&community)).await.unwrap();
        assert!(can_post(&held(&community), &general));
        send_message(&bed.relay, &held(&community), &general, "open again").await.unwrap();
        bed.swap_to(&owner);
        let texts = channel_texts(&bed.relay, &held(&community), &general).await;
        assert!(texts.contains(&"open again".to_string()), "{texts:?}");
        assert!(marked_texts(&bed.relay, &held(&community), &general).await.contains(&"sneaky".to_string()), "what a closed window got stays marked");
    }

    /// Publish an overwrite the way another client would: no settle follows it here.
    async fn publish_overwrite_raw<T: Transport + ?Sized>(relay: &T, community: &CommunityV2, scope: [u8; 32], target: crate::community::roles::OverwriteTarget, allow: u64, deny: u64) {
        let bytes = crate::community::v2::roles::overwrite_target_bytes(community.id(), &target).unwrap();
        let o = crate::community::roles::Overwrite { scope: crate::simd::hex::bytes_to_hex_32(&scope), target, allow: Permissions(allow), deny: Permissions(deny) };
        publish_control_edition(relay, community, vsk::CHANNEL_ACL, &crate::community::v2::derive::acl_locator(community.id(), &scope, &bytes), &crate::community::v2::roles::overwrite_content_json(&o)).await.unwrap();
    }

    #[tokio::test]
    async fn the_writer_duty_backs_up_a_change_made_elsewhere() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, member) = TestBed::new();
        let held = |c: &CommunityV2| crate::db::community::load_community_v2(c.id()).unwrap().unwrap();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Backstop", bed.relays.clone(), None).await.unwrap();
        activate_roles_v2(&bed.relay, &community, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
        follow_control(&bed.relay, &community).await.unwrap();
        let general = community.channels[0].id;
        let m = member.keys.public_key();
        let plain = create_role_v2(&bed.relay, &held(&community), "Member", 0, 0).await.unwrap();
        set_member_roles(&bed.relay, &held(&community), &m, vec![plain]).await.unwrap();
        send_direct_invite(&bed.relay, &held(&community), &m, None, None).await.unwrap();
        bed.swap_to(&member);
        accept_direct_invite(&bed.relay, &fetch_direct_invite(&bed.relay, &bed.relays, &m).await).await.unwrap();
        bed.swap_to(&owner);

        publish_overwrite_raw(&bed.relay, &held(&community), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await;
        follow_control(&bed.relay, &held(&community)).await.unwrap();
        assert!(!held(&community).channel(&general).unwrap().restricted(), "nobody moved the ledger yet");
        let blind = BreaksAfterPublish { inner: &bed.relay, broken: true.into() };
        assert!(access_duty(&blind, &held(&community)).await.is_err(), "nothing moves on a partial read");
        assert_eq!(access_duty(&bed.relay, &held(&community)).await.unwrap().writers, WriterDuty { moved: 1, ..Default::default() });
        assert!(held(&community).channel(&general).unwrap().restricted());
        assert_eq!(access_duty(&bed.relay, &held(&community)).await.unwrap().writers, WriterDuty::default(), "in line now");

        publish_overwrite_raw(&bed.relay, &held(&community), general.0, OverwriteTarget::Member(m.to_hex()), Permissions::SEND_MESSAGES, 0).await;
        follow_control(&bed.relay, &held(&community)).await.unwrap();
        // A stranger hands the new writer a key the ledger never named.
        let stranger = Keys::generate();
        act_as(&stranger);
        let scope = crate::community::v2::writers::writer_rekey_scope(&general);
        let named = held(&community).channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().1;
        deliver_on_plane(&bed.relay, &held(&community), &general, scope, Epoch(1), Some(named), &[0x99; 32], &[m]).await.unwrap();
        act_as(&owner.keys);
        bed.swap_to(&member);
        follow_control(&bed.relay, &held(&community)).await.unwrap();
        assert_eq!(collect_writers(&bed.relay, &held(&community)).await.unwrap(), 0, "a key that derives elsewhere is never taken");
        assert!(!can_post(&held(&community), &general));
        bed.swap_to(&owner);
        // Even a manager's blob serves nobody when it names another address: a losing fork's.
        deliver_on_plane(&bed.relay, &held(&community), &general, scope, Epoch(1), Some([0x11; 32]), &[0x99; 32], &[m]).await.unwrap();
        assert_eq!(access_duty(&bed.relay, &held(&community)).await.unwrap().writers.delivered, 1, "the new writer is owed the live key");
        assert_eq!(access_duty(&bed.relay, &held(&community)).await.unwrap().writers.delivered, 0, "once");
        bed.swap_to(&member);
        follow_control(&bed.relay, &held(&community)).await.unwrap();
        assert_eq!(collect_writers(&bed.relay, &held(&community)).await.unwrap(), 1);
        assert!(can_post(&held(&community), &general));
        assert_eq!(access_duty(&bed.relay, &held(&community)).await.unwrap().writers, WriterDuty::default(), "a member served already owes nobody");
        bed.swap_to(&owner);

        publish_overwrite_raw(&bed.relay, &held(&community), general.0, OverwriteTarget::Member(m.to_hex()), 0, 0).await;
        follow_control(&bed.relay, &held(&community)).await.unwrap();
        assert_eq!(access_duty(&bed.relay, &held(&community)).await.unwrap().writers.cut, 0, "who may post is an absence verdict: not before the memberlist is read whole");
        sync_guestbook(&bed.relay, &held(&community)).await.unwrap();
        assert_eq!(access_duty(&bed.relay, &held(&community)).await.unwrap().writers.cut, 1, "a served writer the channel no longer lets post");
        let ledger = held(&community).channel(&general).unwrap().writers.clone().unwrap();
        assert_eq!(ledger.current_writer().unwrap().0, Epoch(1), "stopped, with no new key");
        assert!(ledger.stopped(Epoch(1), &m.to_bytes(), u64::MAX));
        assert_eq!(access_duty(&bed.relay, &held(&community)).await.unwrap().writers, WriterDuty::default(), "stopped once");
        bed.swap_to(&member);
        follow_control(&bed.relay, &held(&community)).await.unwrap();
        assert!(!can_post(&held(&community), &general));
        bed.swap_to(&owner);
        // Let back in, a writer this epoch stopped is owed a fresh one.
        publish_overwrite_raw(&bed.relay, &held(&community), general.0, OverwriteTarget::Member(m.to_hex()), Permissions::SEND_MESSAGES, 0).await;
        follow_control(&bed.relay, &held(&community)).await.unwrap();
        bed.swap_to(&member);
        follow_control(&bed.relay, &held(&community)).await.unwrap();
        assert!(!can_post(&held(&community), &general), "a writer this epoch stopped posts nothing here, key or not");
        bed.swap_to(&owner);
        assert_eq!(access_duty(&bed.relay, &held(&community)).await.unwrap().writers.moved, 0, "letting someone back is judged on a memberlist read whole");
        sync_guestbook(&bed.relay, &held(&community)).await.unwrap();
        assert_eq!(access_duty(&bed.relay, &held(&community)).await.unwrap().writers.moved, 1);
        assert_eq!(held(&community).channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0, Epoch(2));
        bed.swap_to(&member);
        follow_control(&bed.relay, &held(&community)).await.unwrap();
        collect_writers(&bed.relay, &held(&community)).await.unwrap();
        assert!(can_post(&held(&community), &general));
        bed.swap_to(&owner);
        publish_overwrite_raw(&bed.relay, &held(&community), general.0, OverwriteTarget::Member(m.to_hex()), 0, 0).await;
        follow_control(&bed.relay, &held(&community)).await.unwrap();
        sync_guestbook(&bed.relay, &held(&community)).await.unwrap();
        assert_eq!(access_duty(&bed.relay, &held(&community)).await.unwrap().writers.cut, 1, "stopped at the fresh epoch too");
        assert!(held(&community).channel(&general).unwrap().writers.as_ref().unwrap().stopped(Epoch(2), &m.to_bytes(), u64::MAX));
        assert_eq!(access_duty(&bed.relay, &held(&community)).await.unwrap().writers.cut, 0, "once");
        bed.swap_to(&member);
        follow_control(&bed.relay, &held(&community)).await.unwrap();
        assert!(!can_post(&held(&community), &general));
        bed.swap_to(&owner);

        publish_overwrite_raw(&bed.relay, &held(&community), general.0, OverwriteTarget::Everyone, 0, 0).await;
        follow_control(&bed.relay, &held(&community)).await.unwrap();
        assert_eq!(access_duty(&bed.relay, &held(&community)).await.unwrap().writers.moved, 1);
        assert!(!held(&community).channel(&general).unwrap().restricted());
    }

    #[tokio::test]
    async fn a_refounding_retires_the_writer_key() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, member) = TestBed::new();
        let held = |c: &CommunityV2| crate::db::community::load_community_v2(c.id()).unwrap().unwrap();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Retire", bed.relays.clone(), None).await.unwrap();
        activate_roles_v2(&bed.relay, &community, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
        follow_control(&bed.relay, &community).await.unwrap();
        let general = community.channels[0].id;
        let m = member.keys.public_key();
        let plain = create_role_v2(&bed.relay, &held(&community), "Member", 0, 0).await.unwrap();
        set_member_roles(&bed.relay, &held(&community), &m, vec![plain]).await.unwrap();
        send_direct_invite(&bed.relay, &held(&community), &m, None, None).await.unwrap();
        bed.swap_to(&member);
        accept_direct_invite(&bed.relay, &fetch_direct_invite(&bed.relay, &bed.relays, &m).await).await.unwrap();
        bed.swap_to(&owner);
        set_overwrite(&bed.relay, &held(&community), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
        set_overwrite(&bed.relay, &held(&community), general.0, OverwriteTarget::Member(m.to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
        bed.swap_to(&member);
        follow_control(&bed.relay, &held(&community)).await.unwrap();
        assert_eq!(collect_writers(&bed.relay, &held(&community)).await.unwrap(), 1, "a writer before the ban");
        bed.swap_to(&owner);
        assert_eq!(held(&community).channel(&general).unwrap().writers.as_ref().unwrap().live().map(|l| l.0), Some(Epoch(0)));

        set_members_banned(&bed.relay, community.id(), &[m], true).await.unwrap();
        let after = held(&community);
        assert!(after.root_epoch > community.root_epoch, "a ban refounds");
        // The Refounder re-mints at once; the duty finds nothing left.
        let ledger = held(&community).channel(&general).unwrap().writers.clone().unwrap();
        assert_eq!((ledger.current_writer().unwrap().0, ledger.live().map(|l| l.0)), (Epoch(2), Some(after.root_epoch)));
        let scope = crate::community::v2::writers::writer_rekey_scope(&general);
        let on_plane = fetch_plane_deliveries(&bed.relay, &held(&community), &general, scope).await.unwrap();
        assert!(!served_at(&on_plane, &m, scope, Epoch(2), &|_| true), "the banned writer is left out");
        assert!(served_at(&on_plane, &owner.keys.public_key(), scope, Epoch(2), &|_| true));
        follow_control(&bed.relay, &after).await.unwrap();
        assert_eq!(access_duty(&bed.relay, &held(&community)).await.unwrap().writers, WriterDuty::default(), "retired once");
    }

    #[tokio::test]
    async fn a_manager_cuts_only_writers_it_outranks() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, _m) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Ranks", bed.relays.clone(), None).await.unwrap();
        activate_roles_v2(&bed.relay, &community, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
        follow_control(&bed.relay, &community).await.unwrap();
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let general = held().channels[0].id;
        // Senior ranks above Admin without managing anything: a manager may hold the key anyway.
        let senior = create_role_v2(&bed.relay, &held(), "Senior", 0, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
        let admin = create_role_v2(&bed.relay, &held(), "Admin", 0, Permissions::MANAGE_CHANNELS | crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
        let (y, x) = (Keys::generate(), Keys::generate());
        set_member_roles(&bed.relay, &held(), &y.public_key(), vec![senior.clone()]).await.unwrap();
        set_member_roles(&bed.relay, &held(), &x.public_key(), vec![admin]).await.unwrap();
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Role(senior.clone()), Permissions::SEND_MESSAGES, 0).await.unwrap();
        publish_overwrite_raw(&bed.relay, &held(), general.0, OverwriteTarget::Role(senior), 0, 0).await;
        follow_control(&bed.relay, &held()).await.unwrap();
        sync_guestbook(&bed.relay, &held()).await.unwrap();
        act_as(&x);
        assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().writers.cut, 0, "a writer who outranks this manager is someone else's to cut");
        act_as(&owner.keys);
        assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().writers.cut, 1);
    }

    #[tokio::test]
    async fn a_private_channels_metadata_is_sealed_from_members_without_its_key() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, member) = TestBed::new();
        let held = |c: &CommunityV2| crate::db::community::load_community_v2(c.id()).unwrap().unwrap();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Sealed", bed.relays.clone(), None).await.unwrap();
        activate_roles_v2(&bed.relay, &community, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
        follow_control(&bed.relay, &community).await.unwrap();
        let m = member.keys.public_key();
        let managers = create_role_v2(&bed.relay, &held(&community), "Managers", 0, Permissions::MANAGE_CHANNELS | crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
        set_member_roles(&bed.relay, &held(&community), &m, vec![managers]).await.unwrap();
        let ch = create_private_channel(&bed.relay, &held(&community), "war room").await.unwrap();
        let mut meta = held(&community).channel(&ch).unwrap().metadata();
        meta.extra.insert("topic".into(), "the plan".into());
        edit_channel_metadata(&bed.relay, &held(&community), &ch, &meta).await.unwrap();
        let editions = fetch_control(&bed.relay, &held(&community)).await;
        let heads: Vec<&ParsedEdition> = editions.iter().filter(|e| e.vsk == vsk::CHANNEL_METADATA && e.entity_id == ch.0).collect();
        assert!(heads.len() >= 2 && heads.iter().all(|e| !e.content.contains("war room") && !e.content.contains("the plan")), "nothing a keyless member reads names it");
        assert!(heads.iter().all(|e| control::parse_sealed_channel_meta(&e.content).is_some()));
        send_direct_invite(&bed.relay, &held(&community), &m, None, None).await.unwrap();

        bed.swap_to(&member);
        accept_direct_invite(&bed.relay, &fetch_direct_invite(&bed.relay, &bed.relays, &m).await).await.unwrap();
        follow_control(&bed.relay, &held(&community)).await.unwrap();
        let dark = held(&community).channel(&ch).cloned().expect("a keyless member still sees it exists");
        assert!(dark.private && dark.key.is_none() && dark.name.is_empty() && dark.sealed.as_ref().is_some_and(|s| !s.open), "{dark:?}");
        assert!(edit_channel_metadata(&bed.relay, &held(&community), &ch, &meta).await.is_err(), "a writer can't build a sealed edition from metadata it couldn't read");

        // Let them in: the key arrives and opens the seal.
        bed.swap_to(&owner);
        set_overwrite(&bed.relay, &held(&community), ch.0, OverwriteTarget::Member(m.to_hex()), Permissions::VIEW_CHANNEL, 0).await.unwrap();
        follow_control(&bed.relay, &held(&community)).await.unwrap();
        access_duty(&bed.relay, &held(&community)).await.unwrap();
        bed.swap_to(&member);
        follow_control(&bed.relay, &held(&community)).await.unwrap();
        assert_eq!(collect_access(&bed.relay, &held(&community)).await.unwrap(), 1);
        assert_eq!(absorb_parked_channel_keys(&held(&community), &crate::db::current_session()).len(), 1);
        let open = held(&community).channel(&ch).cloned().unwrap();
        assert_eq!((open.name.as_str(), open.topic()), ("war room", Some("the plan")), "the key opens the seal");
        // Unopened details are never republished, even by a key holder.
        let whole = held(&community);
        let mut stale = whole.clone();
        stale.channels.iter_mut().find(|c| c.id == ch).unwrap().sealed.as_mut().unwrap().open = false;
        crate::db::community::save_community_v2(&stale).unwrap();
        assert!(edit_channel_metadata(&bed.relay, &held(&community), &ch, &meta).await.unwrap_err().contains("sealed"));
        crate::db::community::save_community_v2(&whole).unwrap();

        // A rename by someone else opens on arrival.
        bed.swap_to(&owner);
        let mut renamed = held(&community).channel(&ch).unwrap().metadata();
        renamed.name = "situation room".into();
        edit_channel_metadata(&bed.relay, &held(&community), &ch, &renamed).await.unwrap();
        bed.swap_to(&member);
        follow_control(&bed.relay, &held(&community)).await.unwrap();
        assert_eq!(held(&community).channel(&ch).unwrap().name, "situation room");

        // A rotation the member survives: the rotator re-seals under the new key, and the
        // member opens it once their rekey walk takes that key.
        bed.swap_to(&owner);
        let y = Keys::generate();
        let guests = create_role_v2(&bed.relay, &held(&community), "Guests", 0, 0).await.unwrap();
        set_member_roles(&bed.relay, &held(&community), &y.public_key(), vec![guests]).await.unwrap();
        set_overwrite(&bed.relay, &held(&community), ch.0, OverwriteTarget::Member(y.public_key().to_hex()), Permissions::VIEW_CHANNEL, 0).await.unwrap();
        set_overwrite(&bed.relay, &held(&community), ch.0, OverwriteTarget::Member(y.public_key().to_hex()), 0, 0).await.unwrap();
        let rotated = held(&community).channel(&ch).cloned().unwrap();
        assert!(rotated.epoch.0 >= 2);
        assert_eq!(rotated.sealed.as_ref().map(|s| (s.epoch, s.open)), Some((rotated.epoch.0, true)), "the rotator re-seals");
        assert_eq!(access_duty(&bed.relay, &held(&community)).await.unwrap().resealed, 0, "nothing left to re-seal");
        bed.swap_to(&member);
        follow_control(&bed.relay, &held(&community)).await.unwrap();
        follow_rekeys(&bed.relay, &held(&community), &crate::db::current_session()).await.unwrap();
        let kept = held(&community).channel(&ch).cloned().unwrap();
        assert_eq!((kept.epoch, kept.sealed.as_ref().map(|s| (s.epoch, s.open))), (rotated.epoch, Some((rotated.epoch.0, true))), "the new key opens the new seal");

        // Cut them: the next rotation re-seals beyond their reach.
        bed.swap_to(&owner);
        set_overwrite(&bed.relay, &held(&community), ch.0, OverwriteTarget::Member(m.to_hex()), 0, 0).await.unwrap();
        let rotated = held(&community).channel(&ch).cloned().unwrap();

        // A manager without the key still deletes it: the seal travels verbatim.
        bed.swap_to(&member);
        follow_control(&bed.relay, &held(&community)).await.unwrap();
        delete_channel(&bed.relay, &held(&community), &ch, "").await.unwrap();
        bed.swap_to(&owner);
        follow_control(&bed.relay, &held(&community)).await.unwrap();
        assert!(held(&community).channel(&ch).is_none(), "every member folds the deletion");
        let editions = fetch_control(&bed.relay, &held(&community)).await;
        let tomb = editions.iter().filter(|e| e.vsk == vsk::CHANNEL_METADATA && e.entity_id == ch.0).max_by_key(|e| e.version).unwrap();
        let tomb = control::parse_sealed_channel_meta(&tomb.content).unwrap();
        assert!(tomb.deleted && tomb.epoch == rotated.epoch.0);
    }

    #[tokio::test]
    async fn clearing_the_only_overwrite_that_named_someone_still_cuts_them() {
        use crate::community::roles::OverwriteTarget;
        let (bed, _owner, _x, community) = v2_bed_with_admin("OnlyNamed").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let ch = create_private_channel(&bed.relay, &held(), "side").await.unwrap();
        let y = Keys::generate();
        set_overwrite(&bed.relay, &held(), ch.0, OverwriteTarget::Member(y.public_key().to_hex()), Permissions::VIEW_CHANNEL, 0).await.unwrap();
        let before = held().channel(&ch).unwrap().epoch;
        set_overwrite(&bed.relay, &held(), ch.0, OverwriteTarget::Member(y.public_key().to_hex()), 0, 0).await.unwrap();
        assert!(held().channel(&ch).unwrap().epoch > before, "the key they were handed rotates away");
    }

    #[tokio::test]
    async fn a_manager_seals_a_private_channel_left_plain() {
        let (bed, _owner, _x, community) = v2_bed_with_admin("Plain").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let ch = create_private_channel(&bed.relay, &held(), "staff").await.unwrap();
        let plain = control::ChannelMetadata { name: "staff".into(), private: true, voice: None, deleted: None, custom: None, extra: Default::default() };
        publish_control_edition(&bed.relay, &held(), vsk::CHANNEL_METADATA, &ch.0, &serde_json::to_string(&plain).unwrap()).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        assert!(held().channel(&ch).unwrap().sealed.is_none(), "a plain head unseals the record");
        assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().resealed, 1);
        follow_control(&bed.relay, &held()).await.unwrap();
        let after = held().channel(&ch).cloned().unwrap();
        assert!(after.sealed.as_ref().is_some_and(|s| s.open) && after.name == "staff");
        assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().resealed, 0, "sealed once");
    }

    #[tokio::test]
    async fn a_demoted_minters_blobs_still_show_who_holds_the_key() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, _m) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Minter", bed.relays.clone(), None).await.unwrap();
        activate_roles_v2(&bed.relay, &community, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
        follow_control(&bed.relay, &community).await.unwrap();
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let general = held().channels[0].id;
        let mods = create_role_v2(&bed.relay, &held(), "Mods", 0, Permissions::MANAGE_CHANNELS | Permissions::MANAGE_ROLES | crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
        let members = create_role_v2(&bed.relay, &held(), "Members", 0, 0).await.unwrap();
        let (x, y) = (Keys::generate(), Keys::generate());
        set_member_roles(&bed.relay, &held(), &x.public_key(), vec![mods]).await.unwrap();
        set_member_roles(&bed.relay, &held(), &y.public_key(), vec![members]).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        act_as(&x);
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(y.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
        act_as(&owner.keys);
        assert_eq!(held().channel(&general).unwrap().writers.as_ref().unwrap().live().map(|l| l.1), Some(x.public_key().to_bytes()));
        // The minter loses its standing, then y loses Send where nobody settles it.
        set_member_roles(&bed.relay, &held(), &x.public_key(), vec![]).await.unwrap();
        publish_overwrite_raw(&bed.relay, &held(), general.0, OverwriteTarget::Member(y.public_key().to_hex()), 0, 0).await;
        follow_control(&bed.relay, &held()).await.unwrap();
        // The demotion took the certifier back with a fresh epoch at once; y, whom it still
        // vouches for, is stopped there.
        assert_eq!(held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0, Epoch(2));
        sync_guestbook(&bed.relay, &held()).await.unwrap();
        assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().writers.cut, 1);
        assert!(held().channel(&general).unwrap().writers.as_ref().unwrap().stopped(Epoch(2), &y.public_key().to_bytes(), u64::MAX));
    }

    #[tokio::test]
    async fn a_manager_nobody_served_mints_a_key_it_can_use() {
        use crate::community::roles::OverwriteTarget;
        use crate::community::v2::writers::{writer_address, Ledger, Spell};
        let (bed, owner, _x, community) = v2_bed_with_admin("Starved").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let general = held().channels[0].id;
        let eid = crate::community::v2::derive::writers_locator(community.id(), &general);
        let lost = Ledger::new(&general).appended(2_001_000, Spell::Writer { epoch: Epoch(1), pk: writer_address(&[0x77; 32], &general, Epoch(1)), root: Epoch(0), by: owner.keys.public_key().to_bytes(), certifier: crate::community::v2::writers::certifier_of(&[0x66; 32]) }).unwrap();
        publish_overwrite_raw(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await;
        publish_marked(&bed.relay, &held(), &owner.keys, vsk::WRITERS, &eid, 1, None, &lost.to_json()).await;
        follow_control(&bed.relay, &held()).await.unwrap();
        assert!(!can_post(&held(), &general), "a key nobody holds");
        let stranger = Keys::generate();
        publish_overwrite_raw(&bed.relay, &held(), general.0, OverwriteTarget::Member(stranger.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await;
        follow_control(&bed.relay, &held()).await.unwrap();
        // Another manager left a blob at the owner's locator that opens to nothing usable.
        let scope = crate::community::v2::writers::writer_rekey_scope(&general);
        act_as(&_x);
        deliver_on_plane(&bed.relay, &held(), &general, scope, Epoch(1), Some(lost.current_writer().unwrap().1), &[0x55; 32], &[owner.keys.public_key()]).await.unwrap();
        act_as(&owner.keys);
        assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().writers.moved, 0, "a manager just able to post waits for its key");
        writing::backdate_postable(&held(), &general, 1);
        assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().writers.moved, 1, "a blob that opens to nothing is no key");
        assert!(can_post(&held(), &general));
        let ledger = held().channel(&general).unwrap().writers.clone().unwrap();
        assert_eq!(ledger.current_writer().unwrap().0, Epoch(2));
        let plane = fetch_plane_deliveries(&bed.relay, &held(), &general, scope).await.unwrap();
        assert!(!served_at(&plane, &stranger.public_key(), scope, Epoch(2), &|_| true), "someone only an overwrite names is no member, so no writer");
        assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().writers, WriterDuty::default(), "minted once");
    }

    #[tokio::test]
    async fn history_pages_each_address_on_its_own() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, _m) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Pages", bed.relays.clone(), None).await.unwrap();
        activate_roles_v2(&bed.relay, &community, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
        follow_control(&bed.relay, &community).await.unwrap();
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let general = held().channels[0].id;
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
        let now = now_ms();
        for i in 0..25u64 {
            send_chat_message_at(&bed.relay, &held(), &general, &format!("post {i}"), None, &[], vec![], now - (25 - i) * 60_000).await.unwrap();
        }
        // One old reaction at the read address, far below the writer posts.
        let read = channel_group_key(&community.community_root, &general, community.root_epoch);
        let old = now - 2 * 86_400_000;
        let reaction = chat::build_reaction_rumor(owner.keys.public_key(), &general, community.root_epoch, &"ab".repeat(32), &owner.keys.public_key().to_hex(), 9, "+", None, old);
        let (wrap, _) = chat::seal_chat_rumor(&reaction, &read, &owner.keys, Timestamp::from_secs(old / 1000), false).unwrap();
        bed.relay.publish(&wrap, &community.relays).await.unwrap();
        let got = fetch_channel_history(&bed.relay, &held(), &general, 10, 10, None, None, crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await.unwrap();
        let posts = got.iter().filter(|f| matches!(f.event, ChatEvent::Message { .. })).count();
        assert_eq!(posts, 25, "a quiet address's old bottom never skips the busy one's middle");
        assert!(got.iter().any(|f| matches!(f.event, ChatEvent::Reaction { .. })));
    }

    #[tokio::test]
    async fn history_hands_back_where_to_page_on_from() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, _m) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Spam", bed.relays.clone(), None).await.unwrap();
        activate_roles_v2(&bed.relay, &community, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
        follow_control(&bed.relay, &community).await.unwrap();
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let general = held().channels[0].id;
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
        let now = now_ms();
        send_chat_message_at(&bed.relay, &held(), &general, "a writer's post", None, &[], vec![], now + 1_000).await.unwrap();
        // Anyone with the read key fills the read address, inside the window.
        let read = channel_group_key(&community.community_root, &general, community.root_epoch);
        let spammer = Keys::generate();
        for i in 0..25u64 {
            let at = now + 60_000 + i * 2_000;
            let rumor = chat::build_message_rumor(spammer.public_key(), &general, community.root_epoch, "spam", None, &[], vec![], at);
            let (wrap, _) = chat::seal_chat_rumor(&rumor, &read, &spammer, Timestamp::from_secs(at / 1000), false).unwrap();
            bed.relay.publish(&wrap, &community.relays).await.unwrap();
        }
        // Read once the flood is due, so it is paged rather than held.
        crate::clock::shift_for_test(3 * 60_000);
        let (got, cursor, _) = fetch_channel_history_paged(&bed.relay, &held(), &general, 10, 2, None, None, crate::community::transport::Evidence::Quorum, |_, _, _| true, |_| Default::default()).await.unwrap();
        assert!(!got.iter().any(|f| f.event.opened().rumor.content == "a writer's post") && cursor.is_some_and(|c| c > (now + 1_000) / 1000), "nothing below where the relay walk stopped");
        let (got, ..) = fetch_channel_history_paged(&bed.relay, &held(), &general, 10, 4, None, cursor, crate::community::transport::Evidence::Quorum, |_, _, _| true, |_| Default::default()).await.unwrap();
        crate::clock::shift_for_test(0);
        assert!(got.iter().any(|f| f.event.opened().rumor.content == "a writer's post"), "paging on from the cursor reaches it");
    }

    #[tokio::test]
    async fn a_catch_up_reads_through_held_rows_down_to_its_floor() {
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Hole", vec!["wss://r".into()], None).await.unwrap();
        let general = community.channels[0].id;
        let now = now_ms();
        let at = |i: u64| now - (30 - i) * 60_000;
        for i in 0..30u64 {
            send_chat_message_at(&relay, &community, &general, &format!("m{i}"), None, &[], vec![], at(i)).await.unwrap();
        }
        let all = fetch_channel(&relay, &community, &general, 100).await.unwrap();
        let id_of = |text: &str| all.iter().find(|f| f.event.opened().rumor.content == text).map(|f| f.event.opened().rumor_id.to_hex()).unwrap();
        // The oldest ten were read before going away and the newest ten arrived live after; nothing read the middle.
        let held: std::collections::HashSet<String> = (0..10).chain(20..30).map(|i| id_of(&format!("m{i}"))).collect();
        let walk = |floor: Option<u64>| {
            let held = held.clone();
            let relay = &relay;
            let community = &community;
            async move {
                let (got, ..) = fetch_channel_history_paged(relay, community, &general, 10, 10, None, None, crate::community::transport::Evidence::Quorum, |p, s, n| catch_up_pages_on(p, s, n, floor, |id| held.contains(id)), |_| Default::default()).await.unwrap();
                got.iter().map(|f| f.event.opened().rumor.content.clone()).collect::<std::collections::HashSet<_>>()
            }
        };
        assert!(!walk(None).await.contains("m15"), "without a floor the first held page ends the walk");
        let got = walk(Some(at(5) / 1000)).await;
        assert!((10..20).all(|i| got.contains(&format!("m{i}"))), "the unread middle is read");
    }

    #[tokio::test]
    async fn a_member_who_never_held_a_past_root_reads_it_once_the_channel_publishes_it() {
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Kept", vec!["wss://r".into()], None).await.unwrap();
        let general = community.channels[0].id;
        let now = now_ms();
        send_chat_message_at(&relay, &community, &general, "before", None, &[], vec![], now - 60_000).await.unwrap();
        let rotated = refound_community(&relay, &community, &[]).await.unwrap();
        send_chat_message_at(&relay, &rotated, &general, "after", None, &[], vec![], now + 1_000).await.unwrap();
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let (root, past) = (crate::community::SERVER_ROOT_SCOPE_HEX, community.root_epoch);
        crate::db::community::delete_epoch_key(&cid_hex, root, past.0).unwrap();
        assert_eq!(all_texts_in(&relay, &held(), &general).await, vec!["after"], "without the past root, only what came after");
        // A device that held it publishes the Channel's plane there.
        crate::db::community::store_epoch_key(&cid_hex, root, past.0, &community.community_root).unwrap();
        let ch = held().channel(&general).unwrap().clone();
        let (owed, scanned) = owed_history(&relay, &held(), &ch).await;
        assert_eq!((owed.iter().map(|(e, _)| *e).collect::<Vec<_>>(), scanned), (vec![past], Some(past.0)));
        assert!(publish_history(&relay, &held(), &general, owed).await.unwrap());
        follow_control(&relay, &held()).await.unwrap();
        let ch = held().channel(&general).unwrap().clone();
        assert!(owed_history(&relay, &held(), &ch).await.0.is_empty(), "published once, nothing more is owed");
        crate::db::community::delete_epoch_key(&cid_hex, root, past.0).unwrap();
        assert_eq!(all_texts_in(&relay, &held(), &general).await, vec!["before", "after"], "the published plane reads for a member who never held its root");
        // A catch-up reads it too, whole, while this device hasn't: a Channel whose every post
        // predates the rotation isn't left empty until someone scrolls.
        let unread: Vec<PublicKey> = held().channel(&general).unwrap().published_history().iter().map(|(_, g)| g.pk()).collect();
        let live = Some((held().root_epoch, None));
        let (got, ..) = fetch_channel_history_since_epoch(&relay, &held(), &general, 50, 8, None, None, crate::community::transport::Evidence::Quorum, |_, _, _| true, |_| Default::default(), live, &[]).await.unwrap();
        assert!(!got.iter().any(|f| f.event.opened().rumor.content == "before"), "a catch-up reads the live epoch");
        let (got, ..) = fetch_channel_history_since_epoch(&relay, &held(), &general, 50, 8, None, None, crate::community::transport::Evidence::Quorum, |_, _, _| true, |_| Default::default(), live, &unread).await.unwrap();
        assert!(got.iter().any(|f| f.event.opened().rumor.content == "before"), "and a published plane it never read");
    }

    #[tokio::test]
    async fn after_a_rotation_a_manager_publishes_the_closed_epoch_once() {
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Rotated", vec!["wss://r".into()], None).await.unwrap();
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        activate_roles_v2(&relay, &held(), crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
        follow_control(&relay, &held()).await.unwrap();
        let general = community.channels[0].id;
        send_chat_message_at(&relay, &held(), &general, "before", None, &[], vec![], now_ms() - 60_000).await.unwrap();
        let past = held().root_epoch;
        refound_community(&relay, &held(), &[]).await.unwrap();
        follow_control(&relay, &held()).await.unwrap();
        assert_eq!(access_duty(&relay, &held()).await.unwrap().history, 1);
        follow_control(&relay, &held()).await.unwrap();
        assert_eq!(held().channel(&general).unwrap().published_history().iter().map(|(e, _)| *e).collect::<Vec<_>>(), vec![past]);
        assert_eq!(access_duty(&relay, &held()).await.unwrap().history, 0, "nothing more to publish");
    }

    #[tokio::test]
    async fn a_past_root_the_channel_never_wrote_under_is_not_published() {
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Quiet", vec!["wss://r".into()], None).await.unwrap();
        let general = community.channels[0].id;
        refound_community(&relay, &community, &[]).await.unwrap();
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let (owed, scanned) = owed_history(&relay, &held, held.channel(&general).unwrap()).await;
        assert!(owed.is_empty());
        assert_eq!(scanned, Some(community.root_epoch.0), "looked at, so not again");
    }

    #[tokio::test]
    async fn a_private_channel_made_public_hands_what_it_said_while_private_to_every_member() {
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Opened", vec!["wss://r".into()], None).await.unwrap();
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        activate_roles_v2(&relay, &held(), crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
        follow_control(&relay, &held()).await.unwrap();
        let directory = create_private_channel(&relay, &held(), "directory").await.unwrap();
        send_chat_message_at(&relay, &held(), &directory, "the list", None, &[], vec![], now_ms() - 60_000).await.unwrap();
        let epoch = held().channel(&directory).unwrap().epoch;
        publicize_channel(&relay, &held(), &directory).await.unwrap();
        follow_control(&relay, &held()).await.unwrap();
        assert!(!held().channel(&directory).unwrap().private);
        let (cid_hex, ch_hex) = (crate::simd::hex::bytes_to_hex_32(&community.id().0), crate::simd::hex::bytes_to_hex_32(&directory.0));
        crate::db::community::delete_epoch_key(&cid_hex, &ch_hex, epoch.0).unwrap();
        assert_eq!(all_texts_in(&relay, &held(), &directory).await, vec!["the list"], "a member who never held its key reads it");
    }

    #[tokio::test]
    async fn a_channel_whose_everyone_reads_no_history_publishes_none() {
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Closed", vec!["wss://r".into()], None).await.unwrap();
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        activate_roles_v2(&relay, &held(), crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
        follow_control(&relay, &held()).await.unwrap();
        let directory = create_private_channel(&relay, &held(), "directory").await.unwrap();
        send_chat_message_at(&relay, &held(), &directory, "the list", None, &[], vec![], now_ms() - 60_000).await.unwrap();
        set_overwrite(&relay, &held(), directory.0, crate::community::roles::OverwriteTarget::Everyone, 0, crate::community::roles::Permissions::READ_MESSAGE_HISTORY).await.unwrap();
        follow_control(&relay, &held()).await.unwrap();
        publicize_channel(&relay, &held(), &directory).await.unwrap();
        follow_control(&relay, &held()).await.unwrap();
        assert!(held().channel(&directory).unwrap().published_history().is_empty());
        let (cid_hex, ch_hex) = (crate::simd::hex::bytes_to_hex_32(&community.id().0), crate::simd::hex::bytes_to_hex_32(&directory.0));
        let epoch = crate::db::community::held_epoch_keys(&cid_hex, &ch_hex).unwrap()[0].0;
        crate::db::community::delete_epoch_key(&cid_hex, &ch_hex, epoch.0).unwrap();
        assert!(all_texts_in(&relay, &held(), &directory).await.is_empty(), "history starts where reading did");
    }

    #[test]
    fn a_malformed_history_entry_names_nothing() {
        let good = channel_group_key(&[7u8; 32], &ChannelId([1u8; 32]), Epoch(2));
        let mut ch = crate::community::v2::community::ChannelV2 { id: ChannelId([1u8; 32]), name: "c".into(), private: false, key: None, epoch: Epoch(0), voice: None, meta_custom: None, meta_extra: Default::default(), writers: None, sealed: None };
        ch.meta_extra.insert(
            "history".into(),
            serde_json::json!([[2, crate::simd::hex::bytes_to_hex_32(&good.secret())], [3, "zz"], ["4", crate::simd::hex::bytes_to_hex_32(&good.secret())], [9007199254740992u64, crate::simd::hex::bytes_to_hex_32(&good.secret())], [5]]),
        );
        let got = ch.published_history();
        assert_eq!(got.len(), 1);
        assert_eq!((got[0].0, got[0].1.pk()), (Epoch(2), good.pk()));
    }

    #[tokio::test]
    async fn a_catch_up_after_a_rotation_reads_the_epochs_its_proof_never_read() {
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Moved", vec!["wss://r".into()], None).await.unwrap();
        let general = community.channels[0].id;
        let now = now_ms();
        for i in 0..5u64 {
            send_chat_message_at(&relay, &community, &general, &format!("old{i}"), None, &[], vec![], now - (60 - i) * 60_000).await.unwrap();
        }
        let between = refound_community(&relay, &community, &[]).await.unwrap();
        for i in 0..5u64 {
            send_chat_message_at(&relay, &between, &general, &format!("mid{i}"), None, &[], vec![], now - (20 - i) * 60_000).await.unwrap();
        }
        let rotated = refound_community(&relay, &between, &[]).await.unwrap();
        for i in 0..5u64 {
            send_chat_message_at(&relay, &rotated, &general, &format!("new{i}"), None, &[], vec![], now + (i + 1) * 60_000).await.unwrap();
        }
        crate::clock::shift_for_test(10 * 60_000);
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        assert_eq!(held.root_epoch, rotated.root_epoch);
        // Proven on the old epoch after all of it was said: a floor above every new message.
        let floor = Some((now + 8 * 60_000) / 1000);
        let walk = |past: Option<(Epoch, Option<u64>)>| {
            let (relay, held) = (&relay, &held);
            async move {
                let (got, ..) = fetch_channel_history_since_epoch(relay, held, &general, 10, 8, floor, None, crate::community::transport::Evidence::Quorum, |p, s, n| catch_up_pages_on(p, s, n, floor, |_| false), |_| Default::default(), past, &[]).await.unwrap();
                got.iter().map(|f| f.event.opened().rumor.content.clone()).collect::<std::collections::HashSet<_>>()
            }
        };
        assert!(walk(None).await.is_empty(), "the live epoch from the floor holds nothing");
        let got = walk(Some((community.root_epoch, None))).await;
        crate::clock::shift_for_test(0);
        assert!((0..5).all(|i| got.contains(&format!("new{i}")) && got.contains(&format!("mid{i}"))), "every epoch adopted since the proof is read whole");
        assert!(!got.iter().any(|t| t.starts_with("old")), "the proof's own epoch is read from its floor");
    }

    #[tokio::test]
    async fn a_proof_holds_only_for_the_epoch_it_was_read_under() {
        let (_tmp, _guard, _owner) = init_test_db();
        let chat = "ab".repeat(32);
        let now = 40 * 24 * 3600;
        crate::db::set_sql_setting(format!("history_proven:{chat}"), (now - 3600).to_string()).unwrap();
        assert_eq!(crate::history_gaps::proven_epoch(&chat), None, "a proof that names no epoch vouches for nothing");
        assert!(crate::history_gaps::floor(&chat, None, now).is_some_and(|f| f < now - 3600), "so the catch-up looks back as if unproven");
        crate::history_gaps::prove(&chat, now, 3);
        assert_eq!(crate::history_gaps::proven_epoch(&chat), Some(3));
        assert!(crate::history_gaps::proven(&chat, 3).is_some_and(|p| p < now));
        assert_eq!(crate::history_gaps::proven(&chat, 4), None, "a later epoch was read by nothing");
        assert!(crate::history_gaps::history_read(&chat).is_empty());
        crate::history_gaps::mark_history_read(&chat, ["aa".repeat(32)]);
        assert!(crate::history_gaps::history_read(&chat).contains(&"aa".repeat(32)));
    }

    #[tokio::test]
    async fn after_the_switch_an_unmarked_channel_edition_names_only_a_channel_that_stood() {
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Allow", vec!["wss://r".into()], None).await.unwrap();
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let old = create_public_channel(&relay, &held(), "old").await.unwrap();
        activate_roles_v2(&relay, &held(), crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
        follow_control(&relay, &held()).await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let listed = crate::db::community::get_community_roles(&cid_hex).unwrap().legacy_channels.expect("the switch lists what stood");
        assert!(listed.contains(&crate::simd::hex::bytes_to_hex_32(&old.0)) && listed.contains(&crate::simd::hex::bytes_to_hex_32(&community.channels[0].id.0)));
        let meta = |name: &str| serde_json::to_string(&control::ChannelMetadata { name: name.into(), private: false, voice: None, deleted: None, custom: None, extra: Default::default() }).unwrap();
        // One replayed from another Community never adds a Channel here.
        let foreign = ChannelId([0x6f; 32]);
        publish_fork(&[&relay], &held(), &owner, vsk::CHANNEL_METADATA, &foreign.0, 1, None, &meta("replayed"), None).await;
        follow_control(&relay, &held()).await.unwrap();
        assert!(held().channel(&foreign).is_none());
        // An unmarked edit of a Channel that stood still folds.
        let head = crate::db::community::get_edition_head(&cid_hex, &crate::simd::hex::bytes_to_hex_32(&old.0)).unwrap().unwrap();
        publish_fork(&[&relay], &held(), &owner, vsk::CHANNEL_METADATA, &old.0, head.0 + 1, Some(head.1), &meta("renamed"), None).await;
        follow_control(&relay, &held()).await.unwrap();
        assert_eq!(held().channel(&old).unwrap().name, "renamed");
        // A Channel made after the switch is marked, and stands.
        let new = create_public_channel(&relay, &held(), "new").await.unwrap();
        follow_control(&relay, &held()).await.unwrap();
        let joiner = verify_owner_root_and_reconcile(&relay, held()).await.unwrap().community;
        assert!(joiner.channel(&new).is_some() && joiner.channel(&old).is_some() && joiner.channel(&foreign).is_none(), "a fresh fold agrees");
        // Editing @everyone carries the list.
        set_everyone(&relay, &held(), crate::community::v2::roles::EVERYONE_DEFAULT & !Permissions::ADD_REACTIONS).await.unwrap();
        follow_control(&relay, &held()).await.unwrap();
        assert_eq!(crate::db::community::get_community_roles(&cid_hex).unwrap().legacy_channels, Some(listed.clone()));
        // A read that misses @everyone keeps the list, and a replay still finds no room.
        let everyone = crate::community::v2::derive::everyone_locator(community.id());
        let blind = Hiding { inner: &relay, group: control::ControlPlane::of(&held()).write_group().unwrap(), hide: Box::new(move |e| e.entity_id == everyone) };
        let other = ChannelId([0x70; 32]);
        publish_fork(&[&relay], &held(), &owner, vsk::CHANNEL_METADATA, &other.0, 1, None, &meta("replayed too"), None).await;
        follow_control(&blind, &held()).await.unwrap();
        assert!(held().channel(&other).is_none());
        assert_eq!(crate::db::community::get_community_roles(&cid_hex).unwrap().legacy_channels, Some(listed.clone()));
        // An @everyone edit with a shorter list changes nothing, for this reader or a fresh one.
        let head = crate::db::community::get_edition_head(&cid_hex, &crate::simd::hex::bytes_to_hex_32(&everyone)).unwrap().unwrap();
        let shorter: std::collections::BTreeSet<String> = listed.iter().filter(|c| **c != crate::simd::hex::bytes_to_hex_32(&old.0)).cloned().collect();
        let content = crate::community::v2::roles::everyone_content_json_with(crate::community::v2::roles::EVERYONE_DEFAULT, Some(&shorter));
        publish_marked(&relay, &held(), &owner, vsk::ROLE_V2, &everyone, head.0 + 1, Some(head.1), &content).await;
        follow_control(&relay, &held()).await.unwrap();
        assert_eq!(crate::db::community::get_community_roles(&cid_hex).unwrap().legacy_channels, Some(listed.clone()));
        // A list held from elsewhere gives way to the switch's own.
        let mut other = crate::db::community::get_community_roles(&cid_hex).unwrap();
        other.legacy_channels = Some(shorter.clone());
        crate::db::community::set_community_roles(&cid_hex, &other, 0).unwrap();
        follow_control(&relay, &held()).await.unwrap();
        assert_eq!(crate::db::community::get_community_roles(&cid_hex).unwrap().legacy_channels, Some(listed.clone()));
        // After a Refounding the switch itself isn't served: the list held stays, whatever a later
        // owner edition says.
        let newest = head.0 + 1;
        let carried = Hiding { inner: &relay, group: control::ControlPlane::of(&held()).write_group().unwrap(), hide: Box::new(move |e| e.entity_id == everyone && e.version < newest) };
        follow_control(&carried, &held()).await.unwrap();
        assert_eq!(crate::db::community::get_community_roles(&cid_hex).unwrap().legacy_channels, Some(listed.clone()));
        let mut forgot = crate::db::community::get_community_roles(&cid_hex).unwrap();
        forgot.legacy_channels = None;
        crate::db::community::set_community_roles(&cid_hex, &forgot, 0).unwrap();
        let floors: Floors = Default::default();
        let fresh = fold_authority(&held(), &fetch_control(&relay, &held()).await, &floors);
        assert_eq!(fresh.roles.legacy_channels, Some(listed), "the switch's own list");
    }

    #[tokio::test]
    async fn a_device_that_folded_legacy_edits_made_after_the_switch_lands_where_a_fresh_reader_does() {
        // An older client takes a legacy admin's unmarked edits made after the switch, and floors
        // them without an author. Once upgraded it must read what every other reader reads.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Upgrade", vec!["wss://r".into()], None).await.unwrap();
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        // What an older client publishes: unmarked, citing the Grant it holds.
        let legacy_edit = |signer: Keys, channel: ChannelId, name: &'static str, version: u64, prev: Option<[u8; 32]>| {
            let relay = &relay;
            async move {
                let community = held();
                let cite = cite_on_relay(relay, &community, &signer).await;
                let content = serde_json::to_string(&control::ChannelMetadata { name: name.into(), ..Default::default() }).unwrap();
                let rumor = control::build_edition_rumor(signer.public_key(), vsk::CHANNEL_METADATA, &channel.0, version, prev.as_ref(), &content, 1_000, cite.as_ref());
                let (wrap, _) = control::seal_control_edition(&rumor, &control::ControlPlane::of(&community).write_group().unwrap(), &signer, Timestamp::from_secs(1_000)).unwrap();
                relay.publish(&wrap, &community.relays).await.unwrap();
            }
        };
        let admin = Keys::generate();
        let ra = "a7".repeat(32);
        publish_role(&relay, &community, &owner, &role_at(&ra, "Admin", 1, Permissions::MANAGE_CHANNELS), 1).await;
        publish_grant(&relay, &community, &owner, &admin.public_key(), vec![ra.clone()], 1).await;
        // A Channel that stood before the switch, by an admin demoted since, stays where it's held.
        let demoted = Keys::generate();
        publish_grant(&relay, &community, &owner, &demoted.public_key(), vec![ra.clone()], 1).await;
        follow_control(&relay, &held()).await.unwrap();
        let early = ChannelId([0x5b; 32]);
        legacy_edit(demoted.clone(), early, "early", 1, None).await;
        follow_control(&relay, &held()).await.unwrap();
        assert!(held().channel(&early).is_some());
        publish_grant(&relay, &community, &owner, &demoted.public_key(), vec![], 2).await;
        follow_control(&relay, &held()).await.unwrap();
        assert!(held().channel(&early).is_some());
        activate_roles_v2(&relay, &held(), crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
        follow_control(&relay, &held()).await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let hex = |c: &ChannelId| crate::simd::hex::bytes_to_hex_32(&c.0);
        // So does one made after the switch, marked, by an admin whose standing went since.
        let later = Keys::generate();
        let gl = crate::community::v2::derive::grant_locator(community.id(), &later.public_key().to_bytes());
        let grant = |role_ids: Vec<String>| crate::community::v2::roles::grant_content_json(&MemberGrant { member: later.public_key().to_hex(), role_ids }).unwrap();
        publish_marked(&relay, &held(), &owner, vsk::GRANT, &gl, 1, None, &grant(vec![ra.clone()])).await;
        follow_control(&relay, &held()).await.unwrap();
        let stood = ChannelId([0x5c; 32]);
        let meta = serde_json::to_string(&control::ChannelMetadata { name: "stood".into(), ..Default::default() }).unwrap();
        publish_marked(&relay, &held(), &later, vsk::CHANNEL_METADATA, &stood.0, 1, None, &meta).await;
        follow_control(&relay, &held()).await.unwrap();
        assert!(held().channel(&stood).is_some());
        let (gv, gh) = crate::db::community::get_edition_head(&cid_hex, &crate::simd::hex::bytes_to_hex_32(&gl)).unwrap().unwrap();
        publish_marked(&relay, &held(), &owner, vsk::GRANT, &gl, gv + 1, Some(gh), &grant(vec![])).await;
        follow_control(&relay, &held()).await.unwrap();
        let lounge = create_public_channel(&relay, &held(), "lounge").await.unwrap();
        follow_control(&relay, &held()).await.unwrap();
        let (v, _) = crate::db::community::get_edition_head(&cid_hex, &hex(&lounge)).unwrap().unwrap();
        // That build chains to the owner's marked edition by its unsigned hash.
        let marked = fetch_control(&relay, &held()).await.into_iter().find(|e| e.entity_id == lounge.0 && e.version == v).unwrap();
        assert!(marked.binding.is_some());
        let unsigned = crate::community::version::edition_hash(&marked.entity_id, marked.version, marked.prev_hash.as_ref(), marked.content.as_bytes());
        let made = ChannelId([0x5a; 32]);
        legacy_edit(admin.clone(), lounge, "renamed", v + 1, Some(unsigned)).await;
        legacy_edit(admin.clone(), made, "made", 1, None).await;
        let editions = fetch_control(&relay, &held()).await;
        let edition = |c: &ChannelId, version: u64| editions.iter().find(|e| e.entity_id == c.0 && e.version == version).unwrap().clone();
        let (renamed, own) = (edition(&lounge, v + 1), edition(&made, 1));
        crate::db::community::set_edition_head_with_id(&cid_hex, &hex(&lounge), renamed.version, &renamed.self_hash, &renamed.inner_id).unwrap();
        crate::db::community::set_edition_head_with_id(&cid_hex, &hex(&made), own.version, &own.self_hash, &own.inner_id).unwrap();
        let mut old = held();
        old.channels.iter_mut().find(|c| c.id == lounge).unwrap().name = "renamed".into();
        let mut extra = old.channels[0].clone();
        extra.id = made;
        extra.name = "made".into();
        old.channels.push(extra);
        crate::db::community::save_community_v2(&old).unwrap();

        let joiner = verify_owner_root_and_reconcile(&relay, community.clone()).await.unwrap().community;
        assert_eq!(joiner.channel(&lounge).map(|c| c.name.as_str()), Some("lounge"), "a fresh reader refuses the rename");
        assert!(joiner.channel(&made).is_none(), "and the Channel");
        follow_control(&relay, &held()).await.unwrap();
        assert_eq!(held().channel(&lounge).map(|c| c.name.as_str()), Some("lounge"));
        assert!(held().channel(&made).is_none());
        assert!(held().channel(&early).is_some() && held().channel(&stood).is_some());
    }

    #[tokio::test]
    async fn a_manager_behind_on_the_ledger_never_forks_it() {
        use crate::community::roles::OverwriteTarget;
        use crate::community::v2::writers::{writer_address, Spell};
        let (bed, owner, x, community) = v2_bed_with_admin("Behind").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let general = held().channels[0].id;
        let m = Keys::generate();
        let plain = create_role_v2(&bed.relay, &held(), "Member", 0, 0).await.unwrap();
        set_member_roles(&bed.relay, &held(), &m.public_key(), vec![plain]).await.unwrap();
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(m.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
        // Another manager moves the ledger on; this device hasn't folded it.
        let eid = crate::community::v2::derive::writers_locator(community.id(), &general);
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let (_, head) = crate::db::community::get_edition_head(&cid_hex, &crate::simd::hex::bytes_to_hex_32(&eid)).unwrap().unwrap();
        let theirs = held().channel(&general).unwrap().writers.clone().unwrap().appended(now_ms(), Spell::Writer { epoch: Epoch(2), pk: writer_address(&[0x2b; 32], &general, Epoch(2)), root: Epoch(0), by: x.public_key().to_bytes(), certifier: None }).unwrap();
        let group = control::ControlPlane::of(&held()).write_group().unwrap();
        let cite = cite_on_relay(&bed.relay, &held(), &x).await;
        let secs = now_ms() / 1000;
        let rumor = control::build_edition_rumor_bound(x.public_key(), vsk::WRITERS, &eid, 2, Some(&head), &theirs.to_json(), secs, cite.as_ref(), Some(crate::community::v2::derive::edition_binding(community.id())));
        let (wrap, _) = control::seal_control_edition(&rumor, &group, &x, Timestamp::from_secs(secs)).unwrap();
        bed.relay.publish(&wrap, &held().relays).await.unwrap();
        // Cutting m reads the plane again first, finds the ledger moved, and leaves it.
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(m.public_key().to_hex()), 0, 0).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        let ledger = held().channel(&general).unwrap().writers.clone().unwrap();
        assert_eq!(ledger.live().map(|l| l.1), Some(x.public_key().to_bytes()), "the other manager's entry stands, not a fork over it");
        let _ = owner;
    }

    #[tokio::test]
    async fn sealed_details_open_with_the_key_of_their_own_epoch() {
        let (bed, _owner, _x, community) = v2_bed_with_admin("Epochs").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let ch = create_private_channel(&bed.relay, &held(), "vault").await.unwrap();
        let first = held().channel(&ch).unwrap().clone();
        let old_key = first.key.unwrap();
        // Rotate, then put a head sealed under the archived epoch over the rotator's reseal.
        let y = Keys::generate();
        let guests = create_role_v2(&bed.relay, &held(), "Guests", 0, 0).await.unwrap();
        set_member_roles(&bed.relay, &held(), &y.public_key(), vec![guests]).await.unwrap();
        set_overwrite(&bed.relay, &held(), ch.0, crate::community::roles::OverwriteTarget::Member(y.public_key().to_hex()), Permissions::VIEW_CHANNEL, 0).await.unwrap();
        set_overwrite(&bed.relay, &held(), ch.0, crate::community::roles::OverwriteTarget::Member(y.public_key().to_hex()), 0, 0).await.unwrap();
        assert!(held().channel(&ch).unwrap().epoch > first.epoch);
        let mut meta = first.metadata();
        meta.name = "old-epoch name".into();
        let prev = channel_head(&held(), &ch).unwrap();
        let content = control::seal_channel_metadata(&meta, channel_group_key(&old_key, &ch, first.epoch).conv_key(), first.epoch.0, prev.as_ref()).unwrap();
        publish_control_edition(&bed.relay, &held(), vsk::CHANNEL_METADATA, &ch.0, &content).await.unwrap();
        let mut stale = held();
        stale.channels.iter_mut().find(|c| c.id == ch).unwrap().sealed = None;
        crate::db::community::save_community_v2(&stale).unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        let read = held().channel(&ch).cloned().unwrap();
        assert_eq!((read.name.as_str(), read.sealed.as_ref().map(|s| s.open)), ("old-epoch name", Some(true)), "the archived key of its epoch opens it");
    }

    #[tokio::test]
    async fn a_seal_the_key_cant_open_keeps_what_was_read_and_is_sealed_again() {
        let (bed, owner, _x, community) = v2_bed_with_admin("Junk").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let ch = create_private_channel(&bed.relay, &held(), "keep").await.unwrap();
        let epoch = held().channel(&ch).unwrap().epoch;
        let first_head = channel_head(&held(), &ch).unwrap().unwrap();
        let first_content = held().channel(&ch).unwrap().sealed.clone().unwrap().raw;
        // Garbage under the live epoch, then the first seal replayed as a newer edition.
        for (why, content) in [
            ("garbage", serde_json::json!({ "private": true, "epoch": epoch.0.to_string(), "sealed": "AAAA" }).to_string()),
            ("a replay", first_content.clone()),
        ] {
            publish_control_edition(&bed.relay, &held(), vsk::CHANNEL_METADATA, &ch.0, &content).await.unwrap();
            follow_control(&bed.relay, &held()).await.unwrap();
            let read = held().channel(&ch).cloned().unwrap();
            assert!(read.sealed.as_ref().is_some_and(|s| s.junk) && read.name == "keep", "{why}: the details last read stay");
            follow_control(&bed.relay, &held()).await.unwrap();
            assert!(held().channel(&ch).unwrap().sealed.as_ref().is_some_and(|s| s.junk), "{why}: tried again, still junk");
            assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().resealed, 1, "{why}: and a manager seals them again");
            follow_control(&bed.relay, &held()).await.unwrap();
            assert!(held().channel(&ch).unwrap().sealed.as_ref().is_some_and(|s| s.open), "{why}");
        }
        assert_ne!(channel_head(&held(), &ch).unwrap(), Some(first_head));
        let _ = owner;
    }

    #[tokio::test]
    async fn a_sealed_head_on_a_public_channel_takes_it_private_and_keyless() {
        let (bed, _owner, _x, community) = v2_bed_with_admin("Public").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let general = held().channels[0].id;
        let content = serde_json::json!({ "private": true, "epoch": "1", "sealed": "AAAA" }).to_string();
        publish_control_edition(&bed.relay, &held(), vsk::CHANNEL_METADATA, &general.0, &content).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        let ch = held().channel(&general).cloned().unwrap();
        assert!(ch.private && ch.key.is_none() && ch.sealed.is_some(), "made private, it waits for its key rotation");
        assert!(held().channel_read_coords(&ch).is_empty(), "and is never read or sent at the public plane meanwhile");
    }

    #[tokio::test]
    async fn history_pages_two_busy_addresses_without_a_gap() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, _m) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Pages2", bed.relays.clone(), None).await.unwrap();
        activate_roles_v2(&bed.relay, &community, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
        follow_control(&bed.relay, &community).await.unwrap();
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let general = held().channels[0].id;
        let now = now_ms();
        // Read-address posts spread over the last day, then writer posts packed in the last hour.
        for i in 0..15u64 {
            send_chat_message_at(&bed.relay, &held(), &general, &format!("open {i}"), None, &[], vec![], now - 86_400_000 + i * 3_600_000).await.unwrap();
        }
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
        for i in 0..15u64 {
            send_chat_message_at(&bed.relay, &held(), &general, &format!("writer {i}"), None, &[], vec![], now - 3_600_000 + i * 60_000 + 60_000).await.unwrap();
        }
        let got = fetch_channel_history(&bed.relay, &held(), &general, 10, 10, None, None, crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await.unwrap();
        let posts = got.iter().filter(|f| matches!(f.event, ChatEvent::Message { .. })).count();
        assert_eq!(posts, 30, "both addresses page down without skipping either");
    }

    #[tokio::test]
    async fn a_slow_clock_never_closes_a_window_on_posts_already_made() {
        use crate::community::roles::OverwriteTarget;
        let (bed, _owner, _x, community) = v2_bed_with_admin("Clock").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let general = held().channels[0].id;
        // Someone whose clock runs ahead posted "two minutes from now".
        let ahead = now_ms() + 120_000;
        send_chat_message_at(&bed.relay, &held(), &general, "from a fast clock", None, &[], vec![], ahead).await.unwrap();
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
        let entry = held().channel(&general).unwrap().writers.as_ref().unwrap().entries[0].at;
        assert!(entry > ahead, "the window opens after the newest post held");
    }

    #[tokio::test]
    async fn a_writers_blob_vouches_for_nobody() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, _x, community) = v2_bed_with_admin("Vouch").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let general = held().channels[0].id;
        let (w, w2) = (Keys::generate(), Keys::generate());
        let plain = create_role_v2(&bed.relay, &held(), "Member", 0, 0).await.unwrap();
        set_member_roles(&bed.relay, &held(), &w.public_key(), vec![plain.clone()]).await.unwrap();
        set_member_roles(&bed.relay, &held(), &w2.public_key(), vec![plain]).await.unwrap();
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
        publish_overwrite_raw(&bed.relay, &held(), general.0, OverwriteTarget::Member(w2.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await;
        follow_control(&bed.relay, &held()).await.unwrap();
        let (live, pk) = held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap();
        act_as(&w);
        deliver_on_plane(&bed.relay, &held(), &general, crate::community::v2::writers::writer_rekey_scope(&general), live, Some(pk), &[0x99; 32], &[w2.public_key()]).await.unwrap();
        act_as(&owner.keys);
        assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().writers.delivered, 1, "a writer's blob at w2's locator still leaves w2 owed");
    }

    #[tokio::test]
    async fn a_ledger_head_its_signer_lost_standing_for_is_kept() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, x, community) = v2_bed_with_admin("Kept").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let general = held().channels[0].id;
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
        act_as(&x);
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, 0).await.unwrap();
        act_as(&owner.keys);
        follow_control(&bed.relay, &held()).await.unwrap();
        let minted = held().channel(&general).unwrap().writers.clone().unwrap();
        assert!(minted.entries.len() == 2 && !minted.restricted(), "x reopened what the owner restricted");
        // x's standing goes with nothing sealing what x did.
        publish_grant(&bed.relay, &held(), &owner.keys, &x.public_key(), vec![], 2).await;
        follow_control(&bed.relay, &held()).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        assert_eq!(held().channel(&general).unwrap().writers, Some(minted), "what the ledger recorded stays recorded");
    }

    #[tokio::test]
    async fn a_caller_paging_from_its_oldest_row_misses_nothing() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, _m) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Frontier", bed.relays.clone(), None).await.unwrap();
        activate_roles_v2(&bed.relay, &community, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
        follow_control(&bed.relay, &community).await.unwrap();
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let general = held().channels[0].id;
        let now = now_ms();
        for i in 0..15u64 {
            send_chat_message_at(&bed.relay, &held(), &general, &format!("open {i}"), None, &[], vec![], now - 86_400_000 + i * 3_600_000).await.unwrap();
        }
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
        let opened = held().channel(&general).unwrap().writers.as_ref().unwrap().entries[0].at;
        for i in 0..15u64 {
            send_chat_message_at(&bed.relay, &held(), &general, &format!("writer {i}"), None, &[], vec![], opened + i * 1_000 + 1_000).await.unwrap();
        }
        // The writers' posts are dated just ahead; read once they are due.
        crate::clock::shift_for_test(60_000);
        let mut seen = std::collections::HashSet::new();
        let mut until = None;
        for _ in 0..12 {
            let page = fetch_channel_history(&bed.relay, &held(), &general, 10, 1, None, until, crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await.unwrap();
            let fresh: Vec<&FetchedEvent> = page.iter().filter(|f| matches!(f.event, ChatEvent::Message { .. }) && seen.insert(f.event.opened().rumor_id)).collect();
            let Some(oldest) = page.iter().map(|f| f.event.opened().at_ms).min() else { break };
            if fresh.is_empty() && until == Some(oldest / 1000) {
                break;
            }
            until = Some(oldest / 1000);
        }
        crate::clock::shift_for_test(0);
        assert_eq!(seen.len(), 30, "one page at a time from its oldest row, every post comes");
    }

    #[tokio::test]
    async fn a_writers_ledger_needs_manage_channels_and_the_mark() {
        use crate::community::v2::writers::{writer_address, Ledger, Spell};
        let (bed, owner, x, community) = v2_bed_with_admin("Ledger").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let general = held().channels[0].id;
        let eid = crate::community::v2::derive::writers_locator(community.id(), &general);
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let head = || crate::db::community::get_edition_head(&cid_hex, &crate::simd::hex::bytes_to_hex_32(&eid)).unwrap().map(|h| h.1);
        // publish_marked dates an edition at 2_000 + version seconds.
        let at = |version: u64| (2_000 + version) * 1000;
        let mint = |base: &Ledger, at: u64, n: u8, by: &Keys| {
            let epoch = base.next_epoch().unwrap();
            base.appended(at, Spell::Writer { epoch, pk: writer_address(&[n; 32], &general, epoch), root: Epoch(0), by: by.public_key().to_bytes(), certifier: None }).unwrap()
        };
        let empty = Ledger::new(&general);
        let plain = create_role_v2(&bed.relay, &held(), "Member", 0, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
        let nobody = Keys::generate();
        set_member_roles(&bed.relay, &held(), &nobody.public_key(), vec![plain]).await.unwrap();
        publish_marked(&bed.relay, &held(), &nobody, vsk::WRITERS, &eid, 1, None, &mint(&empty, at(1), 1, &nobody).to_json()).await;
        follow_control(&bed.relay, &held()).await.unwrap();
        assert!(held().channel(&general).unwrap().writers.is_none(), "a member without Manage Channels moves nothing");
        let group = control::ControlPlane::of(&held()).write_group().unwrap();
        let rumor = control::build_edition_rumor(owner.keys.public_key(), vsk::WRITERS, &eid, 1, None, &mint(&empty, 2_100_000, 2, &owner.keys).to_json(), 2_100, None);
        let (wrap, _) = control::seal_control_edition(&rumor, &group, &owner.keys, Timestamp::from_secs(2_100)).unwrap();
        bed.relay.publish(&wrap, &held().relays).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        assert!(held().channel(&general).unwrap().writers.is_none(), "a new kind is read marked only");
        // A first edition holds one entry, or it could close the read address over the past.
        let backdated = mint(&empty, at(1) - 1_000_000, 6, &x).appended(at(1), Spell::Open).unwrap();
        publish_marked(&bed.relay, &held(), &x, vsk::WRITERS, &eid, 1, None, &backdated.to_json()).await;
        follow_control(&bed.relay, &held()).await.unwrap();
        assert!(held().channel(&general).unwrap().writers.is_none(), "a first edition with history");
        // And an entry dated past this reader's horizon waits.
        let ahead = mint(&empty, now_ms() + 2 * 3_600_000, 7, &x);
        let group = control::ControlPlane::of(&held()).write_group().unwrap();
        let cite = cite_on_relay(&bed.relay, &held(), &x).await;
        let secs = ahead.entries[0].at / 1000;
        let rumor = control::build_edition_rumor_bound(x.public_key(), vsk::WRITERS, &eid, 1, None, &ahead.to_json(), secs, cite.as_ref(), Some(crate::community::v2::derive::edition_binding(community.id())));
        let (wrap, _) = control::seal_control_edition(&rumor, &group, &x, Timestamp::from_secs(secs)).unwrap();
        bed.relay.publish(&wrap, &held().relays).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        assert!(held().channel(&general).unwrap().writers.is_none(), "a far-future ledger");
        let first = mint(&empty, at(1), 3, &x);
        publish_marked(&bed.relay, &held(), &x, vsk::WRITERS, &eid, 1, None, &first.to_json()).await;
        follow_control(&bed.relay, &held()).await.unwrap();
        assert_eq!(held().channel(&general).unwrap().writers, Some(first.clone()), "a channel manager's ledger stands");

        // Successors that break the ledger's rules never fold: the head it had stays.
        let other = Ledger::new(&ChannelId([0x05; 32])).appended(at(2), Spell::Open).unwrap();
        let foreign_minter = first.appended(at(2), Spell::Writer { epoch: Epoch(2), pk: writer_address(&[4; 32], &general, Epoch(2)), root: Epoch(0), by: owner.keys.public_key().to_bytes(), certifier: None }).unwrap();
        for (why, content) in [
            ("another channel's", other.to_json()),
            ("malformed", r#"{"channel":"00"}"#.to_string()),
            ("rewriting what it carries", mint(&empty, at(2), 9, &x).to_json()),
            ("a writer entry another signed", foreign_minter.to_json()),
            ("dated an hour from its edition", first.appended(at(2) + 3_600_000, Spell::Open).unwrap().to_json()),
            ("two entries at once", first.appended(at(2), Spell::Open).unwrap().appended(at(2), Spell::Writer { epoch: Epoch(2), pk: writer_address(&[5; 32], &general, Epoch(2)), root: Epoch(0), by: x.public_key().to_bytes(), certifier: None }).unwrap().to_json()),
        ] {
            publish_marked(&bed.relay, &held(), &x, vsk::WRITERS, &eid, 2, head(), &content).await;
            follow_control(&bed.relay, &held()).await.unwrap();
            assert_eq!(held().channel(&general).unwrap().writers, Some(first.clone()), "{why}");
        }
        // Nor one whose entry is dated before the one it follows.
        let mut early: serde_json::Value = serde_json::from_str(&first.appended(at(2), Spell::Open).unwrap().to_json()).unwrap();
        early["ledger"][1]["at"] = serde_json::json!(at(1) - 1_000);
        publish_marked(&bed.relay, &held(), &x, vsk::WRITERS, &eid, 2, head(), &early.to_string()).await;
        follow_control(&bed.relay, &held()).await.unwrap();
        assert_eq!(held().channel(&general).unwrap().writers, Some(first.clone()), "dated before the entry it follows");
        // A manager's root beside the chain, with the longer history: a reader that holds the
        // chain keeps it, a fresh one takes the longer, and with its signer's standing gone, the first.
        let y = Keys::generate();
        let mods = create_role_v2(&bed.relay, &held(), "Mod", 0, Permissions::MANAGE_CHANNELS | crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
        set_member_roles(&bed.relay, &held(), &y.public_key(), vec![mods]).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        let beside = mint(&first, at(2), 8, &y);
        publish_marked(&bed.relay, &held(), &y, vsk::WRITERS, &eid, 2, Some([0x3c; 32]), &beside.to_json()).await;
        follow_control(&bed.relay, &held()).await.unwrap();
        assert_eq!(held().channel(&general).unwrap().writers, Some(first.clone()), "a dangling predecessor");
        let fresh = verify_owner_root_and_reconcile(&bed.relay, community.clone()).await.unwrap();
        assert!(fresh.writers.iter().any(|(_, content, ..)| *content == beside.to_json()), "a fresh fold takes the longer history");
        publish_grant(&bed.relay, &held(), &owner.keys, &y.public_key(), vec![], 2).await;
        follow_control(&bed.relay, &held()).await.unwrap();
        let fresh = verify_owner_root_and_reconcile(&bed.relay, community.clone()).await.unwrap();
        assert!(fresh.writers.iter().any(|(_, content, ..)| *content == first.to_json()), "with its signer's standing gone, the first stands");
        let second = first.appended(at(2), Spell::Open).unwrap();
        publish_marked(&bed.relay, &held(), &x, vsk::WRITERS, &eid, 2, head(), &second.to_json()).await;
        follow_control(&bed.relay, &held()).await.unwrap();
        assert_eq!(held().channel(&general).unwrap().writers, Some(second.clone()), "one that carries it forward moves it on");

        // A fresh joiner folds the ledger from the join walk itself.
        let joiner = verify_owner_root_and_reconcile(&bed.relay, community.clone()).await.unwrap();
        assert!(joiner.writers.iter().any(|(c, content, ..)| *c == crate::simd::hex::bytes_to_hex_32(&general.0) && *content == second.to_json()));
    }

    /// The texts of a channel's posts its writers' rules don't stand behind, oldest first: what a
    /// device that manages the channel keeps marked.
    async fn marked_texts<T: Transport + ?Sized>(relay: &T, community: &CommunityV2, channel: &ChannelId) -> Vec<String> {
        fetch_channel_history(relay, community, channel, 100, 8, None, Some(now_ms() / 1000 + 3600), crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default())
            .await
            .unwrap()
            .iter()
            .filter(|f| matches!(f.event, ChatEvent::Message { .. }) && f.event.opened().held)
            .map(|f| f.event.opened().rumor.content.clone())
            .collect()
    }

    fn sorted(mut v: Vec<String>) -> Vec<String> {
        v.sort();
        v
    }

    /// A writer certificate for `writer` at `epoch` of `channel`, from the certifier this device minted.
    fn cert_for(community: &CommunityV2, channel: &ChannelId, epoch: Epoch, writer: &PublicKey) -> [u8; 64] {
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let secret = crate::db::community::held_epoch_key(&cid_hex, &crate::community::v2::writers::certifier_scope(channel), epoch.0).unwrap().unwrap();
        crate::community::v2::writers::sign_writer_cert(&secret, &crate::community::v2::writers::cert_digest(&community.id().0, &channel.0, epoch, &writer.to_bytes())).unwrap()
    }

    /// [`publish_marked`], returning the edition's hash.
    async fn publish_marked_hash(relay: &MemoryRelay, community: &CommunityV2, signer: &Keys, vsk_code: &str, eid: &[u8; 32], version: u64, prev: Option<[u8; 32]>, content: &str) -> [u8; 32] {
        let group = control::ControlPlane::of(community).write_group().unwrap();
        let cite = cite_on_relay(relay, community, signer).await;
        let binding = Some(crate::community::v2::derive::edition_binding(community.id()));
        let rumor = control::build_edition_rumor_bound(signer.public_key(), vsk_code, eid, version, prev.as_ref(), content, 2_000 + version, cite.as_ref(), binding);
        let (wrap, _) = control::seal_control_edition(&rumor, &group, signer, Timestamp::from_secs(2_000 + version)).unwrap();
        relay.publish(&wrap, &community.relays).await.unwrap();
        control::open_control_edition(&wrap, &group).unwrap().0.self_hash
    }

    #[tokio::test]
    async fn the_longest_ledger_history_takes_every_reader() {
        use crate::community::v2::writers::{writer_address, Ledger, Spell};
        let (bed, owner, x, community) = v2_bed_with_admin("Longest").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let general = held().channels[0].id;
        let eid = crate::community::v2::derive::writers_locator(community.id(), &general);
        let at = |version: u64| (2_000 + version) * 1000;
        let mint = |base: &Ledger, at: u64, n: u8, by: &Keys| {
            let epoch = base.next_epoch().unwrap();
            base.appended(at, Spell::Writer { epoch, pk: writer_address(&[n; 32], &general, epoch), root: Epoch(0), by: by.public_key().to_bytes(), certifier: None }).unwrap()
        };
        // x's chain, three long, against the owner's lone first edition: rank settles only a tie.
        let first = mint(&Ledger::new(&general), at(1), 1, &x);
        let h1 = publish_marked_hash(&bed.relay, &held(), &x, vsk::WRITERS, &eid, 1, None, &first.to_json()).await;
        let second = first.appended(at(2), Spell::Open).unwrap();
        let h2 = publish_marked_hash(&bed.relay, &held(), &x, vsk::WRITERS, &eid, 2, Some(h1), &second.to_json()).await;
        let third = mint(&second, at(3), 3, &x);
        publish_marked(&bed.relay, &held(), &x, vsk::WRITERS, &eid, 3, Some(h2), &third.to_json()).await;
        publish_marked(&bed.relay, &held(), &owner.keys, vsk::WRITERS, &eid, 1, None, &mint(&Ledger::new(&general), at(1), 9, &owner.keys).to_json()).await;
        // A first edition is version 1: one that names no predecessor higher up roots nothing.
        publish_marked(&bed.relay, &held(), &owner.keys, vsk::WRITERS, &eid, 7, None, &mint(&Ledger::new(&general), at(7), 7, &owner.keys).to_json()).await;
        follow_control(&bed.relay, &held()).await.unwrap();
        assert_eq!(held().channel(&general).unwrap().writers, Some(third.clone()));
        let fresh = verify_owner_root_and_reconcile(&bed.relay, community.clone()).await.unwrap();
        assert!(fresh.writers.iter().any(|(_, content, ..)| *content == third.to_json()), "a fresh reader takes the same");
        // After a Refounding, the head it carried outlasts a first edition made after it.
        let carried_ch = create_public_channel(&bed.relay, &held(), "carried").await.unwrap();
        let eid2 = crate::community::v2::derive::writers_locator(community.id(), &carried_ch);
        let mint2 = |base: &Ledger, at: u64, n: u8, by: &Keys| {
            let epoch = base.next_epoch().unwrap();
            base.appended(at, Spell::Writer { epoch, pk: writer_address(&[n; 32], &carried_ch, epoch), root: Epoch(0), by: by.public_key().to_bytes(), certifier: None }).unwrap()
        };
        let head = mint2(&mint2(&Ledger::new(&carried_ch), at(1), 1, &owner.keys), at(9), 2, &owner.keys);
        let hc = publish_marked_hash(&bed.relay, &held(), &owner.keys, vsk::WRITERS, &eid2, 9, Some([0x5a; 32]), &head.to_json()).await;
        let grown = head.appended(at(10), Spell::Open).unwrap();
        publish_marked(&bed.relay, &held(), &owner.keys, vsk::WRITERS, &eid2, 10, Some(hc), &grown.to_json()).await;
        publish_marked(&bed.relay, &held(), &x, vsk::WRITERS, &eid2, 1, None, &mint2(&Ledger::new(&carried_ch), at(1), 8, &x).to_json()).await;
        let fresh = verify_owner_root_and_reconcile(&bed.relay, held()).await.unwrap();
        assert!(fresh.writers.iter().any(|(_, content, ..)| *content == grown.to_json()));
    }

    #[tokio::test]
    async fn a_post_dated_far_ahead_never_dates_a_ledger_entry() {
        use crate::community::roles::OverwriteTarget;
        let (bed, _owner, _x, community) = v2_bed_with_admin("Ahead").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let general = held().channels[0].id;
        let tomorrow = now_ms() + 86_400_000;
        send_chat_message_at(&bed.relay, &held(), &general, "from tomorrow", None, &[], vec![], tomorrow).await.unwrap();
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
        let ledger = held().channel(&general).unwrap().writers.clone().expect("restricted");
        assert!(ledger.entries[0].at < tomorrow, "a post's date is no clock");
        let fresh = verify_owner_root_and_reconcile(&bed.relay, community.clone()).await.unwrap();
        assert!(fresh.writers.iter().any(|(_, content, ..)| *content == ledger.to_json()), "another reader folds it");
    }

    #[tokio::test]
    async fn a_manager_after_a_fast_clock_publishes_what_readers_take() {
        use crate::community::roles::OverwriteTarget;
        use crate::community::v2::writers::{writer_address, Ledger, Spell};
        let (bed, owner, x, community) = v2_bed_with_admin("Skew").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let general = held().channels[0].id;
        let eid = crate::community::v2::derive::writers_locator(community.id(), &general);
        // x restricts with a clock half an hour fast.
        publish_overwrite_raw(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await;
        let fast = now_ms() + 1_800_000;
        let ledger = Ledger::new(&general).appended(fast, Spell::Writer { epoch: Epoch(1), pk: writer_address(&[0x21; 32], &general, Epoch(1)), root: Epoch(0), by: x.public_key().to_bytes(), certifier: None }).unwrap();
        let group = control::ControlPlane::of(&held()).write_group().unwrap();
        let cite = cite_on_relay(&bed.relay, &held(), &x).await;
        let rumor = control::build_edition_rumor_bound(x.public_key(), vsk::WRITERS, &eid, 1, None, &ledger.to_json(), fast / 1000, cite.as_ref(), Some(crate::community::v2::derive::edition_binding(community.id())));
        let (wrap, _) = control::seal_control_edition(&rumor, &group, &x, Timestamp::from_secs(fast / 1000)).unwrap();
        bed.relay.publish(&wrap, &held().relays).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        assert_eq!(held().channel(&general).unwrap().writers, Some(ledger));
        // The owner reopens it straight after.
        act_as(&owner.keys);
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, Permissions::SEND_MESSAGES, 0).await.unwrap();
        let reopened = held().channel(&general).unwrap().writers.clone().unwrap();
        assert!(!reopened.restricted() && reopened.entries.len() == 2);
        let fresh = verify_owner_root_and_reconcile(&bed.relay, community.clone()).await.unwrap();
        assert!(fresh.writers.iter().any(|(_, content, ..)| *content == reopened.to_json()), "another reader folds it");
        let mine = fetch_control(&bed.relay, &held()).await.into_iter().find(|e| e.vsk == vsk::WRITERS && e.author == owner.keys.public_key()).unwrap();
        assert!(mine.created_at >= fast / 1000, "dated with the entry it carries");
        let query = Query { kinds: vec![stream::KIND_WRAP], authors: vec![group.pk_hex()], limit: Some(500), ..Default::default() };
        let ahead = bed.relay.fetch(&query, &held().relays).await.unwrap().iter().filter(|w| w.created_at.as_secs() > now_ms() / 1000 + 1).count();
        assert_eq!(ahead, 1, "x's own is the one wrap dated ahead for a relay to refuse");
    }

    #[tokio::test]
    async fn a_ledger_this_device_cant_chain_from_is_never_published_over() {
        use crate::community::roles::OverwriteTarget;
        let (bed, _owner, _x, community) = v2_bed_with_admin("Unchained").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let general = held().channels[0].id;
        let w = Keys::generate();
        set_member_roles(&bed.relay, &held(), &w.public_key(), vec![create_role_v2(&bed.relay, &held(), "Member", 0, 0).await.unwrap()]).await.unwrap();
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
        let ledger = held().channel(&general).unwrap().writers.clone().unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let eid_hex = crate::simd::hex::bytes_to_hex_32(&crate::community::v2::derive::writers_locator(community.id(), &general));
        // The head this device would chain from isn't the ledger it holds.
        crate::db::community::set_edition_head(&cid_hex, &eid_hex, 7, &[0x42; 32]).unwrap();
        let before = fetch_control(&bed.relay, &held()).await.iter().filter(|e| e.vsk == vsk::WRITERS).count();
        let scope = crate::community::v2::writers::writer_rekey_scope(&general);
        let delivered = fetch_plane_deliveries(&bed.relay, &held(), &general, scope).await.unwrap().len();
        // Cutting w takes a mint: none goes out, not even its deliveries; nor does a reopen.
        let _ = set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), 0, 0).await;
        let _ = set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, 0).await;
        assert_eq!(fetch_control(&bed.relay, &held()).await.iter().filter(|e| e.vsk == vsk::WRITERS).count(), before, "nothing readers would refuse goes out");
        assert_eq!(fetch_plane_deliveries(&bed.relay, &held(), &general, scope).await.unwrap().len(), delivered, "nor a key for one");
        assert_eq!(held().channel(&general).unwrap().writers, Some(ledger));
    }

    #[tokio::test]
    async fn the_switch_refuses_more_channels_than_it_can_list() {
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let crowd = |name: &'static str, total: usize| {
            let relay = &relay;
            async move {
                let community = create_community(relay, name, vec!["wss://r".into()], None).await.unwrap();
                let mut crowded = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
                let general = crowded.channels[0].clone();
                for i in 1..total {
                    let mut ch = general.clone();
                    ch.id = ChannelId(crate::community::random_32());
                    ch.name = format!("c{i}");
                    crowded.channels.push(ch);
                }
                crate::db::community::save_community_v2(&crowded).unwrap();
                crowded
            }
        };
        let max = crate::community::v2::roles::MAX_LEGACY_CHANNELS;
        let full = crowd("Full", max).await;
        activate_roles_v2(&relay, &full, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
        follow_control(&relay, &full).await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&full.id().0);
        assert_eq!(crate::db::community::get_community_roles(&cid_hex).unwrap().legacy_channels.map(|l| l.len()), Some(max), "every one listed");
        let crowded = crowd("Crowded", max + 1).await;
        let err = activate_roles_v2(&relay, &crowded, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap_err();
        assert!(err.contains("at most"), "{err}");
        assert!(!fetch_authority(&relay, &crowded).await.activated, "nothing switched");
    }

    #[tokio::test]
    async fn a_reader_builds_on_the_ledger_it_holds_when_a_window_misses_it() {
        use crate::community::v2::writers::{writer_address, Ledger, Spell};
        let (bed, owner, _x, community) = v2_bed_with_admin("Anchored").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let general = held().channels[0].id;
        let eid = crate::community::v2::derive::writers_locator(community.id(), &general);
        let at = |version: u64| (2_000 + version) * 1000;
        let first = Ledger::new(&general).appended(at(1), Spell::Writer { epoch: Epoch(1), pk: writer_address(&[1; 32], &general, Epoch(1)), root: Epoch(0), by: owner.keys.public_key().to_bytes(), certifier: None }).unwrap();
        let h1 = publish_marked_hash(&bed.relay, &held(), &owner.keys, vsk::WRITERS, &eid, 1, None, &first.to_json()).await;
        let second = first.appended(at(2), Spell::Open).unwrap();
        let h2 = publish_marked_hash(&bed.relay, &held(), &owner.keys, vsk::WRITERS, &eid, 2, Some(h1), &second.to_json()).await;
        follow_control(&bed.relay, &held()).await.unwrap();
        assert_eq!(held().channel(&general).unwrap().writers, Some(second.clone()));
        let third = second.appended(at(3), Spell::Writer { epoch: Epoch(2), pk: writer_address(&[2; 32], &general, Epoch(2)), root: Epoch(0), by: owner.keys.public_key().to_bytes(), certifier: None }).unwrap();
        publish_marked(&bed.relay, &held(), &owner.keys, vsk::WRITERS, &eid, 3, Some(h2), &third.to_json()).await;
        // A read that serves the first edition and the newest, not the one this reader holds.
        let window = Hiding { inner: &bed.relay, group: control::ControlPlane::of(&held()).write_group().unwrap(), hide: Box::new(move |e| e.self_hash == h2) };
        follow_control(&window, &held()).await.unwrap();
        assert_eq!(held().channel(&general).unwrap().writers, Some(third));
    }

    /// Refuses Control Plane publishes after the first `allow`: a relay that goes away mid-change.
    struct RefusesControl<'a> {
        inner: &'a MemoryRelay,
        control: String,
        allow: std::sync::atomic::AtomicUsize,
        tried: std::sync::atomic::AtomicUsize,
    }
    #[async_trait::async_trait]
    impl Transport for RefusesControl<'_> {
        async fn fetch_plane(&self, plane: &Keys, query: &Query, relays: &[String]) -> Result<crate::community::transport::PlaneFetch, String> {
            self.inner.fetch_plane(plane, query, relays).await
        }
        #[allow(deprecated)] // fetch_update, see next_send_ms
        async fn publish(&self, e: &Event, r: &[String]) -> Result<(), String> {
            if e.pubkey.to_hex() == self.control {
                self.tried.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            }
            if e.pubkey.to_hex() == self.control && self.allow.fetch_update(std::sync::atomic::Ordering::SeqCst, std::sync::atomic::Ordering::SeqCst, |n| n.checked_sub(1)).is_err() {
                return Err("refused".into());
            }
            self.inner.publish(e, r).await
        }
        async fn publish_durable(&self, e: &Event, r: &[String]) -> Result<(), String> {
            self.publish(e, r).await
        }
        async fn fetch(&self, q: &Query, r: &[String]) -> Result<Vec<Event>, String> {
            self.inner.fetch(q, r).await
        }
    }

    #[tokio::test]
    async fn a_change_whose_ledger_failed_to_publish_is_finished_by_the_next_pass() {
        use crate::community::roles::OverwriteTarget;
        let (bed, _owner, _x, community) = v2_bed_with_admin("Unfinished").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let general = held().channels[0].id;
        assert!(access_duty_due(community.id(), false));
        assert!(!access_duty_due(community.id(), false), "not again within the period");
        // The overwrite lands; the ledger edition after it doesn't.
        let flaky = RefusesControl { inner: &bed.relay, control: control::ControlPlane::of(&held()).write_group().unwrap().pk_hex(), allow: 1.into(), tried: 0.into() };
        assert!(set_overwrite(&flaky, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.is_err());
        assert!(!held().channel(&general).unwrap().restricted());
        assert!(access_duty_due(community.id(), false), "making the change again would move nothing, so the duty runs next pass");
        follow_control(&bed.relay, &held()).await.unwrap();
        assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().writers.moved, 1);
        assert!(held().channel(&general).unwrap().restricted());
    }

    #[tokio::test]
    async fn a_backstop_on_a_roster_read_before_the_change_stands_down() {
        use crate::community::roles::OverwriteTarget;
        let (bed, _owner, _x, community) = v2_bed_with_admin("Stale").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let general = held().channels[0].id;
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let stale = crate::db::community::get_community_roles(&cid_hex).unwrap();
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
        let ledger = held().channel(&general).unwrap().writers.clone().unwrap();
        assert_eq!(writing::backstop_on(&bed.relay, &held(), &general, &stale).await.unwrap(), writing::Backstop::StoodDown, "a roster from before the restrict reopens nothing");
        assert_eq!(held().channel(&general).unwrap().writers, Some(ledger));
    }

    #[tokio::test]
    async fn a_backstop_that_fails_waits_like_one_that_acted() {
        use crate::community::roles::OverwriteTarget;
        let (bed, _owner, _x, community) = v2_bed_with_admin("Fails").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let general = held().channels[0].id;
        publish_overwrite_raw(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await;
        follow_control(&bed.relay, &held()).await.unwrap();
        let refusing = RefusesControl { inner: &bed.relay, control: control::ControlPlane::of(&held()).write_group().unwrap().pk_hex(), allow: 0.into(), tried: 0.into() };
        let scope = crate::community::v2::writers::writer_rekey_scope(&general);
        let delivered = || async { fetch_plane_deliveries(&bed.relay, &held(), &general, scope).await.unwrap().len() };
        let _ = access_duty(&refusing, &held()).await;
        assert_eq!(delivered().await, 0, "a ledger the relays refuse sends nothing after it");
        assert!(!held().channel(&general).unwrap().restricted());
        let _ = access_duty(&refusing, &held()).await;
        assert_eq!(delivered().await, 0, "and the next pass waits too");
    }

    #[tokio::test]
    async fn an_edit_from_an_old_read_keeps_a_rename_that_landed_since() {
        let (bed, owner, x, community) = v2_bed_with_admin("Merge").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let general = held().channels[0].id;
        let stale = held();
        act_as(&x);
        let mut renamed = held().channel(&general).unwrap().metadata();
        renamed.name = "renamed".into();
        edit_channel_metadata(&bed.relay, &held(), &general, &renamed).await.unwrap();
        act_as(&owner.keys);
        follow_control(&bed.relay, &held()).await.unwrap();
        // The owner's edit was built from what it read before the rename.
        let mut topic = stale.channel(&general).unwrap().metadata();
        topic.extra.insert("topic".into(), "news".into());
        edit_channel_metadata(&bed.relay, &stale, &general, &topic).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        let ch = held().channel(&general).cloned().unwrap();
        assert_eq!((ch.name.as_str(), ch.meta_extra.get("topic").and_then(|t| t.as_str())), ("renamed", Some("news")));
        // A client's own fields merge one by one too.
        let stale = held();
        act_as(&x);
        let mut theirs = held().channel(&general).unwrap().metadata();
        theirs.custom.get_or_insert_with(Default::default).insert("a".into(), 1.into());
        edit_channel_metadata(&bed.relay, &held(), &general, &theirs).await.unwrap();
        act_as(&owner.keys);
        follow_control(&bed.relay, &held()).await.unwrap();
        let mut mine = stale.channel(&general).unwrap().metadata();
        mine.custom.get_or_insert_with(Default::default).insert("b".into(), 2.into());
        edit_channel_metadata(&bed.relay, &stale, &general, &mine).await.unwrap();
        let custom = held().channel(&general).unwrap().meta_custom.clone().unwrap_or_default();
        assert_eq!((custom.get("a"), custom.get("b")), (Some(&1.into()), Some(&2.into())));
    }

    #[tokio::test]
    async fn a_ledger_nobody_can_fold_blocks_nobody() {
        use crate::community::roles::OverwriteTarget;
        use crate::community::v2::writers::{writer_address, Ledger, Spell};
        let (bed, owner, x, community) = v2_bed_with_admin("Refused").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let general = held().channels[0].id;
        let eid = crate::community::v2::derive::writers_locator(community.id(), &general);
        // x's ledger is dated past this reader's horizon: served, and refused whole.
        let ahead = now_ms() + 2 * 3_600_000;
        let ledger = Ledger::new(&general).appended(ahead, Spell::Writer { epoch: Epoch(1), pk: writer_address(&[3; 32], &general, Epoch(1)), root: Epoch(0), by: x.public_key().to_bytes(), certifier: None }).unwrap();
        let group = control::ControlPlane::of(&held()).write_group().unwrap();
        let cite = cite_on_relay(&bed.relay, &held(), &x).await;
        let rumor = control::build_edition_rumor_bound(x.public_key(), vsk::WRITERS, &eid, 1, None, &ledger.to_json(), ahead / 1000, cite.as_ref(), Some(crate::community::v2::derive::edition_binding(community.id())));
        let (wrap, _) = control::seal_control_edition(&rumor, &group, &x, Timestamp::from_secs(now_ms() / 1000)).unwrap();
        bed.relay.publish(&wrap, &held().relays).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        assert!(held().channel(&general).unwrap().writers.is_none());
        // A member without Manage Channels blocks nothing with one of their own.
        let two = create_public_channel(&bed.relay, &held(), "two").await.unwrap();
        let m = Keys::generate();
        set_member_roles(&bed.relay, &held(), &m.public_key(), vec![create_role_v2(&bed.relay, &held(), "Member", 0, 0).await.unwrap()]).await.unwrap();
        let eid_two = crate::community::v2::derive::writers_locator(community.id(), &two);
        let theirs = Ledger::new(&two).appended(2_001_000, Spell::Open).unwrap();
        publish_marked(&bed.relay, &held(), &m, vsk::WRITERS, &eid_two, 1, None, &theirs.to_json()).await;
        follow_control(&bed.relay, &held()).await.unwrap();
        act_as(&x);
        set_overwrite(&bed.relay, &held(), two.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
        assert!(held().channel(&two).unwrap().restricted());
        // Nor does a ledger nobody can fold yet: a manager restricts over it.
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
        act_as(&owner.keys);
        let mine = held().channel(&general).unwrap().writers.clone().expect("restricted");
        let fresh = verify_owner_root_and_reconcile(&bed.relay, community.clone()).await.unwrap();
        assert!(fresh.writers.iter().any(|(_, content, ..)| *content == mine.to_json()), "another reader takes it");
    }

    #[tokio::test]
    async fn a_settled_race_stays_settled_when_ranks_change() {
        use crate::community::v2::writers::{writer_address, Ledger, Spell};
        let (bed, _owner, x, community) = v2_bed_with_admin("Settled").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let general = held().channels[0].id;
        let eid = crate::community::v2::derive::writers_locator(community.id(), &general);
        let y = Keys::generate();
        let mods = create_role_v2(&bed.relay, &held(), "Mod", 0, Permissions::MANAGE_CHANNELS | crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
        set_member_roles(&bed.relay, &held(), &y.public_key(), vec![mods]).await.unwrap();
        let at = |version: u64| (2_000 + version) * 1000;
        let mint = |at: u64, n: u8, by: &Keys| Ledger::new(&general).appended(at, Spell::Writer { epoch: Epoch(1), pk: writer_address(&[n; 32], &general, Epoch(1)), root: Epoch(0), by: by.public_key().to_bytes(), certifier: None }).unwrap();
        // x and y restrict at once; x's goes on.
        publish_marked(&bed.relay, &held(), &y, vsk::WRITERS, &eid, 1, None, &mint(at(1), 2, &y).to_json()).await;
        let xs = mint(at(1), 1, &x);
        let h1 = publish_marked_hash(&bed.relay, &held(), &x, vsk::WRITERS, &eid, 1, None, &xs.to_json()).await;
        let grown = xs.appended(at(2), Spell::Open).unwrap();
        publish_marked(&bed.relay, &held(), &x, vsk::WRITERS, &eid, 2, Some(h1), &grown.to_json()).await;
        follow_control(&bed.relay, &held()).await.unwrap();
        assert_eq!(held().channel(&general).unwrap().writers, Some(grown.clone()));
        // x steps down, its decisions sealed: y now outranks it, and nothing flips.
        set_member_roles(&bed.relay, &held(), &x.public_key(), vec![]).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        assert_eq!(held().channel(&general).unwrap().writers, Some(grown.clone()));
        let fresh = verify_owner_root_and_reconcile(&bed.relay, community.clone()).await.unwrap();
        assert!(fresh.writers.iter().any(|(_, content, ..)| *content == grown.to_json()), "a fresh reader takes the longer history");
    }

    #[tokio::test]
    async fn an_edition_on_a_hidden_held_head_must_extend_it() {
        use crate::community::v2::writers::{writer_address, Ledger, Spell};
        let (bed, owner, _x, community) = v2_bed_with_admin("Extend").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let general = held().channels[0].id;
        let eid = crate::community::v2::derive::writers_locator(community.id(), &general);
        let at = |version: u64| (2_000 + version) * 1000;
        let first = Ledger::new(&general).appended(at(1), Spell::Writer { epoch: Epoch(1), pk: writer_address(&[1; 32], &general, Epoch(1)), root: Epoch(0), by: owner.keys.public_key().to_bytes(), certifier: None }).unwrap();
        let h1 = publish_marked_hash(&bed.relay, &held(), &owner.keys, vsk::WRITERS, &eid, 1, None, &first.to_json()).await;
        let second = first.appended(at(2), Spell::Open).unwrap();
        let h2 = publish_marked_hash(&bed.relay, &held(), &owner.keys, vsk::WRITERS, &eid, 2, Some(h1), &second.to_json()).await;
        follow_control(&bed.relay, &held()).await.unwrap();
        // Names the held head, but drops what it carried.
        let skipped = first.appended(at(3), Spell::Writer { epoch: Epoch(2), pk: writer_address(&[2; 32], &general, Epoch(2)), root: Epoch(0), by: owner.keys.public_key().to_bytes(), certifier: None }).unwrap();
        publish_marked(&bed.relay, &held(), &owner.keys, vsk::WRITERS, &eid, 3, Some(h2), &skipped.to_json()).await;
        let window = Hiding { inner: &bed.relay, group: control::ControlPlane::of(&held()).write_group().unwrap(), hide: Box::new(move |e| e.self_hash == h2) };
        let _ = follow_control(&window, &held()).await;
        assert_eq!(held().channel(&general).unwrap().writers, Some(second));
    }

    #[tokio::test]
    async fn one_channel_that_cant_settle_never_holds_back_the_rest() {
        let (bed, _owner, _x, community) = v2_bed_with_admin("Isolated").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let general = held().channels[0].id;
        let other = create_public_channel(&bed.relay, &held(), "other").await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        // general's ledger head isn't one this device can chain from.
        let eid_hex = crate::simd::hex::bytes_to_hex_32(&crate::community::v2::derive::writers_locator(community.id(), &general));
        crate::db::community::set_edition_head(&cid_hex, &eid_hex, 7, &[0x42; 32]).unwrap();
        let _ = set_everyone(&bed.relay, &held(), crate::community::v2::roles::EVERYONE_DEFAULT & !Permissions::SEND_MESSAGES).await;
        let restricted = |id: &ChannelId| held().channel(id).unwrap().restricted();
        assert!(!restricted(&general));
        assert!(restricted(&other), "the next channel still moved");
    }

    #[tokio::test]
    async fn a_post_signed_with_a_leaked_writer_key_is_marked() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, x, community) = v2_bed_with_admin("Leaked").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let general = held().channels[0].id;
        let (w, n) = (Keys::generate(), Keys::generate());
        let plain = create_role_v2(&bed.relay, &held(), "Member", 0, 0).await.unwrap();
        set_member_roles(&bed.relay, &held(), &w.public_key(), vec![plain.clone()]).await.unwrap();
        set_member_roles(&bed.relay, &held(), &n.public_key(), vec![plain]).await.unwrap();
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
        let (live, secret, writer) = writing::live_writer(&held(), held().channel(&general).unwrap()).unwrap();
        let read = channel_group_key(&community.community_root, &general, community.root_epoch);
        let signed = GroupKey::from_parts(writer.keys().clone(), read.conv_key().clone());
        // w hands the key to n, who may not post; both post with it.
        act_as(&w);
        deliver_on_plane(&bed.relay, &held(), &general, crate::community::v2::writers::writer_rekey_scope(&general), live, Some(writer.pk().to_bytes()), &secret, &[n.public_key()]).await.unwrap();
        act_as(&owner.keys);
        let ws = cert_for(&held(), &general, live, &w.public_key());
        post_certified(&bed.relay, &held(), &w, &general, &signed, community.root_epoch, Some((live, Some(ws))), "from the writer", now_ms()).await;
        // A post carries its proof: a writer's without one is no different from a stranger's.
        post_raw(&bed.relay, &held(), &w, &general, &signed, community.root_epoch, Some(live), "w without its certificate", now_ms()).await;
        post_raw(&bed.relay, &held(), &n, &general, &signed, community.root_epoch, Some(live), "through a leaked key", now_ms()).await;
        // A manager's post stands wherever it lands, certificate or not.
        act_as(&x);
        post_raw(&bed.relay, &held(), &x, &general, &read, community.root_epoch, None, "a manager on an old client", now_ms()).await;
        act_as(&owner.keys);
        // Nor does another writer's certificate vouch for n.
        post_certified(&bed.relay, &held(), &n, &general, &signed, community.root_epoch, Some((live, Some(ws))), "with w's certificate", now_ms()).await;
        let marked = vec!["through a leaked key".to_string(), "w without its certificate".to_string(), "with w's certificate".to_string()];
        assert_eq!(sorted(marked_texts(&bed.relay, &held(), &general).await), marked);
        // A post carries its proof: a certificate n is handed later vouches for nothing n posted before.
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(n.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
        publish_overwrite_raw(&bed.relay, &held(), general.0, OverwriteTarget::Member(n.public_key().to_hex()), 0, 0).await;
        follow_control(&bed.relay, &held()).await.unwrap();
        assert_eq!(sorted(marked_texts(&bed.relay, &held(), &general).await), marked);
    }

    #[tokio::test]
    async fn a_manager_holding_the_certifier_lets_a_writer_in_without_a_new_key() {
        use crate::community::roles::OverwriteTarget;
        let (bed, _owner, x, community) = v2_bed_with_admin("Certifier").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let general = held().channels[0].id;
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let w = Keys::generate();
        set_member_roles(&bed.relay, &held(), &w.public_key(), vec![create_role_v2(&bed.relay, &held(), "Member", 0, 0).await.unwrap()]).await.unwrap();
        // x joined.
        let gb = crate::community::v2::derive::guestbook_group_key(&held().community_root, community.id(), held().root_epoch);
        let join = guestbook::build_join_rumor(x.public_key(), None, now_ms());
        let (wrap, _) = guestbook::seal_guestbook_rumor(&join, &gb, &x, Timestamp::from_secs(now_ms() / 1000)).unwrap();
        bed.relay.publish(&wrap, &held().relays).await.unwrap();
        sync_guestbook(&bed.relay, &held()).await.unwrap();
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
        // x's own device: it holds neither the owner's certifier nor the key until it collects them.
        let scopes = [crate::community::v2::writers::certifier_scope(&general), crate::community::v2::writers::secret_scope(&general), crate::community::v2::writers::minted_scope(&general)];
        for scope in &scopes {
            crate::db::community::delete_epoch_key(&cid_hex, scope, 1).unwrap();
        }
        act_as(&x);
        follow_control(&bed.relay, &held()).await.unwrap();
        collect_writers(&bed.relay, &held()).await.unwrap();
        let certifier = crate::db::community::held_epoch_key(&cid_hex, &scopes[0], 1).unwrap().expect("a manager is handed the certifier");
        assert_eq!(crate::community::v2::writers::certifier_of(&certifier), held().channel(&general).unwrap().writers.as_ref().unwrap().certifier(Epoch(1)));
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
        assert_eq!(held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0, Epoch(1), "no new key");
        let scope = crate::community::v2::writers::writer_rekey_scope(&general);
        let ledger = held().channel(&general).unwrap().writers.clone().unwrap();
        let handed = fetch_plane_deliveries(&bed.relay, &held(), &general, scope).await.unwrap().into_iter().filter(|d| d.deliverer == x.public_key()).flat_map(|d| d.certs).find(|(who, _)| *who == w.public_key().to_bytes());
        assert!(handed.is_some_and(|(_, c)| ledger.certifies(&community.id().0, Epoch(1), &w.public_key().to_bytes(), &c)), "x certified w");
    }

    #[tokio::test]
    async fn two_managers_restricting_at_once_settle_on_one_ledger() {
        use crate::community::roles::OverwriteTarget;
        use crate::community::v2::writers::{writer_address, Ledger, Spell};
        let (bed, owner, x, community) = v2_bed_with_admin("Race").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let general = held().channels[0].id;
        let eid = crate::community::v2::derive::writers_locator(community.id(), &general);
        act_as(&x);
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
        act_as(&owner.keys);
        let x_first = held().channel(&general).unwrap().writers.clone().unwrap();
        // The owner's backstop minted too before x's edition reached it.
        let at = now_ms();
        let owners = Ledger::new(&general).appended(at, Spell::Writer { epoch: Epoch(1), pk: writer_address(&[0x0e; 32], &general, Epoch(1)), root: Epoch(0), by: owner.keys.public_key().to_bytes(), certifier: None }).unwrap();
        let group = control::ControlPlane::of(&held()).write_group().unwrap();
        let rumor = control::build_edition_rumor_bound(owner.keys.public_key(), vsk::WRITERS, &eid, 1, None, &owners.to_json(), at / 1000, None, Some(crate::community::v2::derive::edition_binding(community.id())));
        let (wrap, _) = control::seal_control_edition(&rumor, &group, &owner.keys, Timestamp::from_secs(at / 1000)).unwrap();
        bed.relay.publish(&wrap, &held().relays).await.unwrap();
        assert_ne!(x_first, owners);
        // The lower inner id wins, whoever signed it: what never changes settles the tie.
        let ids: Vec<([u8; 32], String)> = fetch_control(&bed.relay, &held()).await.into_iter().filter(|e| e.vsk == vsk::WRITERS).map(|e| (e.inner_id, e.content)).collect();
        let winner = ids.iter().min_by_key(|(id, _)| *id).map(|(_, c)| c.clone()).unwrap();
        let winner = Ledger::parse(&winner).unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        assert_eq!(held().channel(&general).unwrap().writers, Some(winner.clone()), "the device that held one converges on the winner");
        let fresh = verify_owner_root_and_reconcile(&bed.relay, community.clone()).await.unwrap();
        assert!(fresh.writers.iter().any(|(_, content, ..)| *content == winner.to_json()), "and a fresh reader takes the same");
        // Demoting x builds on the settled race, and takes back a certifier only if x minted the
        // epoch that won.
        let x_won = winner.live().map(|l| l.1) == Some(x.public_key().to_bytes());
        set_member_roles(&bed.relay, &held(), &x.public_key(), vec![]).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        let after = held().channel(&general).unwrap().writers.clone().unwrap();
        assert_eq!(after.entries[0], winner.entries[0]);
        assert_eq!(after.current_writer().unwrap().0, if x_won { Epoch(2) } else { Epoch(1) });
        let fresh = verify_owner_root_and_reconcile(&bed.relay, community.clone()).await.unwrap();
        assert!(fresh.writers.iter().any(|(_, content, ..)| *content == after.to_json()));
        // The ledger moves on from there.
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, 0).await.unwrap();
        let reopened = held().channel(&general).unwrap().writers.clone().unwrap();
        assert!(!reopened.restricted() && reopened.entries.len() == after.entries.len() + 1);
        let fresh = verify_owner_root_and_reconcile(&bed.relay, community.clone()).await.unwrap();
        assert!(fresh.writers.iter().any(|(_, content, ..)| *content == reopened.to_json()));
    }

    #[tokio::test]
    async fn a_ledger_out_of_line_moves_once_an_hour() {
        use crate::community::roles::OverwriteTarget;
        use crate::community::v2::writers::Spell;
        let (bed, _owner, x, community) = v2_bed_with_admin("Damped").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let general = held().channels[0].id;
        let eid = crate::community::v2::derive::writers_locator(community.id(), &general);
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        publish_overwrite_raw(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await;
        follow_control(&bed.relay, &held()).await.unwrap();
        assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().writers.moved, 1);
        // x's roster disagrees and reopens it.
        let ledger = held().channel(&general).unwrap().writers.clone().unwrap();
        let head = crate::db::community::get_edition_head(&cid_hex, &crate::simd::hex::bytes_to_hex_32(&eid)).unwrap().unwrap();
        let reopened = ledger.appended(now_ms(), Spell::Open).unwrap();
        let group = control::ControlPlane::of(&held()).write_group().unwrap();
        let cite = cite_on_relay(&bed.relay, &held(), &x).await;
        let rumor = control::build_edition_rumor_bound(x.public_key(), vsk::WRITERS, &eid, head.0 + 1, Some(&head.1), &reopened.to_json(), now_ms() / 1000, cite.as_ref(), Some(crate::community::v2::derive::edition_binding(community.id())));
        let (wrap, _) = control::seal_control_edition(&rumor, &group, &x, Timestamp::from_secs(now_ms() / 1000)).unwrap();
        bed.relay.publish(&wrap, &held().relays).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        assert!(!held().channel(&general).unwrap().restricted());
        assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().writers.moved, 0, "no ping-pong");
    }

    #[tokio::test]
    async fn a_junk_seal_opens_once_the_key_for_its_epoch_does() {
        let (bed, _owner, _x, community) = v2_bed_with_admin("Retry").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let ch = create_private_channel(&bed.relay, &held(), "keep").await.unwrap();
        let (key, epoch) = { let c = held().channel(&ch).cloned().unwrap(); (c.key.unwrap(), c.epoch) };
        let meta = control::ChannelMetadata { name: "renamed".into(), private: true, ..Default::default() };
        let prev = channel_head(&held(), &ch).unwrap();
        let content = control::seal_channel_metadata(&meta, channel_group_key(&key, &ch, epoch).conv_key(), epoch.0, prev.as_ref()).unwrap();
        publish_control_edition(&bed.relay, &held(), vsk::CHANNEL_METADATA, &ch.0, &content).await.unwrap();
        let set_key = |k: [u8; 32]| {
            let mut row = held();
            row.channels.iter_mut().find(|c| c.id == ch).unwrap().key = Some(k);
            crate::db::community::save_community_v2(&row).unwrap();
        };
        set_key([0x11; 32]);
        follow_control(&bed.relay, &held()).await.unwrap();
        assert!(held().channel(&ch).unwrap().sealed.as_ref().is_some_and(|s| s.junk), "a key that can't open it");
        set_key(key);
        follow_control(&bed.relay, &held()).await.unwrap();
        let read = held().channel(&ch).cloned().unwrap();
        assert_eq!((read.name.as_str(), read.sealed.as_ref().map(|s| (s.open, s.junk))), ("renamed", Some((true, false))));
    }

    #[tokio::test]
    async fn a_minter_who_cant_post_hands_on_the_key_it_minted() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, x, community) = v2_bed_with_admin("Minter").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let general = held().channels[0].id;
        let w = Keys::generate();
        let plain = create_role_v2(&bed.relay, &held(), "Member", 0, 0).await.unwrap();
        set_member_roles(&bed.relay, &held(), &w.public_key(), vec![plain]).await.unwrap();
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(x.public_key().to_hex()), 0, Permissions::SEND_MESSAGES).await.unwrap();
        act_as(&x);
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
        assert!(!can_post(&held(), &general), "x minted a key it may not post with");
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
        act_as(&owner.keys);
        let ledger = held().channel(&general).unwrap().writers.clone().unwrap();
        assert_eq!(ledger.current_writer().unwrap().0, Epoch(1), "no second mint for a writer gained");
        let scope = crate::community::v2::writers::writer_rekey_scope(&general);
        let plane = fetch_plane_deliveries(&bed.relay, &held(), &general, scope).await.unwrap();
        assert!(served_at(&plane, &w.public_key(), scope, Epoch(1), &|d| *d == x.public_key()), "the minter served them");
        assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().writers.cut, 0, "a manager holding what it minted is nobody to cut");
        // Demoted, what x decided stands, and the certifier x held is replaced by a fresh epoch.
        set_member_roles(&bed.relay, &held(), &x.public_key(), vec![]).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        assert!(held().channel(&general).unwrap().restricted());
        assert_eq!(held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0, Epoch(2));
        assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().writers, WriterDuty::default(), "nothing of x's left to take back");
    }

    #[tokio::test]
    async fn a_key_passed_on_lets_nobody_post_and_costs_no_new_epoch() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, _x, community) = v2_bed_with_admin("Passed").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let general = held().channels[0].id;
        let w = Keys::generate();
        set_member_roles(&bed.relay, &held(), &w.public_key(), vec![create_role_v2(&bed.relay, &held(), "Member", 0, 0).await.unwrap()]).await.unwrap();
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Member(w.public_key().to_hex()), Permissions::SEND_MESSAGES, 0).await.unwrap();
        let (live, secret, writer) = writing::live_writer(&held(), held().channel(&general).unwrap()).unwrap();
        // The writer hands the key to h, who may not post, and h hands it on to k.
        let (h, k) = (Keys::generate(), Keys::generate());
        set_member_roles(&bed.relay, &held(), &h.public_key(), vec![create_role_v2(&bed.relay, &held(), "Guest", 0, 0).await.unwrap()]).await.unwrap();
        let scope = crate::community::v2::writers::writer_rekey_scope(&general);
        act_as(&w);
        deliver_on_plane(&bed.relay, &held(), &general, scope, live, Some(writer.pk().to_bytes()), &secret, &[h.public_key()]).await.unwrap();
        act_as(&h);
        deliver_on_plane(&bed.relay, &held(), &general, scope, live, Some(writer.pk().to_bytes()), &secret, &[k.public_key()]).await.unwrap();
        act_as(&owner.keys);
        let read = channel_group_key(&community.community_root, &general, community.root_epoch);
        let signed = GroupKey::from_parts(writer.keys().clone(), read.conv_key().clone());
        post_raw(&bed.relay, &held(), &k, &general, &signed, community.root_epoch, Some(live), "through a passed key", now_ms()).await;
        assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().writers, WriterDuty::default(), "nobody to stop: a key without a certificate vouches for nothing");
        assert_eq!(held().channel(&general).unwrap().writers.as_ref().unwrap().current_writer().unwrap().0, live, "and no epoch spent on it");
        assert_eq!(marked_texts(&bed.relay, &held(), &general).await, vec!["through a passed key".to_string()]);
    }

    #[tokio::test]
    async fn a_role_that_opens_a_private_channel_its_granter_cant_read_is_refused() {
        let (bed, owner, x, community) = v2_bed_with_admin("Gatekeeper").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let ch = create_private_channel(&bed.relay, &held(), "staff").await.unwrap();
        let staff = create_role_v2(&bed.relay, &held(), "Staff", 0, 0).await.unwrap();
        set_overwrite(&bed.relay, &held(), ch.0, crate::community::roles::OverwriteTarget::Role(staff.clone()), Permissions::VIEW_CHANNEL, 0).await.unwrap();
        let key = held().channel(&ch).unwrap().key;
        let with_key = |k: Option<[u8; 32]>| {
            let mut c = held();
            c.channels.iter_mut().find(|c| c.id.0 == ch.0).unwrap().key = k;
            crate::db::community::save_community_v2(&c).unwrap();
        };
        let m = Keys::generate();
        // A manager of roles who isn't in the channel: the member would wait at its door.
        with_key(None);
        act_as(&x);
        let refused = set_member_roles(&bed.relay, &held(), &m.public_key(), vec![staff.clone()]).await.unwrap_err();
        assert!(refused.contains("opens a private channel you don't have access to"), "{refused}");
        let others = create_role_v2(&bed.relay, &held(), "Others", 0, 0).await.unwrap();
        set_member_roles(&bed.relay, &held(), &m.public_key(), vec![others.clone()]).await.unwrap();
        // A granter holding its key hands it over with the grant.
        act_as(&owner.keys);
        with_key(key);
        set_member_roles(&bed.relay, &held(), &m.public_key(), vec![others, staff]).await.unwrap();
    }

    #[tokio::test]
    async fn a_holder_delivers_on_the_access_plane_and_the_member_adopts_it() {
        let (bed, owner, x, community) = v2_bed_with_admin("Access").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let ch = create_private_channel(&bed.relay, &held(), "inner").await.unwrap();
        let readers = create_role_v2(&bed.relay, &held(), "Readers", 0, 0).await.unwrap();
        set_overwrite(&bed.relay, &held(), ch.0, crate::community::roles::OverwriteTarget::Role(readers.clone()), Permissions::VIEW_CHANNEL, 0).await.unwrap();
        let (m, d, f, stranger) = (Keys::generate(), Keys::generate(), Keys::generate(), Keys::generate());
        let key = held().channel(&ch).unwrap().key.unwrap();
        let epoch = held().channel(&ch).unwrap().epoch;
        let with_channel = |k: Option<[u8; 32]>, e: Epoch| {
            let mut c = held();
            let slot = c.channels.iter_mut().find(|x| x.id.0 == ch.0).unwrap();
            slot.key = k;
            slot.epoch = e;
            crate::db::community::save_community_v2(&c).unwrap();
        };
        // Granted by a client that delivers nothing with the grant, so only a holder's duty serves them.
        let quiet = NoAccessDeliveries(&bed.relay, access_group(&held(), &ch).pk());
        set_member_roles(&quiet, &held(), &m.public_key(), vec![readers.clone()]).await.unwrap();
        set_member_roles(&quiet, &held(), &d.public_key(), vec![readers.clone()]).await.unwrap();
        set_member_roles(&quiet, &held(), &f.public_key(), vec![readers]).await.unwrap();
        let others = create_role_v2(&bed.relay, &held(), "Others", 0, 0).await.unwrap();
        set_member_roles(&quiet, &held(), &stranger.public_key(), vec![others]).await.unwrap();
        crate::db::current_session().scoped::<AccessLedger, std::sync::Mutex<std::collections::HashSet<([u8; 32], u64, [u8; 32])>>>().lock().unwrap().clear();
        follow_control(&bed.relay, &held()).await.unwrap();
        let trusted = |pk: &PublicKey| *pk == owner.keys.public_key();
        let served = |pk: PublicKey| {
            let relay = &bed.relay;
            let c = held();
            async move { served_on_plane(&fetch_access_deliveries(relay, &c, &ch).await.unwrap(), &pk, &ch, c.channel(&ch).unwrap().epoch, &trusted) }
        };
        // Someone the channel doesn't let in stakes blobs at every member's locator first.
        with_channel(Some([0x99; 32]), epoch);
        act_as(&stranger);
        deliver_access(&bed.relay, &held(), &ch, &[m.public_key(), d.public_key(), f.public_key()]).await.unwrap();
        // An entitled member offers a key far past the channel's epoch.
        with_channel(Some([0x77; 32]), Epoch(epoch.0 + 1000));
        act_as(&f);
        deliver_access(&bed.relay, &held(), &ch, &[m.public_key()]).await.unwrap();
        with_channel(Some(key), epoch);
        act_as(&owner.keys);

        let blind = BreaksAfterPublish { inner: &bed.relay, broken: true.into() };
        assert!(access_duty(&blind, &held()).await.is_err(), "nothing goes out on a partial read");
        act_as(&x);
        assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().delivered, 0, "a holder the channel doesn't let in delivers nothing readers would take");
        act_as(&owner.keys);
        assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().delivered, 3, "a stranger's blobs serve nobody: every member is owed");
        assert!(served(m.public_key()).await && served(d.public_key()).await);
        assert!(!served(stranger.public_key()).await, "nobody the channel doesn't let in");
        assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().delivered, 0, "a served member is served once");
        // D, later banned, also serves M a key of D's own at the channel's epoch.
        with_channel(Some([0x66; 32]), epoch);
        act_as(&d);
        deliver_access(&bed.relay, &held(), &ch, &[m.public_key()]).await.unwrap();
        act_as(&owner.keys);

        // The member's own device, without the key; D is banned there.
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        crate::db::community::set_community_banlist(&cid_hex, &[d.public_key().to_hex()], 1).unwrap();
        with_channel(None, epoch);
        act_as(&m);
        assert_eq!(collect_access(&bed.relay, &held()).await.unwrap(), 1, "only the honest delivery: not the banned member's, nor one far ahead");
        assert_eq!(collect_access(&bed.relay, &held()).await.unwrap(), 0, "and once a session: re-parking would crowd out other candidates");
        crate::db::community::set_community_banlist(&cid_hex, &[], 2).unwrap();
        assert_eq!(absorb_parked_channel_keys(&held(), &crate::db::current_session()).len(), 1);
        assert_eq!(held().channel(&ch).unwrap().key, Some(key), "the delivered key is the channel's");
        act_as(&stranger);
        with_channel(None, epoch);
        assert_eq!(collect_access(&bed.relay, &held()).await.unwrap(), 0, "a member it doesn't let in finds nothing");
        act_as(&owner.keys);
        with_channel(Some(key), epoch);

        // A rotation that carries a member serves them; one that leaves out a member who held the
        // last epoch has cut them, whatever the roster still says.
        let readers = crate::db::community::get_community_roles(&cid_hex).unwrap().roles.iter().find(|r| r.name == "Readers").unwrap().role_id.clone();
        let (rider, fresh_member) = (Keys::generate(), Keys::generate());
        set_member_roles(&bed.relay, &held(), &rider.public_key(), vec![readers.clone()]).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
        rekey_channel_excluding(&bed.relay, &held(), &ch, &roster, &[], &[d.public_key()]).await.unwrap();
        set_member_roles(&bed.relay, &held(), &fresh_member.public_key(), vec![readers]).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().delivered, 0, "the rotation carried m and the rider, cut d, and the grant itself served the member entitled since");
        assert!(served(fresh_member.public_key()).await && !served(d.public_key()).await && !served(rider.public_key()).await);
    }

    #[tokio::test]
    async fn a_manager_cuts_a_holder_the_channel_no_longer_lets_in() {
        // A strip that rotated nothing (its author couldn't, or it came from another client)
        // leaves the member holding the key: a manager's duty is the backstop.
        let (bed, owner, x, community) = v2_bed_with_admin("Backstop").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let ch = create_private_channel(&bed.relay, &held(), "inner").await.unwrap();
        let readers = create_role_v2(&bed.relay, &held(), "Readers", 0, 0).await.unwrap();
        set_overwrite(&bed.relay, &held(), ch.0, crate::community::roles::OverwriteTarget::Role(readers.clone()), Permissions::VIEW_CHANNEL, 0).await.unwrap();
        let (m, kept) = (Keys::generate().public_key(), Keys::generate().public_key());
        set_member_roles(&bed.relay, &held(), &m, vec![readers.clone()]).await.unwrap();
        set_member_roles(&bed.relay, &held(), &kept, vec![readers]).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        rekey_channel_excluding(&bed.relay, &held(), &ch, &crate::db::community::get_community_roles(&cid_hex).unwrap(), &[], &[]).await.unwrap();
        // A member who joined, then whose strip lands with no rotation behind it.
        let (mut events, cursor) = crate::db::community::get_guestbook(&cid_hex).unwrap();
        events.push(guestbook::GuestbookEvent { epoch: Some(held().root_epoch.0), observed_at: None, rumor_id: [12u8; 32], entry: guestbook::GuestbookEntry::Join { member: m, invited_by: None, at_ms: now_ms() } });
        crate::db::community::set_guestbook(&cid_hex, &events, cursor).unwrap();
        publish_grant(&bed.relay, &held(), &owner.keys, &m, vec![], 2).await;
        follow_control(&bed.relay, &held()).await.unwrap();
        let epoch = held().channel(&ch).unwrap().epoch;
        act_as(&x);
        assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().cut, 0, "a manager who doesn't hold the channel's View delivers and cuts nothing");
        act_as(&owner.keys);
        act_as(&owner.keys);
        let done = access_duty(&bed.relay, &held()).await.unwrap();
        assert_eq!(done.cut, 1, "the holder the channel no longer lets in");
        let now = held().channel(&ch).unwrap().epoch;
        assert!(now > epoch, "the channel rotated");
        let minted = minting_rotations(&bed.relay, &held(), &ch, now).await.unwrap();
        let any = |_: &PublicKey| true;
        assert!(!rotation_carries(&minted, &any, &m, &ch, now), "without them");
        assert!(rotation_carries(&minted, &any, &kept, &ch, now), "and with whoever it still lets in");
        assert_eq!(access_duty(&bed.relay, &held()).await.unwrap(), AccessDuty::default(), "and then there is nothing left to do");
    }

    #[tokio::test]
    async fn a_member_cut_then_let_back_in_walks_through_the_cut_to_the_rotation_that_names_them() {
        let (bed, owner, _x, community) = v2_bed_with_admin("Back").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let ch = create_private_channel(&bed.relay, &held(), "inner").await.unwrap();
        let chan = crate::simd::hex::bytes_to_hex_32(&ch.0);
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let m = Keys::generate();
        let member = crate::community::roles::OverwriteTarget::Member(m.public_key().to_hex());
        set_overwrite(&bed.relay, &held(), ch.0, member.clone(), Permissions::VIEW_CHANNEL, Permissions::READ_MESSAGE_HISTORY).await.unwrap();
        let joined = held().channel(&ch).unwrap().epoch;
        let key = crate::db::community::held_epoch_key(&cid_hex, &chan, joined.0).unwrap().unwrap();
        set_overwrite(&bed.relay, &held(), ch.0, member.clone(), 0, Permissions::VIEW_CHANNEL).await.unwrap();
        set_overwrite(&bed.relay, &held(), ch.0, member, Permissions::VIEW_CHANNEL, Permissions::READ_MESSAGE_HISTORY).await.unwrap();
        let back = held().channel(&ch).unwrap().epoch;
        assert!(back.0 >= joined.0 + 2, "a cut, then the rotation that lets them back in");
        // Their device, holding the epoch they joined at.
        let mut c = held();
        let x = c.channels.iter_mut().find(|x| x.id.0 == ch.0).unwrap();
        (x.key, x.epoch) = (Some(key), joined);
        crate::db::community::save_community_v2(&c).unwrap();
        act_as(&m);
        for _ in 0..4 {
            if let Some(next) = follow_rekeys(&bed.relay, &held(), &crate::db::current_session()).await.unwrap().updated {
                crate::db::community::save_community_v2(&next).unwrap();
            }
        }
        let now = held().channel(&ch).cloned().expect("a cut keeps the channel known");
        assert_eq!((now.epoch, now.key.is_some()), (back, true), "and the walk reaches the epoch that names them");
        act_as(&owner.keys);
    }

    #[tokio::test]
    async fn a_view_grant_without_history_lets_them_in_at_a_fresh_epoch() {
        let (bed, owner, _x, community) = v2_bed_with_admin("Fresh").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let ch = create_private_channel(&bed.relay, &held(), "inner").await.unwrap();
        send_chat_message(&bed.relay, &held(), &ch, "before them", None, &[], vec![]).await.unwrap();
        let before = held().channel(&ch).unwrap().epoch;
        let (m, n) = (Keys::generate().public_key(), Keys::generate().public_key());
        let member = |pk: &PublicKey| crate::community::roles::OverwriteTarget::Member(pk.to_hex());
        set_overwrite(&bed.relay, &held(), ch.0, member(&m), Permissions::VIEW_CHANNEL, 0).await.unwrap();
        assert_eq!(held().channel(&ch).unwrap().epoch, before, "with history, the epoch they're handed is kept");
        let stale = held();
        set_overwrite(&bed.relay, &held(), ch.0, member(&n), Permissions::VIEW_CHANNEL, Permissions::READ_MESSAGE_HISTORY).await.unwrap();
        let after = held().channel(&ch).unwrap().epoch;
        access_duty(&bed.relay, &stale).await.unwrap();
        assert_eq!(held().channel(&ch).unwrap().epoch, after, "a duty that judged the epoch before the grant's rotation mints nothing over it");
        assert!(after > before, "without it, the grant mints the epoch they come in at");
        let any = |_: &PublicKey| true;
        assert!(rotation_carries(&minting_rotations(&bed.relay, &held(), &ch, after).await.unwrap(), &any, &n, &ch, after));
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
        let owner_hex = owner.keys.public_key().to_hex();
        let vends = |pk: &PublicKey| held().vendable_channels(&roster, Some(&owner_hex), Some(&pk.to_hex()), &[], &[]).iter().any(|c| c.id.0 == ch.0);
        assert!(vends(&m) && !vends(&n), "no bundle hands them an epoch");
        let access = crate::VectorCore.channel_access(&cid_hex, &crate::simd::hex::bytes_to_hex_32(&ch.0)).unwrap();
        let npub = |pk: &PublicKey| serde_json::json!(nostr_sdk::prelude::ToBech32::to_bech32(pk).unwrap());
        assert_eq!(access["members"].as_array().unwrap().len(), 2, "both overwrites let them in");
        assert!(access["members"].as_array().unwrap().contains(&npub(&n)));
        let handed = |pk: PublicKey, e: Epoch| {
            let (relay, c, o) = (&bed.relay, held(), owner.keys.public_key());
            async move { fetch_access_deliveries(relay, &c, &ch).await.unwrap().iter().any(|d| d.epoch == e && rekey::find_my_blob(&d.blobs, &o.to_bytes(), &pk.to_bytes(), rekey::RekeyScope::Channel(ch), e).is_some()) }
        };
        access_duty(&bed.relay, &held()).await.unwrap();
        assert!(!handed(n, before).await, "nor does the duty");
        assert_eq!(held().channel(&ch).unwrap().epoch, after, "and it has nothing left to mint for them");
        let key_at = |e: Epoch| crate::db::community::held_epoch_key(&cid_hex, &crate::simd::hex::bytes_to_hex_32(&ch.0), e.0).unwrap();
        let kept = key_at(after);
        rekey_channel_excluding(&bed.relay, &stale, &ch, &roster, &[], &[]).await.unwrap();
        assert_eq!(key_at(after), kept, "a rotation from an old copy never re-mints an epoch already held");
        assert_eq!(held().channel(&ch).unwrap().epoch, Epoch(after.0 + 1));
        let stale = held();
        set_overwrite(&bed.relay, &held(), ch.0, member(&m), 0, Permissions::VIEW_CHANNEL).await.unwrap();
        let cut = held().channel(&ch).unwrap().epoch;
        assert!(cut > stale.channel(&ch).unwrap().epoch, "the revoke rotated them out");
        access_duty(&bed.relay, &stale).await.unwrap();
        assert_eq!(held().channel(&ch).unwrap().epoch, cut, "nor does a duty that judged the epoch before that cut");
    }

    #[tokio::test]
    async fn read_message_history_hands_a_new_reader_the_past_read_only() {
        let (bed, owner, _x, community) = v2_bed_with_admin("History").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let ch = create_private_channel(&bed.relay, &held(), "inner").await.unwrap();
        let chan = crate::simd::hex::bytes_to_hex_32(&ch.0);
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        send_chat_message(&bed.relay, &held(), &ch, "early", None, &[], vec![]).await.unwrap();
        let first = held().channel(&ch).unwrap().epoch;
        rekey_channel_excluding(&bed.relay, &held(), &ch, &crate::db::community::get_community_roles(&cid_hex).unwrap(), &[], &[]).await.unwrap();
        send_chat_message(&bed.relay, &held(), &ch, "later", None, &[], vec![]).await.unwrap();
        let now = held().channel(&ch).unwrap().epoch;
        assert!(now > first);
        // Two readers join after the rotation; one is denied history in this channel.
        let readers = create_role_v2(&bed.relay, &held(), "Readers", 0, 0).await.unwrap();
        set_overwrite(&bed.relay, &held(), ch.0, crate::community::roles::OverwriteTarget::Role(readers.clone()), Permissions::VIEW_CHANNEL, 0).await.unwrap();
        let (m, n) = (Keys::generate(), Keys::generate());
        set_overwrite(&bed.relay, &held(), ch.0, crate::community::roles::OverwriteTarget::Member(n.public_key().to_hex()), 0, Permissions::READ_MESSAGE_HISTORY).await.unwrap();
        set_member_roles(&bed.relay, &held(), &m.public_key(), vec![readers.clone()]).await.unwrap();
        set_member_roles(&bed.relay, &held(), &n.public_key(), vec![readers]).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        assert_eq!(access_duty(&bed.relay, &held()).await.unwrap().delivered, 0, "the grants themselves served them");
        let blob_for = |who: PublicKey| {
            let (relay, c) = (&bed.relay, held());
            let owner_pk = owner.keys.public_key();
            async move {
                fetch_history_deliveries(relay, &c, &ch).await.unwrap().iter().any(|d| d.blobs.iter().any(|b| b.locator == rekey::history_locator(&owner_pk.to_bytes(), &who.to_bytes(), &ch, d.epoch)))
            }
        };
        assert!(blob_for(m.public_key()).await && !blob_for(n.public_key()).await, "history goes only to who may read it");
        // Someone the channel doesn't let in offers M an epoch nobody else did.
        let stranger = Keys::generate();
        let fake = rekey::HistoryView { address: [0x55; 32], conv_key: [0x66; 32] };
        let blob = rekey::build_history_blob_local(&stranger, &m.public_key(), &ch, Epoch(0), &fake).unwrap();
        let rumor = rekey::build_history_rumor(stranger.public_key(), &ch, Epoch(0), &[blob], now_ms() / 1000).unwrap();
        let (wrap, _) = rekey::seal_rekey_chunk(&rumor, &access_group(&held(), &ch), &stranger, Timestamp::now()).unwrap();
        bed.relay.publish(&wrap, &held().relays).await.unwrap();
        // And a holder sends N history N may not read.
        deliver_history(&bed.relay, &held(), &ch, &[n.public_key()]).await.unwrap();
        // A reader denied history is let in by a fresh epoch, which their grant minted.
        let rotated = held().channel(&ch).unwrap().epoch;
        assert!(rotated > now);
        // Each reader's own device: keyless where its fold left it, and no secret of the past epoch.
        let as_reader = |who: &Keys| {
            let mut c = held();
            let x = c.channels.iter_mut().find(|x| x.id.0 == ch.0).unwrap();
            (x.key, x.epoch) = (None, now);
            crate::db::community::save_community_v2(&c).unwrap();
            crate::db::get_write_connection_guard_static().unwrap()
                .execute("DELETE FROM community_epoch_keys WHERE community_id = ?1 AND scope_id IN (?2, ?3, ?4)", rusqlite::params![cid_hex, chan, format!("hist:{chan}"), format!("hista:{chan}")])
                .unwrap();
            act_as(who);
        };
        let texts = |c: CommunityV2| {
            let relay = &bed.relay;
            async move {
                let far = now_ms() / 1000 + 100;
                let got = fetch_channel_history(relay, &c, &ch, 50, 4, None, Some(far), crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await.unwrap();
                got.iter().filter_map(|e| match &e.event { chat::ChatEvent::Message { opened, .. } => Some(opened.rumor.content.clone()), _ => None }).collect::<Vec<_>>()
            }
        };
        as_reader(&m);
        assert_eq!(collect_access(&bed.relay, &held()).await.unwrap(), 1);
        absorb_parked_channel_keys(&held(), &crate::db::current_session());
        assert_eq!(texts(held()).await, vec!["later".to_string()], "the key alone opens only its own epoch");
        assert_eq!(collect_history(&bed.relay, &held()).await.unwrap(), 1, "the earlier epoch, read-only, and not the stranger's");
        assert_eq!(crate::db::community::history_views(&cid_hex, &chan).unwrap().iter().map(|(e, _)| *e).collect::<Vec<_>>(), vec![first]);
        assert!(crate::db::community::held_epoch_key(&cid_hex, &chan, first.0).unwrap().is_none(), "never its secret");
        assert_eq!(texts(held()).await, vec!["early".to_string(), "later".to_string()], "history reads back");
        // A catch-up that already proved the live epoch, as one run the moment the key landed has,
        // reads an epoch delivered after it only when that plane counts as unread.
        let proof = now_ms() / 1000;
        let view = PublicKey::from_slice(&crate::db::community::history_views(&cid_hex, &chan).unwrap()[0].1.address).unwrap();
        let caught = |unread: Vec<PublicKey>| {
            let (relay, c) = (&bed.relay, held());
            async move {
                let live = c.channel(&ch).unwrap().epoch;
                let (got, ..) = fetch_channel_history_since_epoch(relay, &c, &ch, 50, 2, Some(proof), None, crate::community::transport::Evidence::Quorum, |_, _, _| true, |_| Default::default(), Some((live, None)), &unread).await.unwrap();
                got.iter().any(|e| matches!(&e.event, chat::ChatEvent::Message { opened, .. } if opened.rumor.content == "early"))
            }
        };
        assert!(!caught(vec![]).await, "read from the proof, the delivered epoch is passed over");
        assert!(caught(vec![view]).await, "unread, it is read whole");
        assert_eq!(collect_history(&bed.relay, &held()).await.unwrap(), 0, "once");
        as_reader(&n);
        assert_eq!(collect_access(&bed.relay, &held()).await.unwrap(), 0, "never this epoch's key, which opens what came before them");
        let adopted = follow_rekeys(&bed.relay, &held(), &crate::db::current_session()).await.unwrap().updated.expect("the rotation names them");
        crate::db::community::save_community_v2(&adopted).unwrap();
        assert_eq!(held().channel(&ch).unwrap().epoch, rotated);
        assert_eq!(collect_history(&bed.relay, &held()).await.unwrap(), 0, "denied history, it takes none even when sent");
        assert!(texts(held()).await.is_empty(), "nothing from before their access");
        send_chat_message(&bed.relay, &held(), &ch, "after", None, &[], vec![]).await.unwrap();
        assert_eq!(texts(held()).await, vec!["after".to_string()], "history starts where access did");
        act_as(&owner.keys);
    }

    #[tokio::test]
    async fn a_timeout_counts_only_with_the_grant_it_cites() {
        let (bed, _owner, _x, community) = v2_bed_with_admin("Cited").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let mods = create_role_v2(&bed.relay, &held(), "Mods", 0, Permissions::MODERATE_MEMBERS).await.unwrap();
        let (y, m) = (Keys::generate(), Keys::generate().public_key());
        set_member_roles(&bed.relay, &held(), &y.public_key(), vec![mods]).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        act_as(&y);
        timeout_member(&bed.relay, &held(), &m, 600).await.unwrap();
        assert!(community_timeouts(&held()).unwrap().contains_key(&m), "a cited Timeout stands");
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let (mut events, cursor) = crate::db::community::get_guestbook(&cid_hex).unwrap();
        events.push(guestbook::GuestbookEvent {
            rumor_id: [9; 32],
            entry: guestbook::GuestbookEntry::Timeout { actor: y.public_key(), target: m, until_secs: 0, citation: None, at_ms: now_ms() + 1_000 },
            epoch: Some(held().root_epoch.0),
            observed_at: None,
        });
        crate::db::community::set_guestbook(&cid_hex, &events, cursor).unwrap();
        assert!(community_timeouts(&held()).unwrap().contains_key(&m), "an uncited lift lifts nothing");
    }

    fn nick_of(community: &CommunityV2, who: &PublicKey) -> Option<String> {
        community_nicknames(community).unwrap().remove(who)
    }

    /// Forget the local Guestbook and read it back from the relays, as a device that never saw it.
    async fn reread_guestbook(relay: &MemoryRelay, community: &CommunityV2) {
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        crate::db::community::set_guestbook(&cid_hex, &[], 0).unwrap();
        sync_guestbook(relay, community).await.unwrap();
    }

    #[tokio::test]
    async fn a_member_names_themselves_and_a_moderator_renames_those_beneath() {
        let (bed, owner, x, community) = v2_bed_with_admin("Names").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let mods = create_role_v2(&bed.relay, &held(), "Mods", 0, Permissions::MANAGE_NICKNAMES).await.unwrap();
        let (y, m) = (Keys::generate(), Keys::generate());
        set_member_roles(&bed.relay, &held(), &y.public_key(), vec![mods]).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        act_as(&m);
        set_nickname(&bed.relay, &held(), &m.public_key(), "  Moth  ").await.unwrap();
        assert_eq!(nick_of(&held(), &m.public_key()).as_deref(), Some("Moth"), "a member names themselves, trimmed");
        assert!(set_nickname(&bed.relay, &held(), &y.public_key(), "Boss").await.is_err(), "and nobody else");
        assert!(set_nickname(&bed.relay, &held(), &m.public_key(), &"x".repeat(33)).await.is_err(), "in at most 32 characters");
        act_as(&y);
        set_nickname(&bed.relay, &held(), &m.public_key(), "Moderated").await.unwrap();
        assert_eq!(nick_of(&held(), &m.public_key()).as_deref(), Some("Moderated"), "a moderator renames a member beneath them");
        assert!(set_nickname(&bed.relay, &held(), &x.public_key(), "Demoted").await.is_err(), "never one above");
        assert!(set_nickname(&bed.relay, &held(), &owner.keys.public_key(), "Nobody").await.is_err(), "nor the owner");
        act_as(&x);
        assert!(set_nickname(&bed.relay, &held(), &m.public_key(), "Nope").await.is_err(), "outranking takes Manage Nicknames too");
        act_as(&owner.keys);
        let log = audit_log(&bed.relay, &held()).await.unwrap();
        let renames: Vec<_> = log.entries.iter().filter(|e| e.action == "member_nick_update").collect();
        assert_eq!(renames.len(), 2, "each change is one entry");
        assert_eq!(renames[0].actor.as_deref(), Some(nostr_sdk::prelude::ToBech32::to_bech32(&y.public_key()).unwrap().as_str()));
        assert_eq!(renames[0].changes, vec![serde_json::json!({ "field": "nick", "old": "Moth", "new": "Moderated" })]);
        reread_guestbook(&bed.relay, &held()).await;
        assert_eq!(nick_of(&held(), &m.public_key()).as_deref(), Some("Moderated"), "a device reading the relays agrees");
        act_as(&m);
        set_nickname(&bed.relay, &held(), &m.public_key(), "").await.unwrap();
        assert_eq!(nick_of(&held(), &m.public_key()), None, "clearing leaves their own name");
        act_as(&owner.keys);
    }

    #[tokio::test]
    async fn on_the_legacy_roster_anyone_names_themselves() {
        let (bed, owner, _m) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Legacy", bed.relays.clone(), None).await.unwrap();
        follow_control(&bed.relay, &community).await.unwrap();
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let (m, n) = (Keys::generate(), Keys::generate().public_key());
        act_as(&m);
        set_nickname(&bed.relay, &held(), &m.public_key(), "Moth").await.unwrap();
        assert_eq!(nick_of(&held(), &m.public_key()).as_deref(), Some("Moth"));
        assert!(set_nickname(&bed.relay, &held(), &n, "Them").await.is_err(), "but only themselves");
        act_as(&owner.keys);
    }

    #[tokio::test]
    async fn a_banned_members_nickname_names_nobody() {
        let (bed, owner, _x, community) = v2_bed_with_admin("BannedName").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let m = Keys::generate();
        act_as(&m);
        set_nickname(&bed.relay, &held(), &m.public_key(), "Admin").await.unwrap();
        act_as(&owner.keys);
        set_members_banned(&bed.relay, community.id(), &[m.public_key()], true).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        assert_eq!(nick_of(&held(), &m.public_key()), None);
    }

    #[tokio::test]
    async fn turning_off_change_nickname_takes_down_the_ones_members_set() {
        let (bed, owner, _x, community) = v2_bed_with_admin("NoNames").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let (m, n) = (Keys::generate(), Keys::generate().public_key());
        act_as(&m);
        set_nickname(&bed.relay, &held(), &m.public_key(), "Mine").await.unwrap();
        act_as(&owner.keys);
        set_nickname(&bed.relay, &held(), &n, "Given").await.unwrap();
        set_everyone(&bed.relay, &held(), crate::community::v2::roles::EVERYONE_DEFAULT & !Permissions::CHANGE_NICKNAME).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        assert_eq!(nick_of(&held(), &m.public_key()), None, "a member's own Nickname stands only while they may set it");
        assert_eq!(nick_of(&held(), &n).as_deref(), Some("Given"), "one the owner gave stays");
        act_as(&m);
        assert!(set_nickname(&bed.relay, &held(), &m.public_key(), "Again").await.is_err());
        act_as(&owner.keys);
    }

    #[tokio::test]
    async fn renaming_someone_else_counts_only_with_the_grant_it_cites() {
        let (bed, _owner, _x, community) = v2_bed_with_admin("NameCited").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let mods = create_role_v2(&bed.relay, &held(), "Mods", 0, Permissions::MANAGE_NICKNAMES).await.unwrap();
        let (y, m) = (Keys::generate(), Keys::generate().public_key());
        set_member_roles(&bed.relay, &held(), &y.public_key(), vec![mods]).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        act_as(&y);
        set_nickname(&bed.relay, &held(), &m, "Cited").await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let (mut events, cursor) = crate::db::community::get_guestbook(&cid_hex).unwrap();
        events.push(guestbook::GuestbookEvent {
            rumor_id: [9; 32],
            entry: guestbook::GuestbookEntry::Nickname { actor: y.public_key(), target: m, nick: "Uncited".into(), citation: None, at_ms: now_ms() + 1_000 },
            epoch: Some(held().root_epoch.0),
            observed_at: None,
        });
        crate::db::community::set_guestbook(&cid_hex, &events, cursor).unwrap();
        assert_eq!(nick_of(&held(), &m).as_deref(), Some("Cited"), "an uncited one names nobody");
        // A co-moderator's clock runs ahead: the next rename still lands after theirs.
        let (mut events, cursor) = crate::db::community::get_guestbook(&cid_hex).unwrap();
        events.push(guestbook::GuestbookEvent {
            rumor_id: [10; 32],
            entry: guestbook::GuestbookEntry::Nickname { actor: _owner.keys.public_key(), target: m, nick: "Ahead".into(), citation: None, at_ms: now_ms() + 600_000 },
            epoch: Some(held().root_epoch.0),
            observed_at: None,
        });
        crate::db::community::set_guestbook(&cid_hex, &events, cursor).unwrap();
        assert_eq!(nick_of(&held(), &m).as_deref(), Some("Ahead"));
        set_nickname(&bed.relay, &held(), &m, "Latest").await.unwrap();
        assert_eq!(nick_of(&held(), &m).as_deref(), Some("Latest"));
        // A member nobody lets name m plants one an hour ahead: it moves nobody's next rename.
        let (mut events, cursor) = crate::db::community::get_guestbook(&cid_hex).unwrap();
        events.push(guestbook::GuestbookEvent {
            rumor_id: [11; 32],
            entry: guestbook::GuestbookEntry::Nickname { actor: Keys::generate().public_key(), target: m, nick: "Junk".into(), citation: None, at_ms: now_ms() + 3_500_000 },
            epoch: Some(held().root_epoch.0),
            observed_at: None,
        });
        crate::db::community::set_guestbook(&cid_hex, &events, cursor).unwrap();
        set_nickname(&bed.relay, &held(), &m, "Prompt").await.unwrap();
        let w = &standing_nicknames(&held()).unwrap()[&m];
        assert_eq!(w.nick, "Prompt");
        assert!(w.at_ms < now_ms() + 1_000_000, "dated after what counts, not after junk");
    }

    #[tokio::test]
    async fn nicknames_cross_a_refounding() {
        let (bed, owner, x, community) = v2_bed_with_admin("NameCarry").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let (m, gone) = (Keys::generate(), Keys::generate().public_key());
        act_as(&m);
        set_nickname(&bed.relay, &held(), &m.public_key(), "Moth").await.unwrap();
        let first = standing_nicknames(&held()).unwrap()[&m.public_key()].at_ms;
        act_as(&owner.keys);
        set_nickname(&bed.relay, &held(), &x.public_key(), "Given").await.unwrap();
        set_nickname(&bed.relay, &held(), &gone, "Former").await.unwrap();
        refound_community(&bed.relay, &held(), &[]).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        assert_ne!(held().root_epoch, community.root_epoch);
        sync_guestbook(&bed.relay, &held()).await.unwrap();
        let named = standing_nicknames(&held()).unwrap();
        assert_eq!(named.get(&x.public_key()).map(|w| w.nick.as_str()), Some("Given"), "the refounder carried the one it gave");
        assert!(!named.contains_key(&gone), "but only for a member it re-keyed");
        assert!(!named.contains_key(&m.public_key()), "a member's own waits for their own client, even on a device that held it");
        act_as(&m);
        carry_my_nickname(&bed.relay, &held()).await.unwrap();
        act_as(&owner.keys);
        let log = audit_log(&bed.relay, &held()).await.unwrap();
        let renames: Vec<_> = log.entries.iter().filter(|e| e.action == "member_nick_update").collect();
        assert_eq!(renames.len(), 3, "what a Refounding carried is no new act");
        reread_guestbook(&bed.relay, &held()).await;
        let named = standing_nicknames(&held()).unwrap();
        assert_eq!(named.get(&m.public_key()).map(|w| (w.nick.as_str(), w.at_ms)), Some(("Moth", first)), "carried, dated as first issued");
        assert_eq!(named.get(&x.public_key()).map(|w| w.nick.as_str()), Some("Given"));
    }

    #[tokio::test]
    async fn a_carried_nickname_reads_the_same_on_every_device_and_goes_out_once() {
        let (bed, owner, _x, community) = v2_bed_with_admin("CarryOnce").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let mods = create_role_v2(&bed.relay, &held(), "Mods", 0, Permissions::MANAGE_NICKNAMES).await.unwrap();
        let bans = create_role_v2(&bed.relay, &held(), "Bans", 0, Permissions::BAN).await.unwrap();
        let (y, z, m, t) = (Keys::generate(), Keys::generate(), Keys::generate(), Keys::generate().public_key());
        set_member_roles(&bed.relay, &held(), &y.public_key(), vec![mods]).await.unwrap();
        set_member_roles(&bed.relay, &held(), &z.public_key(), vec![bans]).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        act_as(&m);
        set_nickname(&bed.relay, &held(), &m.public_key(), "Moth").await.unwrap();
        act_as(&y);
        set_nickname(&bed.relay, &held(), &t, "Given").await.unwrap();
        act_as(&owner.keys);
        set_everyone(&bed.relay, &held(), crate::community::v2::roles::EVERYONE_DEFAULT & !Permissions::CHANGE_NICKNAME).await.unwrap();
        set_everyone(&bed.relay, &held(), crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        act_as(&z);
        refound_community(&bed.relay, &held(), &[]).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        sync_guestbook(&bed.relay, &held()).await.unwrap();
        // Nobody could carry what y gave t: a device that held it and one that never did agree.
        assert_eq!(nick_of(&held(), &t), None, "a device that held the old Guestbook");
        act_as(&m);
        carry_my_nickname(&bed.relay, &held()).await.unwrap();
        // m's other device holds the first copy, and reads the carried one off the new plane.
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let (mut events, cursor) = crate::db::community::get_guestbook(&cid_hex).unwrap();
        for e in events.iter_mut().filter(|e| matches!(e.entry, guestbook::GuestbookEntry::Nickname { .. })) {
            e.epoch = Some(community.root_epoch.0);
        }
        crate::db::community::set_guestbook(&cid_hex, &events, cursor).unwrap();
        sync_guestbook(&bed.relay, &held()).await.unwrap();
        let gb = super::super::derive::guestbook_group_key(&held().community_root, community.id(), held().root_epoch).pk().to_hex();
        let q = Query { kinds: vec![1059], authors: vec![gb], ..Default::default() };
        let published = bed.relay.fetch(&q, &held().relays).await.unwrap().len();
        for _ in 0..2 {
            carry_my_nickname(&bed.relay, &held()).await.unwrap();
        }
        assert_eq!(bed.relay.fetch(&q, &held().relays).await.unwrap().len(), published, "the other device doesn't send it again");
        act_as(&owner.keys);
        reread_guestbook(&bed.relay, &held()).await;
        assert_eq!(nick_of(&held(), &t), None, "a device that never held it");
        assert_eq!(nick_of(&held(), &m.public_key()).as_deref(), Some("Moth"));
    }

    #[tokio::test]
    async fn a_carried_nickname_still_stands_on_its_members_own_word() {
        let (bed, owner, _x, community) = v2_bed_with_admin("CarryWord").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        // A Role with no bits makes m someone the Refounding re-keys, naming themselves on @everyone's bit alone.
        let plain = create_role_v2(&bed.relay, &held(), "Plain", 0, 0).await.unwrap();
        let m = Keys::generate();
        set_member_roles(&bed.relay, &held(), &m.public_key(), vec![plain]).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        act_as(&m);
        set_nickname(&bed.relay, &held(), &m.public_key(), "Mine").await.unwrap();
        act_as(&owner.keys);
        refound_community(&bed.relay, &held(), &[]).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        sync_guestbook(&bed.relay, &held()).await.unwrap();
        act_as(&m);
        carry_my_nickname(&bed.relay, &held()).await.unwrap();
        assert_eq!(nick_of(&held(), &m.public_key()).as_deref(), Some("Mine"));
        act_as(&owner.keys);
        set_everyone(&bed.relay, &held(), crate::community::v2::roles::EVERYONE_DEFAULT & !Permissions::CHANGE_NICKNAME).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        assert_eq!(nick_of(&held(), &m.public_key()), None, "turning Change Nickname off takes it down after a Refounding too");
    }

    #[tokio::test]
    async fn a_carried_nickname_heard_live_moves_to_the_new_epoch() {
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "LiveCarry", vec!["wss://r".into()], None).await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let row = |id: u8, entry: guestbook::GuestbookEntry| guestbook::GuestbookEvent { rumor_id: [id; 32], entry, epoch: Some(0), observed_at: None };
        let me = owner.public_key();
        let nick = guestbook::GuestbookEntry::Nickname { actor: me, target: me, nick: "Boss".into(), citation: None, at_ms: now_ms() - 1_000 };
        let join = guestbook::GuestbookEntry::Join { member: me, invited_by: None, at_ms: now_ms() - 2_000 };
        crate::db::community::set_guestbook(&cid_hex, &[row(1, nick.clone()), row(2, join.clone())], 0).unwrap();
        let mut moved = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        moved.root_epoch = Epoch(1);
        assert!(ingest_guestbook_event(&moved, row(1, nick.clone()), now_ms() / 1000).unwrap(), "the same Nickname on the new plane");
        assert!(!ingest_guestbook_event(&moved, row(1, nick), now_ms() / 1000).unwrap(), "once");
        assert!(!ingest_guestbook_event(&moved, row(2, join), now_ms() / 1000).unwrap(), "a Join keeps the plane it was first read on");
        let (events, _) = crate::db::community::get_guestbook(&cid_hex).unwrap();
        assert_eq!(events.iter().map(|e| e.epoch).collect::<Vec<_>>(), vec![Some(1), Some(0)]);
    }

    #[tokio::test]
    async fn a_timed_out_member_cant_rename_themselves() {
        let (bed, owner, _x, community) = v2_bed_with_admin("NameTimeout").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let m = Keys::generate();
        act_as(&m);
        set_nickname(&bed.relay, &held(), &m.public_key(), "Before").await.unwrap();
        act_as(&owner.keys);
        timeout_member(&bed.relay, &held(), &m.public_key(), 600).await.unwrap();
        assert_eq!(nick_of(&held(), &m.public_key()), None, "their own names nobody while it runs");
        act_as(&m);
        let err = set_nickname(&bed.relay, &held(), &m.public_key(), "Taunt").await.unwrap_err();
        assert!(err.contains("timed out"), "{err}");
        act_as(&owner.keys);
        timeout_member(&bed.relay, &held(), &m.public_key(), 0).await.unwrap();
        assert_eq!(nick_of(&held(), &m.public_key()).as_deref(), Some("Before"), "and stands again once it's lifted");
    }

    #[tokio::test]
    async fn a_member_carries_their_own_nickname_when_the_refounder_cant() {
        let (bed, _owner, _x, community) = v2_bed_with_admin("SelfCarry").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let bans = create_role_v2(&bed.relay, &held(), "Bans", 0, Permissions::BAN).await.unwrap();
        let (z, m) = (Keys::generate(), Keys::generate());
        set_member_roles(&bed.relay, &held(), &z.public_key(), vec![bans]).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        act_as(&m);
        set_nickname(&bed.relay, &held(), &m.public_key(), "Moth").await.unwrap();
        let first = standing_nicknames(&held()).unwrap()[&m.public_key()].at_ms;
        act_as(&z);
        refound_community(&bed.relay, &held(), &[]).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        assert_ne!(held().root_epoch, community.root_epoch);
        act_as(&m);
        // The Refounder holds no Manage Nicknames: m's own device carries it.
        carry_my_nickname(&bed.relay, &held()).await.unwrap();
        let gb = super::super::derive::guestbook_group_key(&held().community_root, community.id(), held().root_epoch).pk().to_hex();
        let q = Query { kinds: vec![1059], authors: vec![gb], ..Default::default() };
        let published = bed.relay.fetch(&q, &held().relays).await.unwrap().len();
        carry_my_nickname(&bed.relay, &held()).await.unwrap();
        assert_eq!(bed.relay.fetch(&q, &held().relays).await.unwrap().len(), published, "carried once");
        reread_guestbook(&bed.relay, &held()).await;
        let named = standing_nicknames(&held()).unwrap();
        assert_eq!(named.get(&m.public_key()).map(|w| (w.nick.as_str(), w.at_ms)), Some(("Moth", first)), "dated as first issued");
    }

    async fn invites_to(relay: &MemoryRelay, community: &CommunityV2, pk: &PublicKey) -> usize {
        let q = Query { kinds: vec![1059], p_tags: vec![pk.to_hex()], ..Default::default() };
        relay.fetch(&q, &community.relays).await.unwrap_or_default().len()
    }

    #[tokio::test]
    async fn a_tenure_vouching_for_unpublished_editions_isnt_resealed() {
        // An admin pre-seals a puppet's unpublished edition, then is demoted: the honest
        // re-seal leaves that Tenure out, so the puppet can't publish it later on that standing.
        let (bed, owner, w, community) = v2_bed_with_admin("PreSeal").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let b = Keys::generate();
        let made = "da".repeat(32);
        let group = control::ControlPlane::of(&held()).write_group().unwrap();
        let content = crate::community::v2::roles::role_v2_content_json(&role_v2(&made, "Puppet", "z", 0)).unwrap();
        let binding = Some(crate::community::v2::derive::edition_binding(community.id()));
        let rumor = control::build_edition_rumor_bound(b.public_key(), vsk::ROLE_V2, &eid_of(&made), 1, None, &content, 1_000, None, binding);
        let (wrap, _) = control::seal_control_edition(&rumor, &group, &b, Timestamp::from_secs(1_000)).unwrap();
        let (pre, _) = control::open_control_edition(&wrap, &group).unwrap();
        publish_tenure(&bed.relay, &held(), &w, &b.public_key(), vec![entry("y", Permissions::MANAGE_ROLES, &[pre.self_hash])], 1).await;
        // A refused successor naming it doesn't make it seen.
        let next = control::build_edition_rumor_bound(b.public_key(), vsk::ROLE_V2, &eid_of(&made), 2, Some(&pre.self_hash), &content, 1_001, None, binding);
        let (next, _) = control::seal_control_edition(&next, &group, &b, Timestamp::from_secs(1_001)).unwrap();
        bed.relay.publish(&next, &held().relays).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        set_member_roles(&bed.relay, &held(), &w.public_key(), vec![]).await.unwrap();
        bed.relay.publish(&wrap, &held().relays).await.unwrap();
        let f = fold_authority(&held(), &fetch_control(&bed.relay, &held()).await, &Floors::default());
        assert!(f.roles.role(&made).is_none(), "the late edition stands on nothing");
        let _ = owner;
    }

    #[tokio::test]
    async fn a_tenure_listing_a_superseded_edition_is_still_resealed() {
        let (bed, owner, w, community) = v2_bed_with_admin("Superseded").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let r = create_role_v2(&bed.relay, &held(), "Old", 0, 0).await.unwrap();
        let first = fetch_control(&bed.relay, &held()).await.into_iter().find(|e| e.entity_id == eid_of(&r)).unwrap();
        let rank = fetch_authority(&bed.relay, &held()).await.roles.role(&r).unwrap().rank.clone().unwrap();
        publish_role_v2(&bed.relay, &held(), &owner.keys, &role_v2(&r, "New", &rank, 0), 2).await;
        let b = Keys::generate().public_key();
        publish_tenure(&bed.relay, &held(), &w, &b, vec![entry("y", Permissions::MANAGE_ROLES, &[first.self_hash])], 1).await;
        follow_control(&bed.relay, &held()).await.unwrap();
        let tenure = super::super::derive::tenure_locator(community.id(), &b.to_bytes(), &w.public_key().to_bytes());
        let w_tenure = fetch_control(&bed.relay, &held()).await.into_iter().find(|e| e.entity_id == tenure).unwrap().self_hash;
        // The superseded edition is compacted away; its successor still names it.
        let compacted = Hiding { inner: &bed.relay, group: control::ControlPlane::of(&held()).write_group().unwrap(), hide: Box::new(move |e| e.self_hash == first.self_hash) };
        set_member_roles(&compacted, &held(), &w.public_key(), vec![]).await.unwrap();
        let seal = super::super::derive::tenure_locator(community.id(), &w.public_key().to_bytes(), &owner.keys.public_key().to_bytes());
        let mine = fetch_control(&bed.relay, &held()).await.into_iter().filter(|e| e.entity_id == seal).max_by_key(|e| e.version).expect("W's standing was sealed");
        let listed = crate::community::v2::roles::parse_tenure_content(&mine.content).unwrap();
        assert!(listed.sealed.iter().any(|x| x.heads.contains(&crate::simd::hex::bytes_to_hex_32(&w_tenure))), "W's Tenure is kept");
    }

    #[tokio::test]
    async fn a_member_cant_let_themselves_in() {
        let (bed, owner, x, community) = v2_bed_with_admin("SelfIn").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let ch = create_private_channel(&bed.relay, &held(), "inner").await.unwrap();
        let chan = crate::simd::hex::bytes_to_hex_32(&ch.0);
        let o = crate::community::roles::Overwrite { scope: chan.clone(), target: crate::community::roles::OverwriteTarget::Member(x.public_key().to_hex()), allow: Permissions(Permissions::VIEW_CHANNEL), deny: Permissions(0) };
        let t = crate::community::v2::roles::overwrite_target_bytes(community.id(), &o.target).unwrap();
        publish_marked(&bed.relay, &held(), &x, vsk::CHANNEL_ACL, &crate::community::v2::derive::acl_locator(community.id(), &ch.0, &t), 1, None, &crate::community::v2::roles::overwrite_content_json(&o)).await;
        let f = fold_authority(&held(), &fetch_control(&bed.relay, &held()).await, &Floors::default());
        assert!(!f.roles.is_entitled(Some(&owner.keys.public_key().to_hex()), &x.public_key().to_hex(), &chan, &[], &[]), "their own standing sits above nothing of theirs");
        // The owner's own allow does let them in.
        grant_channel_access(&bed.relay, &held(), &ch, &x.public_key()).await.unwrap();
        let f = fold_authority(&held(), &fetch_control(&bed.relay, &held()).await, &Floors::default());
        assert!(f.roles.is_entitled(Some(&owner.keys.public_key().to_hex()), &x.public_key().to_hex(), &chan, &[], &[]));
    }

    #[tokio::test]
    async fn a_role_moved_past_an_overwrites_writer_rekeys_who_it_let_in() {
        let (bed, owner, a, community) = v2_bed_with_admin("MovePast").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let ch = create_private_channel(&bed.relay, &held(), "inner").await.unwrap();
        let chan = crate::simd::hex::bytes_to_hex_32(&ch.0);
        let r = create_role_v2(&bed.relay, &held(), "Readers", 0, 0).await.unwrap();
        let m = Keys::generate().public_key();
        set_member_roles(&bed.relay, &held(), &m, vec![r.clone()]).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        act_as(&a);
        set_overwrite(&bed.relay, &held(), ch.0, crate::community::roles::OverwriteTarget::Role(r.clone()), Permissions::VIEW_CHANNEL, 0).await.unwrap();
        act_as(&owner.keys);
        follow_control(&bed.relay, &held()).await.unwrap();
        assert!(crate::db::community::get_community_roles(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap().is_entitled(Some(&owner.keys.public_key().to_hex()), &m.to_hex(), &chan, &[], &[]));
        let epoch = held().channel(&ch).unwrap().epoch;
        // The owner lifts Readers above A: A's allow no longer stands, so M is cut.
        move_role_v2(&bed.relay, &held(), &r, 0).await.unwrap();
        let f = fold_authority(&held(), &fetch_control(&bed.relay, &held()).await, &Floors::default());
        assert!(!f.roles.is_entitled(Some(&owner.keys.public_key().to_hex()), &m.to_hex(), &chan, &[], &[]), "readers drop the allow");
        assert!(held().channel(&ch).unwrap().epoch > epoch, "and the channel rotated without M");
    }

    /// Serves reads until the first publish, then refuses every one.
    struct BreaksAfterPublish<'a> {
        inner: &'a MemoryRelay,
        broken: std::sync::atomic::AtomicBool,
    }
    #[async_trait::async_trait]
    impl Transport for BreaksAfterPublish<'_> {
        async fn fetch_plane(&self, _plane: &Keys, query: &Query, relays: &[String]) -> Result<crate::community::transport::PlaneFetch, String> {
            Ok(crate::community::transport::PlaneFetch::whole(self.fetch(query, relays).await?))
        }
        async fn publish(&self, e: &Event, r: &[String]) -> Result<(), String> {
            self.broken.store(true, std::sync::atomic::Ordering::SeqCst);
            self.inner.publish(e, r).await
        }
        async fn publish_durable(&self, e: &Event, r: &[String]) -> Result<(), String> {
            self.broken.store(true, std::sync::atomic::Ordering::SeqCst);
            self.inner.publish_durable(e, r).await
        }
        async fn fetch(&self, q: &Query, r: &[String]) -> Result<Vec<Event>, String> {
            if self.broken.load(std::sync::atomic::Ordering::SeqCst) {
                return Err("offline".into());
            }
            self.inner.fetch(q, r).await
        }
    }

    #[tokio::test]
    async fn ban_severance_on_roles_v2_refuses_a_partial_read() {
        let (bed, _owner, _x, community) = v2_bed_with_admin("SeverBlind").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let ch = create_private_channel(&bed.relay, &held(), "inner").await.unwrap();
        let b = Keys::generate().public_key();
        grant_channel_access(&bed.relay, &held(), &ch, &b).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        let before = crate::db::community::get_community_roles(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap();
        let epoch = held().channel(&ch).unwrap().epoch;
        let blind = BreaksAfterPublish { inner: &bed.relay, broken: true.into() };
        let err = sever_banned_private_reads(&blind, &held(), &[(b, Vec::new())], Some(&before)).await.unwrap_err();
        assert!(err.contains("read whole"), "{err}");
        assert_eq!(held().channel(&ch).unwrap().epoch, epoch, "nothing rotated on half a roster");
        // The cut is owed, not forgotten: the next whole read rotates without them.
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        assert!(has_read_cuts(&cid_hex));
        let invited = invites_to(&bed.relay, &held(), &b).await;
        assert_eq!(run_read_cuts(&bed.relay, &held()).await.unwrap(), 1);
        assert!(held().channel(&ch).unwrap().epoch > epoch, "the channel rotated");
        assert_eq!(invites_to(&bed.relay, &held(), &b).await, invited, "and the banned member got no new key");
        assert!(!has_read_cuts(&cid_hex), "the cut is settled");
    }

    #[tokio::test]
    async fn a_role_move_settles_on_what_it_knows_when_the_reread_fails() {
        let (bed, owner, _x, community) = v2_bed_with_admin("MoveOffline").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let ch = create_private_channel(&bed.relay, &held(), "inner").await.unwrap();
        let (r, other) = (create_role_v2(&bed.relay, &held(), "Readers", 0, 0).await.unwrap(), create_role_v2(&bed.relay, &held(), "Other", 0, 0).await.unwrap());
        set_overwrite(&bed.relay, &held(), ch.0, crate::community::roles::OverwriteTarget::Role(r.clone()), Permissions::VIEW_CHANNEL, 0).await.unwrap();
        let m = Keys::generate().public_key();
        set_member_roles(&bed.relay, &held(), &m, vec![r]).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        let epoch = held().channel(&ch).unwrap().epoch;
        let flaky = BreaksAfterPublish { inner: &bed.relay, broken: false.into() };
        for (i, mv) in [(0usize, true), (1, false)] {
            flaky.broken.store(false, std::sync::atomic::Ordering::SeqCst);
            if mv {
                move_role_v2(&flaky, &held(), &other, i).await.unwrap();
            } else {
                let ranked: Vec<String> = { let v = fetch_authority(&bed.relay, &held()).await; ranked(&v).into_iter().map(|r| r.role_id.clone()).collect() };
                let mut order = ranked.clone();
                order.rotate_left(1);
                reorder_roles_v2(&flaky, &held(), &order).await.unwrap();
            }
            assert_eq!(held().channel(&ch).unwrap().epoch, epoch, "a failed reread evicts no one");
            let stored = crate::db::community::get_community_roles(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap();
            assert!(stored.is_entitled(Some(&owner.keys.public_key().to_hex()), &m.to_hex(), &crate::simd::hex::bytes_to_hex_32(&ch.0), &[], &[]), "nor drops them from the roster");
            assert!(stored.role(&other).is_some(), "nor its Roles");
        }
    }

    #[tokio::test]
    async fn a_role_move_whose_reread_fails_owes_the_cut() {
        let (bed, owner, a, community) = v2_bed_with_admin("OwedCut").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let ch = create_private_channel(&bed.relay, &held(), "inner").await.unwrap();
        let chan = crate::simd::hex::bytes_to_hex_32(&ch.0);
        let r = create_role_v2(&bed.relay, &held(), "Readers", 0, 0).await.unwrap();
        let m = Keys::generate().public_key();
        set_member_roles(&bed.relay, &held(), &m, vec![r.clone()]).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        act_as(&a);
        set_overwrite(&bed.relay, &held(), ch.0, crate::community::roles::OverwriteTarget::Role(r.clone()), Permissions::VIEW_CHANNEL, 0).await.unwrap();
        act_as(&owner.keys);
        follow_control(&bed.relay, &held()).await.unwrap();
        let epoch = held().channel(&ch).unwrap().epoch;
        // Readers above A: A's allow falls, but the reread fails, so the cut is owed.
        let flaky = BreaksAfterPublish { inner: &bed.relay, broken: false.into() };
        move_role_v2(&flaky, &held(), &r, 0).await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        assert!(has_owed_settle(&cid_hex));
        assert_eq!(held().channel(&ch).unwrap().epoch, epoch, "nothing cut on a failed read");
        let blind = BreaksAfterPublish { inner: &bed.relay, broken: true.into() };
        assert!(run_owed_settle(&blind, &held()).await.is_err(), "a partial read pays nothing");
        assert!(has_owed_settle(&cid_hex) && held().channel(&ch).unwrap().epoch == epoch, "and evicts no one");
        assert!(run_owed_settle(&bed.relay, &held()).await.unwrap());
        assert!(held().channel(&ch).unwrap().epoch > epoch, "the whole read cuts M");
        let owner_hex = owner.keys.public_key().to_hex();
        assert!(!crate::db::community::get_community_roles(&cid_hex).unwrap().is_entitled(Some(&owner_hex), &m.to_hex(), &chan, &[], &[]));
        assert!(!has_owed_settle(&cid_hex), "and the settle is paid");
    }

    #[tokio::test]
    async fn on_roles_v2_a_public_ban_rotates_the_channels_its_target_could_read() {
        let (bed, owner, _x, community) = v2_bed_with_admin("PublicBan").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        mint_public_link(&bed.relay, &held(), "https://vectorapp.io", None, None).await.unwrap();
        let (inner, other) = (create_private_channel(&bed.relay, &held(), "inner").await.unwrap(), create_private_channel(&bed.relay, &held(), "other").await.unwrap());
        let b = Keys::generate().public_key();
        grant_channel_access(&bed.relay, &held(), &inner, &b).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        let (e_inner, e_other) = (held().channel(&inner).unwrap().epoch, held().channel(&other).unwrap().epoch);
        set_members_banned(&bed.relay, held().id(), &[b], true).await.unwrap();
        assert_eq!(held().root_epoch, community.root_epoch, "public: no Refounding");
        assert!(held().channel(&inner).unwrap().epoch > e_inner, "the ban itself rotated what they could read");
        assert_eq!(held().channel(&other).unwrap().epoch, e_other, "and nothing else");
        let _ = owner;
    }

    #[tokio::test]
    async fn readers_agree_when_an_overwrites_editor_is_outranked() {
        let (bed, owner, x, community) = v2_bed_with_admin("Outranked").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let ch = create_private_channel(&bed.relay, &held(), "inner").await.unwrap();
        let r = create_role_v2(&bed.relay, &held(), "Readers", 0, 0).await.unwrap();
        let target = crate::community::roles::OverwriteTarget::Role(r.clone());
        set_overwrite(&bed.relay, &held(), ch.0, target.clone(), Permissions::VIEW_CHANNEL, 0).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        act_as(&x);
        set_overwrite(&bed.relay, &held(), ch.0, target.clone(), Permissions::VIEW_CHANNEL | Permissions::SEND_MESSAGES, 0).await.unwrap();
        act_as(&owner.keys);
        follow_control(&bed.relay, &held()).await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let floors = || -> Floors { crate::db::community::get_all_edition_heads_full(&cid_hex).unwrap().into_iter().filter(|(_, f)| f.0 == held().root_epoch.0).map(|(e, f)| (e, (f.1, f.2, f.3, f.4, f.5))).collect() };
        let held_floors = floors();
        // Readers lifted above X: X's edit no longer stands.
        move_role_v2(&bed.relay, &held(), &r, 0).await.unwrap();
        let eds = fetch_control(&bed.relay, &held()).await;
        let allow_of = |f: &AuthoritySet| f.roles.overwrites.iter().find(|o| o.target == target).map(|o| o.allow.0);
        let (warm, cold) = (fold_authority(&held(), &eds, &held_floors), fold_authority(&held(), &eds, &Floors::default()));
        assert_eq!(allow_of(&cold), Some(Permissions::VIEW_CHANNEL), "a cold reader folds the owner's edition");
        assert_eq!(allow_of(&warm), allow_of(&cold), "and a reader that held X's edit agrees");
    }

    #[tokio::test]
    async fn an_unsync_out_of_a_superiors_category_is_refused() {
        let (bed, _owner, x, community) = v2_bed_with_admin("Unsync").await;
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let top = "f7".repeat(32);
        publish_role_v2(&bed.relay, &held(), &_owner.keys, &role_v2(&top, "Top", "1", 0), 1).await;
        follow_control(&bed.relay, &held()).await.unwrap();
        let k = create_category(&bed.relay, &held(), "Rules").await.unwrap();
        set_overwrite(&bed.relay, &held(), k, crate::community::roles::OverwriteTarget::Role(top.clone()), Permissions::SEND_MESSAGES, 0).await.unwrap();
        let news = create_channel_in(&bed.relay, &held(), "news", false, Some(k)).await.unwrap();
        follow_control(&bed.relay, &held()).await.unwrap();
        let eid = crate::community::v2::derive::sync_locator(community.id(), &news);
        let prev = head_hash_on_relay(&bed.relay, &held(), &eid).await;
        let content = crate::community::v2::roles::sync_content_json(&crate::simd::hex::bytes_to_hex_32(&news.0), None);
        publish_marked(&bed.relay, &held(), &x, vsk::CHANNEL_SYNC, &eid, 2, prev, &content).await;
        let f = fold_authority(&held(), &fetch_control(&bed.relay, &held()).await, &Floors::default());
        assert_eq!(f.roles.syncs.get(&crate::simd::hex::bytes_to_hex_32(&news.0)), Some(&crate::simd::hex::bytes_to_hex_32(&k)), "X can't swap out a rule naming a Role above them");
    }

    #[tokio::test]
    async fn a_member_denied_send_cannot_post() {
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "NoSend", vec!["wss://r".into()], None).await.unwrap();
        activate_roles_v2(&relay, &community, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
        follow_control(&relay, &community).await.unwrap();
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let ch = community.channels[0].id;
        set_overwrite(&relay, &held(), ch.0, crate::community::roles::OverwriteTarget::Everyone, 0, Permissions::SEND_MESSAGES).await.unwrap();
        assert!(send_chat_message(&relay, &held(), &ch, "owner speaks", None, &[], vec![]).await.is_ok(), "the owner holds everything");
        let member = Keys::generate();
        let open = create_public_channel(&relay, &held(), "open").await.unwrap();
        let quiet = create_public_channel(&relay, &held(), "quiet").await.unwrap();
        set_overwrite(&relay, &held(), quiet.0, crate::community::roles::OverwriteTarget::Member(member.public_key().to_hex()), 0, Permissions::SEND_MESSAGES).await.unwrap();
        crate::state::MY_SECRET_KEY.store_from_keys(&member, &[]);
        crate::state::set_my_public_key(member.public_key());
        assert!(send_chat_message(&relay, &held(), &open, "fine here", None, &[], vec![]).await.is_ok(), "where Send stands, they post");
        let err = send_chat_message(&relay, &held(), &ch, "hi", None, &[], vec![]).await.unwrap_err();
        assert!(err.contains("can't send"), "{err}");
        assert!(send_chat_message(&relay, &held(), &quiet, "hi", None, &[], vec![]).await.is_err());
        // In an open channel readers collapse that member's posts, not the owner's.
        use nostr_sdk::prelude::ToBech32;
        let (mn, on) = (member.public_key().to_bech32().unwrap(), owner.public_key().to_bech32().unwrap());
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let denied = |c: &ChannelId, who: &[String]| crate::VectorCore.channel_send_denied(&cid_hex, &crate::simd::hex::bytes_to_hex_32(&c.0), who).unwrap();
        assert_eq!(denied(&quiet, &[mn.clone(), on.clone()]), vec![mn.clone()]);
        assert!(denied(&open, &[mn.clone()]).is_empty());
        // A restricted channel judges read-address posts the same way; a writer's stand on their key.
        assert!(held().channel(&ch).unwrap().restricted());
        assert_eq!(denied(&ch, &[mn, on]), vec![member.public_key().to_bech32().unwrap()]);
        crate::state::MY_SECRET_KEY.store_from_keys(&owner, &[]);
        crate::state::set_my_public_key(owner.public_key());
    }

    #[tokio::test]
    async fn on_roles_v2_keys_follow_roles_through_the_channel() {
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "AclRoles", vec!["wss://r".into()], None).await.unwrap();
        activate_roles_v2(&relay, &community, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
        follow_control(&relay, &community).await.unwrap();
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let priv_id = create_private_channel(&relay, &held(), "staff").await.unwrap();
        let chan = crate::simd::hex::bytes_to_hex_32(&priv_id.0);
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let owner_hex = community.owner().unwrap().to_hex();
        let m = Keys::generate().public_key();
        let roster = || crate::db::community::get_community_roles(&cid_hex).unwrap();
        assert!(roster().channel_roles(&chan).is_empty(), "no access role on Roles v2");
        assert!(!roster().is_entitled(Some(&owner_hex), &m.to_hex(), &chan, &[], &[]), "@everyone can't view it");

        let staff = create_role_v2(&relay, &held(), "Staff", 0, 0).await.unwrap();
        set_overwrite(&relay, &held(), priv_id.0, crate::community::roles::OverwriteTarget::Role(staff.clone()), Permissions::VIEW_CHANNEL, 0).await.unwrap();
        set_member_roles(&relay, &held(), &m, vec![staff.clone()]).await.unwrap();
        assert!(roster().is_entitled(Some(&owner_hex), &m.to_hex(), &chan, &[], &[]), "the role the channel lets through");
        assert!(bundle_of(&held(), BundleAudience::Member(m), None, None, None).channels.iter().any(|c| c.id == chan));
        assert_eq!(invites_to(&relay, &held(), &m).await, 1, "and a Direct Invite carried it to them");
        assert_eq!(held().channel(&priv_id).unwrap().epoch, Epoch(1));
        set_member_roles(&relay, &held(), &m, vec![]).await.unwrap();
        assert_eq!(held().channel(&priv_id).unwrap().epoch, Epoch(2), "losing the role rotates the channel");
        // Deleting the allow overwrite's role does the same for its holders.
        let n = Keys::generate().public_key();
        set_member_roles(&relay, &held(), &n, vec![staff.clone()]).await.unwrap();
        delete_role_v2(&relay, &held(), &staff).await.unwrap();
        assert_eq!(held().channel(&priv_id).unwrap().epoch, Epoch(3));
        assert!(!roster().is_entitled(Some(&owner_hex), &n.to_hex(), &chan, &[], &[]));
    }

    #[tokio::test]
    async fn an_overwrite_stands_only_on_authority_above_its_target() {
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "AclJudge", vec!["wss://r".into()], None).await.unwrap();
        publish_everyone(&relay, &community, &owner, crate::community::v2::roles::EVERYONE_DEFAULT, 1).await;
        let (a, b) = (Keys::generate(), Keys::generate());
        let mr = Permissions::MANAGE_ROLES | Permissions::VIEW_CHANNEL | Permissions::SEND_MESSAGES;
        let (ra, rb) = ("e3".repeat(32), "e4".repeat(32));
        publish_role_v2(&relay, &community, &owner, &role_v2(&ra, "A", "C", mr), 1).await;
        publish_role_v2(&relay, &community, &owner, &role_v2(&rb, "B", "F", Permissions::VIEW_CHANNEL), 1).await;
        publish_grant(&relay, &community, &owner, &a.public_key(), vec![ra.clone()], 1).await;
        let ch = community.channels[0].id.0;
        let put = |target: crate::community::roles::OverwriteTarget, allow: u64, deny: u64| {
            let o = crate::community::roles::Overwrite { scope: crate::simd::hex::bytes_to_hex_32(&ch), target, allow: Permissions(allow), deny: Permissions(deny) };
            let t = crate::community::v2::roles::overwrite_target_bytes(community.id(), &o.target).unwrap();
            (crate::community::v2::derive::acl_locator(community.id(), &ch, &t), crate::community::v2::roles::overwrite_content_json(&o))
        };
        use crate::community::roles::OverwriteTarget as T;
        // A, above B, denies B Send: stands. A denying A's own role: refused (not above it).
        let (e1, c1) = put(T::Role(rb.clone()), 0, Permissions::SEND_MESSAGES);
        publish_marked(&relay, &community, &a, vsk::CHANNEL_ACL, &e1, 1, None, &c1).await;
        let (e2, c2) = put(T::Role(ra.clone()), 0, Permissions::SEND_MESSAGES);
        publish_marked(&relay, &community, &a, vsk::CHANNEL_ACL, &e2, 1, None, &c2).await;
        // A allowing @everyone a bit A lacks: refused.
        let (e3, c3) = put(T::Everyone, Permissions::ATTACH_FILES, 0);
        publish_marked(&relay, &community, &a, vsk::CHANNEL_ACL, &e3, 1, None, &c3).await;
        // The owner's, at another target's coordinate: ignored. Unmarked: ignored.
        let (_, c4) = put(T::Everyone, 0, Permissions::ADD_REACTIONS);
        publish_marked(&relay, &community, &owner, vsk::CHANNEL_ACL, &e1, 2, None, &c4).await;
        let (e5, c5) = put(T::Member(b.public_key().to_hex()), Permissions::ATTACH_FILES, 0);
        publish_fork(&[&relay], &community, &owner, vsk::CHANNEL_ACL, &e5, 1, None, &c5, None).await;
        let f = fold_authority(&community, &fetch_control(&relay, &community).await, &Floors::default());
        let got: Vec<(T, u64, u64)> = f.roles.overwrites.iter().map(|o| (o.target.clone(), o.allow.0, o.deny.0)).collect();
        assert_eq!(got, vec![(T::Role(rb), 0, Permissions::SEND_MESSAGES)]);
    }

    #[tokio::test]
    async fn a_private_channel_mints_its_access_role_and_entitlement_follows_the_grant() {
        // CORD-03/04: the roles scoped to a channel ARE its access list. Proven
        // against a NON-owner so the owner-is-always-entitled rule can't carry it.
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Scoped", vec!["wss://r".into()], None).await.unwrap();
        let priv_id = create_private_channel(&relay, &community, "mods").await.unwrap();
        let chan_hex = crate::simd::hex::bytes_to_hex_32(&priv_id.0);
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);

        let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
        let access = roster.channel_roles(&chan_hex);
        assert_eq!(access.len(), 1, "the channel minted exactly one access role");
        assert!(
            access[0].permissions == crate::community::roles::Permissions::empty(),
            "the access role confers READ access (key possession), never authority"
        );
        assert_eq!(access[0].name, "mods", "named for its channel");

        // A stranger holds no scoped role: unentitled, and no key rides their bundle.
        let stranger = Keys::generate().public_key();
        let owner_hex = community.owner().unwrap().to_hex();
        assert!(!roster.is_entitled(Some(&owner_hex), &stranger.to_hex(), &chan_hex, &[], &[]));

        // Granting the access role entitles them; revoking un-entitles them. Both
        // proven through the roster, which is what routes keys.
        let role_id = access[0].role_id.clone();
        assert!(
            roster.is_entitled(Some(&owner_hex), &stranger.to_hex(), &chan_hex, std::slice::from_ref(&role_id), &[]),
            "the grant overlay entitles before the fold catches up"
        );

        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        grant_channel_access(&relay, &held, &priv_id, &stranger).await.unwrap();
        let after = crate::db::community::get_community_roles(&cid_hex).unwrap();
        assert!(
            after.is_entitled(Some(&owner_hex), &stranger.to_hex(), &chan_hex, &[], &[]),
            "the grant landed in the local roster (the fold runs later)"
        );
        let vend = bundle_of(&held, BundleAudience::Member(stranger), None, None, None);
        assert!(
            vend.channels.iter().any(|c| c.id == chan_hex),
            "a now-entitled member's bundle carries the channel key"
        );

        revoke_channel_access(&relay, &held, &priv_id, &stranger).await.unwrap();
        let after = crate::db::community::get_community_roles(&cid_hex).unwrap();
        assert!(
            !after.is_entitled(Some(&owner_hex), &stranger.to_hex(), &chan_hex, &[], &[]),
            "the revoke dropped the access role"
        );
        let rotated = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        assert_eq!(
            rotated.channel(&priv_id).unwrap().epoch,
            Epoch(2),
            "the revoke rotated the channel — a removal that doesn't rekey severs nobody"
        );

        // The access summary a bot reads back: roles, holders, and key state.
        let access = crate::VectorCore.channel_access(&cid_hex, &chan_hex).unwrap();
        assert_eq!(access["private"], true);
        assert_eq!(access["readable"], true, "we minted it, so we hold its key");
        assert_eq!(access["roles"].as_array().unwrap().len(), 1, "one access role");
        let holders = access["members"].as_array().unwrap();
        let me_npub = {
            use nostr_sdk::prelude::ToBech32;
            me_pk().unwrap().to_bech32().unwrap()
        };
        assert_eq!(holders.len(), 1, "only the creator holds it — the revoked member is gone");
        assert_eq!(holders[0], serde_json::json!(me_npub), "and that holder is the creator");
    }

    #[tokio::test]
    async fn a_public_ban_severs_the_private_channels_the_member_could_read() {
        // CORD-06 §1 per channel: a Public-community ban skips the Refounding
        // (CORD-05 §5), so without this rotation the banned member keeps each
        // held channel key and reads on forever. Only channels they could
        // actually reach rotate — the rest keep their epoch.
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Sever", vec!["wss://r".into()], None).await.unwrap();
        let mods = create_private_channel(&relay, &community, "mods").await.unwrap();
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let vault = create_private_channel(&relay, &held, "vault").await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);

        let spammer = Keys::generate().public_key();
        let bystander = Keys::generate().public_key();
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        grant_channel_access(&relay, &held, &mods, &spammer).await.unwrap();
        grant_channel_access(&relay, &held, &mods, &bystander).await.unwrap();

        // The ban composition's capture-then-strip: entitlement must be judged
        // from the PRE-strip roles, whether or not the strip has folded.
        let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
        let stripped: Vec<String> = roster.roles_of(&spammer.to_hex()).map(|r| r.role_id.clone()).collect();
        assert!(!stripped.is_empty(), "the grant landed before the strip");
        grant_roles(&relay, &held, &spammer, vec![]).await.unwrap();

        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let rotated = sever_banned_private_reads(&relay, &held, &[(spammer, stripped)], None).await.unwrap();
        assert_eq!(rotated, 1, "exactly the one channel they could read rotated");
        let after = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        assert_eq!(after.channel(&mods).unwrap().epoch, Epoch(2), "the reachable channel advanced");
        assert_eq!(after.channel(&vault).unwrap().epoch, Epoch(1), "the unreachable channel did not");

        // A member who never had reach rotates nothing.
        let stranger = Keys::generate().public_key();
        let n = sever_banned_private_reads(&relay, &after, &[(stranger, Vec::new())], None).await.unwrap();
        assert_eq!(n, 0, "no entitlement, no rotation");
    }

    #[tokio::test]
    async fn ban_severance_refuses_without_a_rotation_bit() {
        // Offer-side mirror of `channel_rotator_ok`: readers honor a channel
        // rotation only from MANAGE_CHANNELS holders, so a BAN-only moderator
        // publishing one would adopt an epoch every reader rejects — a fork.
        let (bed, owner, moderator) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Gated", bed.relays.clone(), None).await.unwrap();
        create_private_channel(&bed.relay, &community, "mods").await.unwrap();
        let rid = "c1".repeat(32);
        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::KICK), 1).await;
        publish_grant(&bed.relay, &community, &owner.keys, &moderator.keys.public_key(), vec![rid], 1).await;
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let bundle = bundle_of(&held, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
        let bundle_json = serde_json::to_string(&bundle).unwrap();

        bed.swap_to(&moderator);
        let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
        let _ = follow_control(&bed.relay, &joined).await;
        let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
        let target = Keys::generate().public_key();
        let err = sever_banned_private_reads(&bed.relay, &joined, &[(target, Vec::new())], None).await.unwrap_err();
        assert!(err.contains("permission"), "refused at the gate, not mid-rotation: {err}");
    }

    #[tokio::test]
    async fn set_banlist_refuses_an_author_the_fold_would_reject() {
        // The reader gates the banlist head on BAN and each added entry on strict
        // outrank. Publishing anyway would be silently void everywhere while the
        // author's own echo caches the phantom — fail-closed at the offer instead.
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Soap", bed.relays.clone(), None).await.unwrap();
        let rid = "c2".repeat(32);
        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::BAN), 1).await;
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let bundle = bundle_of(&held, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
        let bundle_json = serde_json::to_string(&bundle).unwrap();

        // A roleless member holds no BAN: refused before any publish.
        bed.swap_to(&member);
        let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
        let _ = follow_control(&bed.relay, &joined).await;
        let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
        let target = Keys::generate().public_key().to_hex();
        let err = set_banlist(&bed.relay, &joined, std::slice::from_ref(&target)).await.unwrap_err();
        assert!(err.contains("BAN"), "refused for the missing bit: {err}");
        assert!(
            crate::db::community::get_community_banlist(&crate::simd::hex::bytes_to_hex_32(&joined.id().0)).unwrap().is_empty(),
            "no phantom echo cached"
        );

        // Grant them BAN: adding a peer they don't outrank still refuses (the
        // fold drops per-target on outrank), while an unranked target passes.
        bed.swap_to(&owner);
        publish_grant(&bed.relay, &community, &owner.keys, &member.keys.public_key(), vec![rid.clone()], 1).await;
        let peer = Keys::generate().public_key();
        publish_grant(&bed.relay, &community, &owner.keys, &peer, vec![rid], 2).await;
        bed.swap_to(&member);
        let _ = follow_control(&bed.relay, &joined).await;
        let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
        let err = set_banlist(&bed.relay, &joined, &[peer.to_hex()]).await.unwrap_err();
        assert!(err.contains("outrank"), "an equal is not actionable: {err}");
        set_banlist(&bed.relay, &joined, std::slice::from_ref(&target)).await.unwrap();
    }

    #[tokio::test]
    async fn metadata_and_link_minting_refuse_unauthorized_authors() {
        // Both are reader-gated (MANAGE_METADATA; CREATE_INVITE on the registry) —
        // the offer must mirror or the SDK reports success on a void publish.
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Locked", bed.relays.clone(), None).await.unwrap();
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let bundle = bundle_of(&held, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
        let bundle_json = serde_json::to_string(&bundle).unwrap();

        bed.swap_to(&member);
        let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
        let _ = follow_control(&bed.relay, &joined).await;
        let joined = crate::db::community::load_community_v2(joined.id()).unwrap().unwrap();
        let meta = control::CommunityMetadata {
            name: "Hijacked".into(),
            description: None,
            relays: vec![],
            icon: None,
            banner: None,
            custom: None,
            extra: Default::default(),
        };
        assert!(edit_community_metadata(&bed.relay, &joined, &meta).await.is_err(), "metadata edit refused");
        assert!(
            mint_public_link(&bed.relay, &joined, "https://vectorapp.io/i/", None, None).await.is_err(),
            "link minting refused"
        );
    }

    #[tokio::test]
    async fn a_vended_key_parks_until_the_fold_proves_the_grant_then_adopts() {
        // JSKitty's race: the vend can land BEFORE the control fold that proves
        // the grant. It must park quietly (a lagging fold is not an anomaly) and
        // be adopted on the re-judge once the roster catches up.
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Vend", bed.relays.clone(), None).await.unwrap();
        let priv_id = create_private_channel(&bed.relay, &community, "mods").await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let chan_hex = crate::simd::hex::bytes_to_hex_32(&priv_id.0);
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let real_key = held.channel(&priv_id).unwrap().key.unwrap();
        let owner_hex = community.owner().unwrap().to_hex();

        // Judge as the MEMBER — the owner is always entitled, so only a non-owner
        // can exercise the grant rule at all.
        bed.swap_to(&member);
        let me = member.keys.public_key().to_hex();
        // Their fold has the channel (control-follow records it keyless) but not
        // yet the grant that entitles them.
        let mut member_view = held.clone();
        if let Some(c) = member_view.channels.iter_mut().find(|c| c.id.0 == priv_id.0) {
            c.key = None;
            c.epoch = Epoch(0);
        }

        // Ungranted → PARK, never refuse: this is exactly the "not synced enough
        // to judge" case, and it must stay quiet and retryable.
        let empty = crate::community::roles::CommunityRoles::default();
        assert!(matches!(
            judge_channel_key_vend(&member_view, &empty, &priv_id, Epoch(1), &owner_hex),
            VendVerdict::Park(_)
        ));

        // A channel our fold says is PUBLIC never heals — that's a spoof shape.
        let mut public_view = member_view.clone();
        if let Some(c) = public_view.channels.iter_mut().find(|c| c.id.0 == priv_id.0) {
            c.private = false;
        }
        assert!(matches!(
            judge_channel_key_vend(&public_view, &empty, &priv_id, Epoch(1), &owner_hex),
            VendVerdict::Refuse(_)
        ));

        // An unknown channel parks (our fold may simply be behind), never refuses.
        assert!(matches!(
            judge_channel_key_vend(&member_view, &empty, &ChannelId([0x77; 32]), Epoch(1), &owner_hex),
            VendVerdict::Park(_)
        ));

        // Park the vend, then re-judge with a roster that still lacks our grant:
        // it must SURVIVE, not be discarded.
        crate::db::community::park_channel_key(&cid_hex, &chan_hex, 1, &real_key, &owner_hex).unwrap();
        crate::db::community::set_community_roles(&cid_hex, &empty, 0).unwrap();
        crate::db::community::save_community_v2(&member_view).unwrap();
        let session = crate::db::current_session();
        let reloaded = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        assert!(absorb_parked_channel_keys(&reloaded, &session).is_empty(), "unprovable vend adopts nothing");
        assert_eq!(
            crate::db::community::get_pending_channel_keys(&cid_hex).unwrap().len(),
            1,
            "and stays parked for the next fold"
        );

        // The fold catches up: our grant lands, so the same vend now adopts.
        let access = crate::community::roles::Role {
            role_id: "44".repeat(32),
            name: "mods".into(),
            position: u32::MAX - 1,
            permissions: crate::community::roles::Permissions::empty(),
            scope: crate::community::roles::RoleScope::Channel(chan_hex.clone()),
            color: 0, rank: None, display: false, mentionable: false, extra: Default::default(),
        };
        let folded = crate::community::roles::CommunityRoles {
            grants: vec![crate::community::roles::MemberGrant { member: me.clone(), role_ids: vec![access.role_id.clone()] }],
            roles: vec![access],
            everyone: None,
            overwrites: Vec::new(), syncs: Default::default(), legacy_channels: None, creators: Default::default(),
        };
        let vendor = Keys::generate().public_key().to_hex();
        crate::db::community::set_community_banlist(&cid_hex, &[vendor.clone()], 1).unwrap();
        assert!(
            matches!(judge_channel_key_vend(&member_view, &folded, &priv_id, Epoch(1), &vendor), VendVerdict::Refuse("vendor is banned")),
            "a banned member delivers nothing"
        );
        crate::db::community::set_community_banlist(&cid_hex, &[], 2).unwrap();
        crate::db::community::set_community_roles(&cid_hex, &folded, 1).unwrap();
        let reloaded = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let adopted = absorb_parked_channel_keys(&reloaded, &session);
        assert_eq!(adopted.len(), 1, "the re-judge adopts once the grant folds");

        let after = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let ch = after.channel(&priv_id).unwrap();
        assert_eq!(ch.key, Some(real_key), "adopted the vended key");
        assert_eq!(ch.epoch, Epoch(1));
        assert!(
            crate::db::community::get_pending_channel_keys(&cid_hex).unwrap().is_empty(),
            "and the park is discharged"
        );
    }

    #[tokio::test]
    async fn a_vend_from_an_unentitled_sender_is_never_seated_but_survives_for_the_real_one() {
        // Vend rule 4: the VENDOR must be entitled too. Every other test sends as
        // the owner, which short-circuits the check one line above it, so the rule
        // itself has never been exercised. Both halves matter — a stranger must not
        // seat a key, and their row must not consume the slot either, which is the
        // suppression the candidate table exists to prevent.
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Vendors", bed.relays.clone(), None).await.unwrap();
        let priv_id = create_private_channel(&bed.relay, &community, "mods").await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let chan_hex = crate::simd::hex::bytes_to_hex_32(&priv_id.0);
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let owner_hex = community.owner().unwrap().to_hex();

        bed.swap_to(&member);
        let mut member_view = held.clone();
        if let Some(c) = member_view.channels.iter_mut().find(|c| c.id.0 == priv_id.0) {
            c.key = None;
            c.epoch = Epoch(0);
        }
        crate::db::community::save_community_v2(&member_view).unwrap();

        // WE are entitled (rule 3 passes, so the judge reaches rule 4). The vendor
        // below is not, and is not the owner.
        let access = crate::community::roles::Role {
            role_id: "66".repeat(32),
            name: "mods".into(),
            position: u32::MAX - 1,
            permissions: crate::community::roles::Permissions::empty(),
            scope: crate::community::roles::RoleScope::Channel(chan_hex.clone()),
            color: 0, rank: None, display: false, mentionable: false, extra: Default::default(),
        };
        let roster = crate::community::roles::CommunityRoles {
            grants: vec![crate::community::roles::MemberGrant {
                member: member.keys.public_key().to_hex(),
                role_ids: vec![access.role_id.clone()],
            }],
            roles: vec![access],
            everyone: None,
            overwrites: Vec::new(), syncs: Default::default(), legacy_channels: None, creators: Default::default(),
        };
        crate::db::community::set_community_roles(&cid_hex, &roster, 1).unwrap();

        let stranger_hex = Keys::generate().public_key().to_hex();
        let junk = [0x11; 32];
        crate::db::community::park_channel_key(&cid_hex, &chan_hex, 0, &junk, &stranger_hex).unwrap();

        let session = crate::db::current_session();
        let reloaded = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        assert!(
            absorb_parked_channel_keys(&reloaded, &session).is_empty(),
            "an unentitled vendor seats nothing"
        );
        let after = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        assert_eq!(after.channel(&priv_id).unwrap().key, None, "the channel is still keyless");
        assert_eq!(
            crate::db::community::get_pending_channel_keys(&cid_hex).unwrap().len(),
            1,
            "parked, not refused — the vendor's own entitlement may simply not have folded here yet"
        );

        // The entitled vendor's key lands despite the stranger's row sitting there.
        let real = [0x5a; 32];
        crate::db::community::park_channel_key(&cid_hex, &chan_hex, 0, &real, &owner_hex).unwrap();
        let reloaded = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        assert_eq!(
            absorb_parked_channel_keys(&reloaded, &session).len(),
            1,
            "the genuine vend is seated — a stranger cannot occupy the slot"
        );
        let after = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        assert_eq!(after.channel(&priv_id).unwrap().key, Some(real), "and it is the ENTITLED vendor's key");
        assert!(
            crate::db::community::get_pending_channel_keys(&cid_hex).unwrap().is_empty(),
            "both candidates discharge once one is seated"
        );
    }

    #[tokio::test]
    async fn a_vend_at_epoch_zero_is_adopted_onto_a_keyless_channel() {
        // Live cross-client finding: a peer that mints born-private channels at
        // epoch 0 vends epoch 0, which collides with our keyless cursor (also 0).
        // The monotonic guard (`new > current`) would refuse the only key we are
        // ever offered, and refuse it SILENTLY. First delivery is not a rotation.
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "EpochZero", bed.relays.clone(), None).await.unwrap();
        let priv_id = create_private_channel(&bed.relay, &community, "mods").await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let chan_hex = crate::simd::hex::bytes_to_hex_32(&priv_id.0);
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let vended = [0x5a; 32];
        let owner_hex = community.owner().unwrap().to_hex();

        bed.swap_to(&member);
        // The member's view: channel known, keyless, parked at the epoch-0 cursor.
        let mut member_view = held.clone();
        if let Some(c) = member_view.channels.iter_mut().find(|c| c.id.0 == priv_id.0) {
            c.key = None;
            c.epoch = Epoch(0);
        }
        crate::db::community::save_community_v2(&member_view).unwrap();

        // Entitle them, then park a vend AT EPOCH 0 (what the peer actually sends).
        let access = crate::community::roles::Role {
            role_id: "77".repeat(32),
            name: "mods".into(),
            position: u32::MAX - 1,
            permissions: crate::community::roles::Permissions::empty(),
            scope: crate::community::roles::RoleScope::Channel(chan_hex.clone()),
            color: 0, rank: None, display: false, mentionable: false, extra: Default::default(),
        };
        let roster = crate::community::roles::CommunityRoles {
            grants: vec![crate::community::roles::MemberGrant {
                member: member.keys.public_key().to_hex(),
                role_ids: vec![access.role_id.clone()],
            }],
            roles: vec![access],
            everyone: None,
            overwrites: Vec::new(), syncs: Default::default(), legacy_channels: None, creators: Default::default(),
        };
        crate::db::community::set_community_roles(&cid_hex, &roster, 1).unwrap();
        crate::db::community::park_channel_key(&cid_hex, &chan_hex, 0, &vended, &owner_hex).unwrap();

        let session = crate::db::current_session();
        let reloaded = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let adopted = absorb_parked_channel_keys(&reloaded, &session);
        assert_eq!(adopted.len(), 1, "an epoch-0 vend onto a keyless channel is adopted");

        let after = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let ch = after.channel(&priv_id).unwrap();
        assert_eq!(ch.key, Some(vended), "the key actually landed on the row");
        assert_eq!(ch.epoch, Epoch(0), "at the epoch the vendor named");
        assert!(
            !after.channel_read_coords(ch).is_empty(),
            "and the channel is readable — the whole point"
        );
        assert!(
            crate::db::community::get_pending_channel_keys(&cid_hex).unwrap().is_empty(),
            "the park is discharged"
        );
    }

    #[tokio::test]
    async fn a_wildly_ahead_vend_epoch_is_refused_not_seated() {
        // The channel head is MONOTONIC, so over-advancing it can never be walked
        // back: every genuine rotation afterwards lands at head+1, reads as stale,
        // and the channel dies for us with no heal path at all. An entitled
        // insider vending a garbage key costs isolation (accepted); one vending a
        // garbage EPOCH would cost the channel permanently, which is not.
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Poison", bed.relays.clone(), None).await.unwrap();
        let priv_id = create_private_channel(&bed.relay, &community, "mods").await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let chan_hex = crate::simd::hex::bytes_to_hex_32(&priv_id.0);
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let owner_hex = community.owner().unwrap().to_hex();

        bed.swap_to(&member);
        let mut member_view = held.clone();
        if let Some(c) = member_view.channels.iter_mut().find(|c| c.id.0 == priv_id.0) {
            c.key = None;
            c.epoch = Epoch(0);
        }
        crate::db::community::save_community_v2(&member_view).unwrap();
        let access = crate::community::roles::Role {
            role_id: "99".repeat(32),
            name: "mods".into(),
            position: u32::MAX - 1,
            permissions: crate::community::roles::Permissions::empty(),
            scope: crate::community::roles::RoleScope::Channel(chan_hex.clone()),
            color: 0, rank: None, display: false, mentionable: false, extra: Default::default(),
        };
        let roster = crate::community::roles::CommunityRoles {
            grants: vec![crate::community::roles::MemberGrant {
                member: member.keys.public_key().to_hex(),
                role_ids: vec![access.role_id.clone()],
            }],
            roles: vec![access],
            everyone: None,
            overwrites: Vec::new(), syncs: Default::default(), legacy_channels: None, creators: Default::default(),
        };
        crate::db::community::set_community_roles(&cid_hex, &roster, 1).unwrap();
        let reloaded = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();

        // Everything else about this vend is valid — only the epoch is absurd.
        assert!(matches!(
            judge_channel_key_vend(&reloaded, &roster, &priv_id, Epoch(1 << 40), &owner_hex),
            VendVerdict::Refuse(_)
        ));
        // REFUSED, not parked: a row nothing can ever discharge is its own leak.
        crate::db::community::park_channel_key(&cid_hex, &chan_hex, 1 << 40, &[0xEE; 32], &owner_hex).unwrap();
        let session = crate::db::current_session();
        assert!(absorb_parked_channel_keys(&reloaded, &session).is_empty(), "a poison epoch adopts nothing");
        assert!(
            crate::db::community::get_pending_channel_keys(&cid_hex).unwrap().is_empty(),
            "and the row is discharged rather than parked forever"
        );
        // The head is untouched, so the genuine vend still lands afterwards.
        let after = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        assert_eq!(after.channel(&priv_id).unwrap().epoch, Epoch(0), "head never advanced");
        assert!(matches!(
            judge_channel_key_vend(&after, &roster, &priv_id, Epoch(1), &owner_hex),
            VendVerdict::Accept
        ));
    }

    #[tokio::test]
    async fn a_channel_rename_lands_locally_without_waiting_for_the_fold() {
        // The fold is the authority but runs later, so publishing alone leaves the
        // edit reading back stale — it looks like the rename silently failed.
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Renames", vec!["wss://r".into()], None).await.unwrap();
        let priv_id = create_private_channel(&relay, &community, "mods").await.unwrap();
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let key_before = held.channel(&priv_id).unwrap().key;

        let mut meta = held.channel(&priv_id).unwrap().metadata();
        meta.name = "staff".into();
        edit_channel_metadata(&relay, &held, &priv_id, &meta).await.unwrap();

        let after = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let ch = after.channel(&priv_id).unwrap();
        assert_eq!(ch.name, "staff", "the rename is visible immediately");
        assert!(ch.private, "and privacy survives the edit");
        assert_eq!(ch.key, key_before, "as does the key — a rename is not a rotation");
    }

    #[tokio::test]
    async fn a_channel_rename_carries_its_companion_access_role() {
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Renames", vec!["wss://r".into()], None).await.unwrap();
        let priv_id = create_private_channel(&relay, &community, "mods").await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let chan_hex = crate::simd::hex::bytes_to_hex_32(&priv_id.0);

        let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
        let before = roster.channel_roles(&chan_hex);
        assert_eq!(before.len(), 1, "one companion role, minted at create");
        assert_eq!(before[0].name, "mods", "named after the channel it gates");
        let role_id = before[0].role_id.clone();

        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let mut meta = held.channel(&priv_id).unwrap().metadata();
        meta.name = "staff".into();
        edit_channel_metadata(&relay, &held, &priv_id, &meta).await.unwrap();

        let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
        let after = roster.channel_roles(&chan_hex);
        assert_eq!(after.len(), 1, "renamed in place, never duplicated");
        assert_eq!(after[0].role_id, role_id, "a rename is a versioned edit of the same id");
        assert_eq!(after[0].name, "staff", "the access role followed the channel");
        assert_eq!(
            after[0].permissions,
            crate::community::roles::Permissions::empty(),
            "and still confers read access, never authority"
        );
    }

    #[tokio::test]
    async fn a_customised_access_role_name_survives_a_channel_rename() {
        // The label is cosmetic — entitlement rides the scope. Overwriting a name
        // someone chose deliberately is the surprising half of "keep them in step".
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Renames", vec!["wss://r".into()], None).await.unwrap();
        let priv_id = create_private_channel(&relay, &community, "mods").await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let chan_hex = crate::simd::hex::bytes_to_hex_32(&priv_id.0);

        let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
        let mut role = roster.channel_roles(&chan_hex)[0].clone();
        role.name = "Lab Insiders".into();
        set_role(&relay, &community, &role).await.unwrap();
        merge_local_roster(&cid_hex, Some(&role), None);

        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let mut meta = held.channel(&priv_id).unwrap().metadata();
        meta.name = "staff".into();
        edit_channel_metadata(&relay, &held, &priv_id, &meta).await.unwrap();

        let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
        assert_eq!(
            roster.channel_roles(&chan_hex)[0].name,
            "Lab Insiders",
            "a deliberate name is left alone"
        );
    }

    #[tokio::test]
    async fn a_squatted_park_row_cannot_suppress_the_genuine_vend() {
        // Parking is reachable by ANY npub that can gift-wrap us — the bundle
        // self-certifies and its inputs are public for a public community. With a
        // single slot per channel, a stranger could pre-park and the admin's real
        // vend would be a silent no-op, leaving the member keyless with no retry.
        // Candidates + judge-them-all is what closes that.
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Squat", bed.relays.clone(), None).await.unwrap();
        let priv_id = create_private_channel(&bed.relay, &community, "mods").await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let chan_hex = crate::simd::hex::bytes_to_hex_32(&priv_id.0);
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let real_key = held.channel(&priv_id).unwrap().key.unwrap();
        let owner_hex = community.owner().unwrap().to_hex();

        bed.swap_to(&member);
        let mut member_view = held.clone();
        if let Some(c) = member_view.channels.iter_mut().find(|c| c.id.0 == priv_id.0) {
            c.key = None;
            c.epoch = Epoch(0);
        }
        crate::db::community::save_community_v2(&member_view).unwrap();
        let access = crate::community::roles::Role {
            role_id: "aa".repeat(32),
            name: "mods".into(),
            position: u32::MAX - 1,
            permissions: crate::community::roles::Permissions::empty(),
            scope: crate::community::roles::RoleScope::Channel(chan_hex.clone()),
            color: 0, rank: None, display: false, mentionable: false, extra: Default::default(),
        };
        let roster = crate::community::roles::CommunityRoles {
            grants: vec![crate::community::roles::MemberGrant {
                member: member.keys.public_key().to_hex(),
                role_ids: vec![access.role_id.clone()],
            }],
            roles: vec![access],
            everyone: None,
            overwrites: Vec::new(), syncs: Default::default(), legacy_channels: None, creators: Default::default(),
        };
        crate::db::community::set_community_roles(&cid_hex, &roster, 1).unwrap();

        // A stranger squats FIRST, at a higher epoch than the genuine vend.
        let stranger = Keys::generate().public_key().to_hex();
        crate::db::community::park_channel_key(&cid_hex, &chan_hex, 9, &[0xBA; 32], &stranger).unwrap();
        // The admin's real vend arrives after, at the true epoch.
        crate::db::community::park_channel_key(&cid_hex, &chan_hex, 1, &real_key, &owner_hex).unwrap();
        assert_eq!(
            crate::db::community::get_pending_channel_keys(&cid_hex).unwrap().len(),
            2,
            "the squatter never displaces the genuine vend — both are candidates"
        );

        let session = crate::db::current_session();
        let reloaded = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let adopted = absorb_parked_channel_keys(&reloaded, &session);
        assert_eq!(adopted.len(), 1, "exactly one adoption");

        let after = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let ch = after.channel(&priv_id).unwrap();
        assert_eq!(ch.key, Some(real_key), "the OWNER's key won, not the squatter's");
        assert_eq!(ch.epoch, Epoch(1), "at the genuine epoch");
        assert!(
            crate::db::community::get_pending_channel_keys(&cid_hex).unwrap().is_empty(),
            "and every candidate for the channel is discharged"
        );
    }

    #[tokio::test]
    async fn revoking_without_a_folded_access_role_refuses_instead_of_evicting_everyone() {
        // With no access role folded, the retained-set filter matches NOBODY, so
        // the rotation would cut off every legitimately entitled member while the
        // Grant it published revoked nothing. Reachable with no attacker: the
        // channel was made on another admin's client and its role hasn't folded.
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "NoRole", vec!["wss://r".into()], None).await.unwrap();
        let priv_id = create_private_channel(&relay, &community, "mods").await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let before = held.channel(&priv_id).unwrap().epoch;

        // Nothing serves the access role, cache, wraps held or plane: a withholding relay, or a
        // channel minted on another admin's client.
        crate::db::community::set_community_roles(&cid_hex, &crate::community::roles::CommunityRoles::default(), 0).unwrap();
        forget_held(&held);
        let mut blind = held.clone();
        blind.relays = vec!["wss://empty".into()];
        let err = revoke_channel_access(&relay, &blind, &priv_id, &Keys::generate().public_key())
            .await
            .unwrap_err();
        assert!(err.contains("has not folded"), "refuses with a retryable reason: {err}");

        let after = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        assert_eq!(after.channel(&priv_id).unwrap().epoch, before, "and rotates nothing");
    }

    // ── Live rekey-follow ────────────────────────────────────────────────────

    /// Publish an owner-grammar base rotation (Refounding) delivering `new_root`
    /// to each recipient. `rotator` is the seal signer (owner for a legit rotation,
    /// a stranger for the authority test); `prev_key` is the root it claims to
    /// extend (mismatch → a fork).
    async fn publish_base_rotation(
        relay: &MemoryRelay,
        community: &CommunityV2,
        rotator: &Keys,
        recipients: &[PublicKey],
        new_root: &[u8; 32],
        prev_key: &[u8; 32],
    ) {
        let new_epoch = Epoch(community.root_epoch.0 + 1);
        let prev_epoch = community.root_epoch;
        let prev_commit = super::super::derive::epoch_key_commitment(prev_epoch, prev_key);
        let group = base_rekey_group_key(&community.community_root, community.id(), new_epoch);
        let blobs: Vec<_> = recipients
            .iter()
            .map(|r| rekey::build_blob_local(rotator.secret_key(), &rotator.public_key().to_bytes(), r, RekeyScope::Root, new_epoch, new_root).unwrap())
            .collect();
        let events = rekey::build_rekey_chunks_local(rotator, &group, RekeyScope::Root, new_epoch, prev_epoch, &prev_commit, &blobs, 2_000, my_authority_citation(community, &rotator.public_key()).as_ref(), false).unwrap();
        for e in &events {
            relay.publish(e, &community.relays).await.unwrap();
        }
    }

    /// A base rotation that carries the containment marker (CORD-06 Severing).
    async fn publish_severing_base_rotation(
        relay: &MemoryRelay,
        community: &CommunityV2,
        rotator: &Keys,
        recipients: &[PublicKey],
        new_root: &[u8; 32],
        prev_key: &[u8; 32],
    ) {
        let new_epoch = Epoch(community.root_epoch.0 + 1);
        let prev_epoch = community.root_epoch;
        let prev_commit = super::super::derive::epoch_key_commitment(prev_epoch, prev_key);
        let group = base_rekey_group_key(&community.community_root, community.id(), new_epoch);
        let blobs: Vec<_> = recipients
            .iter()
            .map(|r| rekey::build_blob_local(rotator.secret_key(), &rotator.public_key().to_bytes(), r, RekeyScope::Root, new_epoch, new_root).unwrap())
            .collect();
        let events = rekey::build_rekey_chunks_local(rotator, &group, RekeyScope::Root, new_epoch, prev_epoch, &prev_commit, &blobs, 2_000, my_authority_citation(community, &rotator.public_key()).as_ref(), true).unwrap();
        for e in &events {
            relay.publish(e, &community.relays).await.unwrap();
        }
    }

    /// Attach a Private channel (key + epoch) to a held community and persist it.
    fn add_private_channel(community: &mut CommunityV2, id: ChannelId, key: [u8; 32], epoch: Epoch) {
        community.channels.push(ChannelV2 { id, name: "mods".into(), private: true, key: Some(key), epoch, voice: None, meta_custom: None, meta_extra: Default::default(), writers: None, sealed: None });
        crate::db::community::save_community_v2(community).unwrap();
    }

    #[tokio::test]
    async fn follow_rekeys_is_a_noop_without_rotations() {
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Still", vec!["wss://r".into()], None).await.unwrap();
        let session = crate::db::current_session();
        let follow = follow_rekeys(&relay, &community, &session).await.unwrap();
        assert!(follow.updated.is_none() && !follow.self_removed, "no rotation → nothing to adopt");
    }

    #[tokio::test]
    async fn follow_rekeys_adopts_an_owner_base_rotation() {
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Refound", vec!["wss://r".into()], None).await.unwrap();
        let new_root = [0xB1; 32];
        // Owner rotates the base to epoch 1, delivering the new root to me.
        publish_base_rotation(&relay, &community, &owner, &[owner.public_key()], &new_root, &community.community_root).await;

        let session = crate::db::current_session();
        let updated = follow_rekeys(&relay, &community, &session).await.unwrap().updated.expect("adopted");
        assert_eq!(updated.root_epoch, Epoch(1), "advanced one epoch");
        assert_eq!(updated.community_root, new_root, "adopted the fresh root");
        // The public channel now reads under the NEW root/epoch (its address moved).
        let addr = super::super::realtime::plane_authors(std::slice::from_ref(&updated));
        let general = updated.channels[0].id;
        let new_chat = channel_group_key(&new_root, &general, Epoch(1)).pk();
        assert!(addr.contains(&new_chat), "the public channel re-addresses under the new root");
    }

    #[tokio::test]
    async fn follow_rekeys_adopts_an_owner_private_channel_rotation() {
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let mut community = create_community(&relay, "PrivRot", vec!["wss://r".into()], None).await.unwrap();
        let priv_id = ChannelId([0x33; 32]);
        add_private_channel(&mut community, priv_id, [0x44; 32], Epoch(0));

        // Owner rotates the private channel to epoch 1 with a fresh key, delivered to me.
        let new_key = [0x55; 32];
        let prev_commit = super::super::derive::epoch_key_commitment(Epoch(0), &[0x44; 32]);
        let group = channel_rekey_group_key(&community.community_root, &priv_id, Epoch(1));
        let blob = rekey::build_blob_local(owner.secret_key(), &owner.public_key().to_bytes(), &owner.public_key(), RekeyScope::Channel(priv_id), Epoch(1), &new_key).unwrap();
        let events = rekey::build_rekey_chunks_local(&owner, &group, RekeyScope::Channel(priv_id), Epoch(1), Epoch(0), &prev_commit, &[blob], 2_000, None, false).unwrap();
        for e in &events {
            relay.publish(e, &community.relays).await.unwrap();
        }

        let session = crate::db::current_session();
        let updated = follow_rekeys(&relay, &community, &session).await.unwrap().updated.expect("adopted");
        let ch = updated.channel(&priv_id).unwrap();
        assert_eq!(ch.epoch, Epoch(1), "the private channel advanced an epoch");
        assert_eq!(ch.key, Some(new_key), "adopted the fresh channel key");
        assert_eq!(updated.root_epoch, Epoch(0), "the base is untouched by a channel rotation");
    }

    #[tokio::test]
    async fn a_whole_channel_fan_rotates_in_one_hop_without_crossing_keys() {
        // The fan is fetched concurrently and keyed by (channel, addressing root). A
        // mis-keyed prefetch cannot hand channel A's key to channel B — the blob's
        // scope is authenticated, so a wrong batch is refused rather than adopted — but
        // it CAN starve a channel of the chunks that are sitting on the plane for it,
        // which reads as "that channel never rotates" and strands its members.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let mut community = create_community(&relay, "FanRot", vec!["wss://r".into()], None).await.unwrap();

        // Distinct held key AND distinct fresh key per channel — a swap between any
        // two is then visible as an equality failure rather than a silent pass.
        let fan: Vec<(ChannelId, [u8; 32], [u8; 32])> = (0u8..12)
            .map(|i| (ChannelId([0x30 + i; 32]), [0x40 + i; 32], [0x80 + i; 32]))
            .collect();
        for (id, held, _) in &fan {
            add_private_channel(&mut community, *id, *held, Epoch(0));
        }

        for (id, held, fresh) in &fan {
            let prev_commit = super::super::derive::epoch_key_commitment(Epoch(0), held);
            let group = channel_rekey_group_key(&community.community_root, id, Epoch(1));
            let blob = rekey::build_blob_local(owner.secret_key(), &owner.public_key().to_bytes(), &owner.public_key(), RekeyScope::Channel(*id), Epoch(1), fresh).unwrap();
            let events = rekey::build_rekey_chunks_local(&owner, &group, RekeyScope::Channel(*id), Epoch(1), Epoch(0), &prev_commit, &[blob], 2_000, None, false).unwrap();
            for e in &events {
                relay.publish(e, &community.relays).await.unwrap();
            }
        }

        let session = crate::db::current_session();
        let updated = follow_rekeys(&relay, &community, &session).await.unwrap().updated.expect("adopted");
        for (id, _, fresh) in &fan {
            let ch = updated.channel(id).expect("channel survived the fan");
            assert_eq!(ch.epoch, Epoch(1), "every channel in the fan advanced");
            assert_eq!(ch.key, Some(*fresh), "each channel adopted ITS OWN key, not a neighbour's");
        }
    }

    #[tokio::test]
    async fn follow_rekeys_ignores_a_non_owner_rotation() {
        // A member holds the community_root, so they can derive the rekey group key
        // and mint a rotation — but they aren't the owner, so it's not adopted.
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Guarded", vec!["wss://r".into()], None).await.unwrap();
        let rogue = Keys::generate();
        publish_base_rotation(&relay, &community, &rogue, &[rogue.public_key()], &[0xEE; 32], &community.community_root).await;

        let session = crate::db::current_session();
        let follow = follow_rekeys(&relay, &community, &session).await.unwrap();
        assert!(follow.updated.is_none() && !follow.self_removed, "a non-owner rotation is not adopted");
    }

    #[tokio::test]
    async fn follow_rekeys_ignores_a_rotation_off_the_wrong_prev() {
        // A rotation whose prevcommit doesn't match the key I hold is a fork, not an
        // extension — never adopted (would splice me onto an unrelated chain).
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Forked", vec!["wss://r".into()], None).await.unwrap();
        // prev_key ≠ the real community_root → the continuity check reads Fork.
        publish_base_rotation(&relay, &community, &owner, &[owner.public_key()], &[0xB2; 32], &[0x00; 32]).await;

        let session = crate::db::current_session();
        let follow = follow_rekeys(&relay, &community, &session).await.unwrap();
        assert!(follow.updated.is_none(), "a fork off the wrong prev is not adopted");
    }

    #[tokio::test]
    async fn follow_rekeys_holds_on_an_incomplete_rotation() {
        // A 2-chunk rotation with only chunk 1 present can never conclude — not an
        // adoption, and crucially NOT a removal (a missing chunk might carry my blob).
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Partial", vec!["wss://r".into()], None).await.unwrap();
        let new_epoch = Epoch(1);
        let prev_commit = super::super::derive::epoch_key_commitment(Epoch(0), &community.community_root);
        let group = base_rekey_group_key(&community.community_root, community.id(), new_epoch);
        // Chunk 1 of a declared 2, carrying someone else's blob (not mine).
        let other = Keys::generate();
        let blob = rekey::build_blob_local(owner.secret_key(), &owner.public_key().to_bytes(), &other.public_key(), RekeyScope::Root, new_epoch, &[0xB3; 32]).unwrap();
        let rumor = rekey::build_rekey_rumor(owner.public_key(), RekeyScope::Root, new_epoch, Epoch(0), &prev_commit, &[blob], 1, 2, 2_000, None, false).unwrap();
        let (wrap, _) = rekey::seal_rekey_chunk(&rumor, &group, &owner, Timestamp::from_secs(2_000)).unwrap();
        relay.publish(&wrap, &community.relays).await.unwrap();

        let session = crate::db::current_session();
        let follow = follow_rekeys(&relay, &community, &session).await.unwrap();
        assert!(follow.updated.is_none() && !follow.self_removed, "an incomplete rotation neither adopts nor removes");
    }

    #[tokio::test]
    async fn follow_rekeys_removes_a_member_dropped_by_a_base_rotation() {
        // Realistic two-actor removal: the owner Refounds the base and delivers the
        // new root to a THIRD party, not the member — a complete rotation with no
        // blob for the member is a removal.
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Evict", bed.relays.clone(), None).await.unwrap();
        send_direct_invite(&bed.relay, &community, &member.keys.public_key(), None, None).await.unwrap();

        bed.swap_to(&member);
        let invite_wrap = fetch_direct_invite(&bed.relay, &bed.relays, &member.keys.public_key()).await;
        let joined = accept_direct_invite(&bed.relay, &invite_wrap).await.unwrap();

        // Owner rotates, delivering only to a stranger (the member is dropped).
        bed.swap_to(&owner);
        let stranger = Keys::generate();
        publish_base_rotation(&bed.relay, &community, &owner.keys, &[stranger.public_key()], &[0xC4; 32], &community.community_root).await;

        // The member's follow concludes removal (a complete rotation without their blob).
        bed.swap_to(&member);
        let session = crate::db::current_session();
        let follow = follow_rekeys(&bed.relay, &joined, &session).await.unwrap();
        assert!(follow.self_removed, "a complete base rotation dropping the member removes them");
        assert!(follow.updated.is_none(), "a removed member adopts nothing");
    }

    #[tokio::test]
    async fn a_ban_holders_channel_rotation_stands_and_a_bitless_ones_doesnt() {
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Refounder", vec!["wss://r".into()], None).await.unwrap();
        let moderator = Keys::generate();
        let rid = "b1".repeat(32);
        publish_role(&relay, &community, &owner, &admin_role(&rid, Permissions::BAN), 1).await;
        publish_grant(&relay, &community, &owner, &moderator.public_key(), vec![rid], 1).await;
        let mut community = follow_control(&relay, &community).await.unwrap().updated.unwrap_or(community);
        let priv_id = ChannelId([0x34; 32]);
        let key1 = [0x45; 32];
        add_private_channel(&mut community, priv_id, key1, Epoch(1));
        let cite = cite_on_relay(&relay, &community, &moderator).await;
        let key2 = [0x56; 32];
        let prev_commit = super::super::derive::epoch_key_commitment(Epoch(1), &key1);
        let group = channel_rekey_group_key(&community.community_root, &priv_id, Epoch(2));
        let blob = rekey::build_blob_local(moderator.secret_key(), &moderator.public_key().to_bytes(), &owner.public_key(), RekeyScope::Channel(priv_id), Epoch(2), &key2).unwrap();
        for e in rekey::build_rekey_chunks_local(&moderator, &group, RekeyScope::Channel(priv_id), Epoch(2), Epoch(1), &prev_commit, &[blob], 2_000, cite.as_ref(), false).unwrap() {
            relay.publish(&e, &community.relays).await.unwrap();
        }
        let session = crate::db::current_session();
        let updated = follow_rekeys(&relay, &community, &session).await.unwrap().updated.expect("a BAN holder's rotation stands");
        assert_eq!(updated.channel(&priv_id).unwrap().key, Some(key2));

        let stranger = Keys::generate();
        let prev3 = super::super::derive::epoch_key_commitment(Epoch(2), &key2);
        let group3 = channel_rekey_group_key(&updated.community_root, &priv_id, Epoch(3));
        let blob3 = rekey::build_blob_local(stranger.secret_key(), &stranger.public_key().to_bytes(), &owner.public_key(), RekeyScope::Channel(priv_id), Epoch(3), &[0x57; 32]).unwrap();
        for e in rekey::build_rekey_chunks_local(&stranger, &group3, RekeyScope::Channel(priv_id), Epoch(3), Epoch(2), &prev3, &[blob3], 3_000, None, false).unwrap() {
            relay.publish(&e, &updated.relays).await.unwrap();
        }
        assert!(follow_rekeys(&relay, &updated, &session).await.unwrap().updated.is_none(), "nobody without the bits rotates a Channel");
    }

    #[tokio::test]
    async fn follow_rekeys_finds_a_channel_rekey_under_an_archived_prior_root() {
        // PROTO-B2 regression: a Refounding's channel rekeys ride the PRIOR root
        // (CORD-06 §3). A follower who adopted the BASE first (the live window:
        // the base crate landed and was walked before the channel crates) must
        // still find them — the lookup fans across the archived roots, not just
        // the current one.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let mut community = create_community(&relay, "Strand", vec!["wss://r".into()], None).await.unwrap();
        let root0 = community.community_root;
        let priv_id = ChannelId([0x33; 32]);
        let key1 = [0x44; 32];
        add_private_channel(&mut community, priv_id, key1, Epoch(1));

        // The refounder's channel rekey (1 → 2), sealed + addressed under the PRIOR
        // root (root0), delivering the fresh key to me.
        let key2 = [0x55; 32];
        let prev_commit = super::super::derive::epoch_key_commitment(Epoch(1), &key1);
        let group = channel_rekey_group_key(&root0, &priv_id, Epoch(2));
        let blob = rekey::build_blob_local(owner.secret_key(), &owner.public_key().to_bytes(), &owner.public_key(), RekeyScope::Channel(priv_id), Epoch(2), &key2).unwrap();
        for e in rekey::build_rekey_chunks_local(&owner, &group, RekeyScope::Channel(priv_id), Epoch(2), Epoch(1), &prev_commit, &[blob], 2_000, None, false).unwrap() {
            relay.publish(&e, &community.relays).await.unwrap();
        }

        // Simulate the base having ALREADY advanced (the stranding order): the head
        // moved to a fresh root while root0 sits in the epoch-key archive (where
        // genesis put it).
        community.community_root = [0xB7; 32];
        community.root_epoch = Epoch(1);
        crate::db::community::save_community_v2(&community).unwrap();

        let session = crate::db::current_session();
        let updated = follow_rekeys(&relay, &community, &session).await.unwrap().updated.expect("the prior-root crate is found");
        let ch = updated.channel(&priv_id).unwrap();
        assert_eq!(ch.epoch, Epoch(2), "the channel advanced despite the moved base");
        assert_eq!(ch.key, Some(key2), "adopted the key delivered under the prior root");
    }

    #[tokio::test]
    async fn follow_rekeys_keyless_cursor_walks_past_an_excluding_rotation_then_adopts() {
        // A keyless private channel (announced by vsk-2, key not yet held) has no
        // chain, so its epoch is a scan cursor: a complete rotation that excludes
        // us advances the cursor (never a removal — we were never in); a later
        // rotation that includes us is the entry point.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let mut community = create_community(&relay, "Cursor", vec!["wss://r".into()], None).await.unwrap();
        let priv_id = ChannelId([0x66; 32]);
        community.channels.push(ChannelV2 { id: priv_id, name: "vault".into(), private: true, key: None, epoch: Epoch(0), voice: None, meta_custom: None, meta_extra: Default::default(), writers: None, sealed: None });
        crate::db::community::save_community_v2(&community).unwrap();
        let community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        assert!(community.channel(&priv_id).unwrap().key.is_none(), "keyless survives the round-trip");

        // Epoch 1: the creation delivery went to a stranger only (pre-dates us).
        let stranger = Keys::generate();
        let key1 = [0x71; 32];
        let pc1 = super::super::derive::epoch_key_commitment(Epoch(0), &community.community_root);
        let g1 = channel_rekey_group_key(&community.community_root, &priv_id, Epoch(1));
        let b1 = rekey::build_blob_local(owner.secret_key(), &owner.public_key().to_bytes(), &stranger.public_key(), RekeyScope::Channel(priv_id), Epoch(1), &key1).unwrap();
        for e in rekey::build_rekey_chunks_local(&owner, &g1, RekeyScope::Channel(priv_id), Epoch(1), Epoch(0), &pc1, &[b1], 2_000, None, false).unwrap() {
            relay.publish(&e, &community.relays).await.unwrap();
        }
        // Epoch 2: a later rotation includes ME (e.g. a removal-forced re-mint whose
        // recipient set is the CURRENT members).
        let key2 = [0x72; 32];
        let pc2 = super::super::derive::epoch_key_commitment(Epoch(1), &key1);
        let g2 = channel_rekey_group_key(&community.community_root, &priv_id, Epoch(2));
        let b2 = rekey::build_blob_local(owner.secret_key(), &owner.public_key().to_bytes(), &owner.public_key(), RekeyScope::Channel(priv_id), Epoch(2), &key2).unwrap();
        for e in rekey::build_rekey_chunks_local(&owner, &g2, RekeyScope::Channel(priv_id), Epoch(2), Epoch(1), &pc2, &[b2], 2_100, None, false).unwrap() {
            relay.publish(&e, &community.relays).await.unwrap();
        }

        // ONE follow: the cursor walks 0→1 (excluded, still keyless) and 1→2 (my
        // blob — adopt), because each real step re-loops.
        let session = crate::db::current_session();
        let updated = follow_rekeys(&relay, &community, &session).await.unwrap().updated.expect("the walk lands on the included epoch");
        let ch = updated.channel(&priv_id).unwrap();
        assert_eq!(ch.epoch, Epoch(2), "cursor walked through the excluding epoch to the included one");
        assert_eq!(ch.key, Some(key2), "adopted the delivery that includes us");
    }

    #[tokio::test]
    async fn follow_rekeys_honors_an_admin_channel_rotation_but_never_a_strangers() {
        // CORD-06 §Authority: a CHANNEL rekey is honored from the owner or a
        // MANAGE_CHANNELS holder under the persisted roster — so an admin-run
        // rotation keys members up; a mere keyholder's forgery never does.
        use crate::community::roles::{CommunityRoles, MemberGrant, Role};
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let mut community = create_community(&relay, "AdminRot", vec!["wss://r".into()], None).await.unwrap();
        let priv_id = ChannelId([0x88; 32]);
        let key1 = [0x91; 32];
        add_private_channel(&mut community, priv_id, key1, Epoch(1));

        // Persist a roster granting `admin` the Admin role (MANAGE_CHANNELS ⊂ ADMIN_ALL).
        let admin = Keys::generate();
        let role = Role::admin("aa".repeat(32));
        let roster = CommunityRoles {
            roles: vec![role.clone()],
            grants: vec![MemberGrant { member: admin.public_key().to_hex(), role_ids: vec![role.role_id.clone()] }],
            everyone: None,
            overwrites: Vec::new(), syncs: Default::default(), legacy_channels: None, creators: Default::default(),
        };
        seed_roster_with_heads(&community, &roster, 1_000);

        // The ADMIN rotates the channel 1 → 2, delivering to me: adopted.
        let key2 = [0x92; 32];
        let pc = super::super::derive::epoch_key_commitment(Epoch(1), &key1);
        let g2 = channel_rekey_group_key(&community.community_root, &priv_id, Epoch(2));
        let me_pk = crate::state::MY_SECRET_KEY.to_keys().unwrap().public_key();
        let blob = rekey::build_blob_local(admin.secret_key(), &admin.public_key().to_bytes(), &me_pk, RekeyScope::Channel(priv_id), Epoch(2), &key2).unwrap();
        for e in rekey::build_rekey_chunks_local(&admin, &g2, RekeyScope::Channel(priv_id), Epoch(2), Epoch(1), &pc, &[blob], 2_000, my_authority_citation(&community, &admin.public_key()).as_ref(), false).unwrap() {
            relay.publish(&e, &community.relays).await.unwrap();
        }
        let session = crate::db::current_session();
        let updated = follow_rekeys(&relay, &community, &session).await.unwrap().updated.expect("an admin rotation is honored");
        assert_eq!(updated.channel(&priv_id).unwrap().key, Some(key2), "adopted the admin's key");

        // A STRANGER (keyholder, no roster standing) rotates 2 → 3: refused.
        let rogue = Keys::generate();
        let key3 = [0x93; 32];
        let pc3 = super::super::derive::epoch_key_commitment(Epoch(2), &key2);
        let g3 = channel_rekey_group_key(&updated.community_root, &priv_id, Epoch(3));
        let rb = rekey::build_blob_local(rogue.secret_key(), &rogue.public_key().to_bytes(), &me_pk, RekeyScope::Channel(priv_id), Epoch(3), &key3).unwrap();
        for e in rekey::build_rekey_chunks_local(&rogue, &g3, RekeyScope::Channel(priv_id), Epoch(3), Epoch(2), &pc3, &[rb], 2_100, None, false).unwrap() {
            relay.publish(&e, &updated.relays).await.unwrap();
        }
        let follow = follow_rekeys(&relay, &updated, &session).await.unwrap();
        assert!(follow.updated.is_none(), "a stranger's channel rotation is never adopted");
    }

    #[tokio::test]
    async fn a_non_outranking_admins_rotation_never_concludes_my_removal() {
        // CORD-06 §Authority: the Rotator must strictly OUTRANK every removed
        // target. An equal-rank bit-holder's complete rotation that skips my blob
        // must read Stay (my record survives); the OWNER's reads Removed. Needs a
        // two-account bed: the follower must be a NON-owner admin.
        use crate::community::roles::{CommunityRoles, MemberGrant, Role};
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Outrank", bed.relays.clone(), None).await.unwrap();

        // The MEMBER's device: holds the community + the private channel, with a
        // persisted roster granting the member AND a peer the same Admin role.
        bed.swap_to(&member);
        let mut held = community.clone();
        let priv_id = ChannelId([0xAB; 32]);
        let key1 = [0xA1; 32];
        add_private_channel(&mut held, priv_id, key1, Epoch(1));
        let peer = Keys::generate();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let role = Role::admin("bb".repeat(32));
        let roster = CommunityRoles {
            roles: vec![role.clone()],
            grants: vec![
                MemberGrant { member: peer.public_key().to_hex(), role_ids: vec![role.role_id.clone()] },
                MemberGrant { member: member.keys.public_key().to_hex(), role_ids: vec![role.role_id.clone()] },
            ],
            everyone: None,
            overwrites: Vec::new(), syncs: Default::default(), legacy_channels: None, creators: Default::default(),
        };
        crate::db::community::set_community_roles(&cid_hex, &roster, 1_000).unwrap();

        // The equal-rank PEER rotates 1 → 2 delivering only to themselves.
        let key2 = [0xA2; 32];
        let pc = super::super::derive::epoch_key_commitment(Epoch(1), &key1);
        let g2 = channel_rekey_group_key(&held.community_root, &priv_id, Epoch(2));
        let pb = rekey::build_blob_local(peer.secret_key(), &peer.public_key().to_bytes(), &peer.public_key(), RekeyScope::Channel(priv_id), Epoch(2), &key2).unwrap();
        for e in rekey::build_rekey_chunks_local(&peer, &g2, RekeyScope::Channel(priv_id), Epoch(2), Epoch(1), &pc, &[pb], 2_000, my_authority_citation(&held, &peer.public_key()).as_ref(), false).unwrap() {
            bed.relay.publish(&e, &held.relays).await.unwrap();
        }
        let session = crate::db::current_session();
        let follow = follow_rekeys(&bed.relay, &held, &session).await.unwrap();
        assert!(follow.updated.is_none(), "an equal-rank rotation excluding me is Stay, never my removal");
        let reloaded = crate::db::community::load_community_v2(held.id()).unwrap().unwrap();
        assert!(reloaded.channel(&priv_id).is_some(), "my channel record survives the peer's rotation");

        // The OWNER's rotation excluding me IS a removal (owner outranks everyone).
        let key3 = [0xA3; 32];
        let stranger = Keys::generate();
        let ob = rekey::build_blob_local(owner.keys.secret_key(), &owner.keys.public_key().to_bytes(), &stranger.public_key(), RekeyScope::Channel(priv_id), Epoch(2), &key3).unwrap();
        for e in rekey::build_rekey_chunks_local(&owner.keys, &g2, RekeyScope::Channel(priv_id), Epoch(2), Epoch(1), &pc, &[ob], 2_100, None, false).unwrap() {
            bed.relay.publish(&e, &held.relays).await.unwrap();
        }
        let follow = follow_rekeys(&bed.relay, &held, &session).await.unwrap();
        let updated = follow.updated.expect("the owner's removal folds");
        let cut = updated.channel(&priv_id).expect("the channel stays known, so a later rotation can name me again");
        assert!(cut.key.is_none() && cut.epoch == Epoch(2), "the owner's exclusion cuts my key at its epoch");
    }

    #[tokio::test]
    async fn a_public_channel_made_private_keys_who_it_lets_in_and_keeps_its_past() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, member) = TestBed::new();
        let held = |c: &CommunityV2| crate::db::community::load_community_v2(c.id()).unwrap().unwrap();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Convert", bed.relays.clone(), None).await.unwrap();
        activate_roles_v2(&bed.relay, &community, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
        follow_control(&bed.relay, &community).await.unwrap();
        let general = community.channels[0].id;
        let m = member.keys.public_key();
        send_message(&bed.relay, &held(&community), &general, "said in public").await.unwrap();
        send_direct_invite(&bed.relay, &held(&community), &m, None, None).await.unwrap();
        bed.swap_to(&member);
        accept_direct_invite(&bed.relay, &fetch_direct_invite(&bed.relay, &bed.relays, &m).await).await.unwrap();
        follow_control(&bed.relay, &held(&community)).await.unwrap();
        let before = held(&community);

        // The flag alone is refused: the conversion is its own action.
        bed.swap_to(&owner);
        let mut meta = held(&community).channel(&general).unwrap().metadata();
        meta.private = true;
        assert!(edit_channel_metadata(&bed.relay, &held(&community), &general, &meta).await.is_err());
        set_overwrite(&bed.relay, &held(&community), general.0, OverwriteTarget::Member(m.to_hex()), Permissions::VIEW_CHANNEL, 0).await.unwrap();
        privatize_channel(&bed.relay, &held(&community), &general).await.unwrap();
        let mine = held(&community).channel(&general).cloned().unwrap();
        assert!(mine.private && mine.key.is_some() && mine.epoch == Epoch(1) && mine.public_until().is_some());
        let editions = fetch_control(&bed.relay, &held(&community)).await;
        let head = editions.iter().filter(|e| e.vsk == vsk::CHANNEL_METADATA && e.entity_id == general.0).max_by_key(|e| e.version).unwrap();
        assert!(control::parse_sealed_channel_meta(&head.content).is_some() && !head.content.contains("general"), "its details seal at once");
        send_message(&bed.relay, &held(&community), &general, "said in private").await.unwrap();

        // A member it lets in takes the key from the rotation and reads both eras.
        bed.swap_to(&member);
        follow_control(&bed.relay, &held(&community)).await.unwrap();
        let dark = held(&community).channel(&general).cloned().unwrap();
        assert!(dark.private && dark.key.is_none(), "a reader holding it public takes it private, keyless");
        follow_rekeys(&bed.relay, &held(&community), &crate::db::current_session()).await.unwrap();
        let mut keyed = held(&community);
        unseal_held(&mut keyed);
        let ch = keyed.channel(&general).cloned().unwrap();
        assert!(ch.key.is_some() && ch.name == "general", "{ch:?}");
        crate::db::community::save_community_v2(&keyed).unwrap();
        let texts = texts_in(&bed.relay, &keyed, &general).await;
        assert!(texts.contains(&"said in public".to_string()) && texts.contains(&"said in private".to_string()), "{texts:?}");

        // A post at the old public plane after the switch stands nowhere.
        send_message(&bed.relay, &before, &general, "too late").await.unwrap();
        assert!(!texts_in(&bed.relay, &held(&community), &general).await.contains(&"too late".to_string()));
    }

    #[tokio::test]
    async fn junk_at_a_channels_rekey_address_takes_no_epoch_from_a_conversion() {
        let (bed, owner, member) = TestBed::new();
        let held = |c: &CommunityV2| crate::db::community::load_community_v2(c.id()).unwrap().unwrap();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Junk", bed.relays.clone(), None).await.unwrap();
        activate_roles_v2(&bed.relay, &community, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
        follow_control(&bed.relay, &community).await.unwrap();
        let general = community.channels[0].id;
        // Any root holder can seal a 3303 at epoch 1's address; nobody honors it.
        let squatter = Keys::generate();
        let group = channel_rekey_group_key(&community.community_root, &general, Epoch(1));
        let blob = rekey::build_blob_local(squatter.secret_key(), &squatter.public_key().to_bytes(), &squatter.public_key(), RekeyScope::Channel(general), Epoch(1), &[0x58; 32]).unwrap();
        let prev = super::super::derive::epoch_key_commitment(Epoch(0), &community.community_root);
        for e in rekey::build_rekey_chunks_local(&squatter, &group, RekeyScope::Channel(general), Epoch(1), Epoch(0), &prev, &[blob], 2_000, None, false).unwrap() {
            bed.relay.publish(&e, &community.relays).await.unwrap();
        }
        let m = member.keys.public_key();
        send_direct_invite(&bed.relay, &held(&community), &m, None, None).await.unwrap();
        set_overwrite(&bed.relay, &held(&community), general.0, crate::community::roles::OverwriteTarget::Member(m.to_hex()), Permissions::VIEW_CHANNEL, 0).await.unwrap();
        privatize_channel(&bed.relay, &held(&community), &general).await.unwrap();
        assert_eq!(held(&community).channel(&general).unwrap().epoch, Epoch(1), "junk takes no epoch");

        bed.swap_to(&member);
        accept_direct_invite(&bed.relay, &fetch_direct_invite(&bed.relay, &bed.relays, &m).await).await.unwrap();
        follow_control(&bed.relay, &held(&community)).await.unwrap();
        follow_rekeys(&bed.relay, &held(&community), &crate::db::current_session()).await.unwrap();
        assert!(held(&community).channel(&general).unwrap().key.is_some(), "the member takes the key the conversion minted");
    }

    #[tokio::test]
    async fn privatising_again_climbs_past_an_era_this_converter_never_held() {
        let (bed, owner, member) = TestBed::new();
        let held = |c: &CommunityV2| crate::db::community::load_community_v2(c.id()).unwrap().unwrap();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Again", bed.relays.clone(), None).await.unwrap();
        activate_roles_v2(&bed.relay, &community, crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
        follow_control(&bed.relay, &community).await.unwrap();
        let m = member.keys.public_key();
        let managers = create_role_v2(&bed.relay, &held(&community), "Managers", 0, Permissions::MANAGE_CHANNELS | crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
        set_member_roles(&bed.relay, &held(&community), &m, vec![managers]).await.unwrap();
        let ch = create_private_channel(&bed.relay, &held(&community), "ops").await.unwrap();
        let mut public = held(&community).channel(&ch).unwrap().metadata();
        public.private = false;
        edit_channel_metadata(&bed.relay, &held(&community), &ch, &public).await.unwrap();
        send_direct_invite(&bed.relay, &held(&community), &m, None, None).await.unwrap();

        bed.swap_to(&member);
        accept_direct_invite(&bed.relay, &fetch_direct_invite(&bed.relay, &bed.relays, &m).await).await.unwrap();
        follow_control(&bed.relay, &held(&community)).await.unwrap();
        assert!(!held(&community).channel(&ch).unwrap().private);
        privatize_channel(&bed.relay, &held(&community), &ch).await.unwrap();
        let mine = held(&community).channel(&ch).cloned().unwrap();
        assert_eq!(mine.epoch, Epoch(2), "the old era's epoch 1 is taken, though this device never held it");

        bed.swap_to(&owner);
        follow_control(&bed.relay, &held(&community)).await.unwrap();
        follow_rekeys(&bed.relay, &held(&community), &crate::db::current_session()).await.unwrap();
        let theirs = held(&community).channel(&ch).cloned().unwrap();
        assert_eq!((theirs.epoch, theirs.key), (Epoch(2), mine.key), "the owner walks to the same key");
    }

    /// Publish a 13302 (signed by `me`) carrying a leave tombstone for `cid_hex` at
    /// `removed_at` — simulating a sibling device having left that community.
    async fn publish_remote_tombstone(relay: &MemoryRelay, me: &Keys, relays: &[String], cid_hex: &str, removed_at: u64) {
        let doc = super::super::list::CommunityList {
            entries: vec![],
            tombstones: vec![super::super::list::Tombstone { community_id: cid_hex.to_string(), removed_at, extra: Default::default() }],
            extra: Default::default(),
        };
        // A sibling device writes fragments, like any §8 client.
        for (i, frag) in super::super::list_frag::fragment(&doc).iter().enumerate() {
            let event = super::super::list_frag::build_fragment_event_keys(me, frag, i, now_ms() / 1000).unwrap();
            relay.publish(&event, relays).await.unwrap();
        }
    }

    #[tokio::test]
    async fn joining_one_community_does_not_resurrect_a_sibling_left_community() {
        // W1 (send side): a sibling device left X (a remote tombstone). Joining a
        // DIFFERENT community must not re-add X to the 13302 with added_at=now,
        // which would silently undo the leave everywhere.
        let (_tmp, _guard, me) = init_test_db();
        let relay = MemoryRelay::new();
        let x = create_community(&relay, "X", vec!["wss://r".into()], None).await.unwrap();
        let x_hex = crate::simd::hex::bytes_to_hex_32(&x.id().0);

        // A sibling leaves X: a remote tombstone strictly newer than X's add.
        publish_remote_tombstone(&relay, &me, &x.relays, &x_hex, now_ms() + 10_000).await;

        // Now join a different community Y → republish(just_joined = Y).
        let y = create_community(&relay, "Y", vec!["wss://r".into()], None).await.unwrap();
        republish_community_list(&relay, Some(y.id())).await.unwrap();

        // X must still read as LEFT in the published list; Y must be live.
        let list = fetch_fragments(&relay, &x.relays).await.unwrap().unwrap().list;
        assert!(!list.is_live(&x_hex), "joining Y did not resurrect the sibling-left X");
        assert!(list.is_live(&crate::simd::hex::bytes_to_hex_32(&y.id().0)), "Y is live");
    }

    #[tokio::test]
    async fn sync_tears_down_a_community_a_sibling_left() {
        // W1 (receive side): a community still held locally that the synced 13302
        // shows tombstoned-and-not-live is torn down, so a leave propagates.
        let (_tmp, _guard, me) = init_test_db();
        let relay = MemoryRelay::new();
        let x = create_community(&relay, "Leaveme", vec!["wss://r".into()], None).await.unwrap();
        let x_hex = crate::simd::hex::bytes_to_hex_32(&x.id().0);
        assert!(crate::db::community::load_community_v2(x.id()).unwrap().is_some(), "held before sync");

        publish_remote_tombstone(&relay, &me, &x.relays, &x_hex, now_ms() + 10_000).await;
        sync_community_list(&relay, &x.relays).await.unwrap();
        assert!(crate::db::community::load_community_v2(x.id()).unwrap().is_none(), "the sibling's leave tore X down locally");
    }

    /// Publish a List copy (signed by `me`) written at `at_secs`: a sibling device's, or an older
    /// one a relay still serves.
    async fn publish_remote_list(
        relay: &MemoryRelay,
        me: &Keys,
        relays: &[String],
        entries: Vec<super::super::list::CommunityListEntry>,
        tombstones: Vec<super::super::list::Tombstone>,
        at_secs: u64,
    ) {
        let doc = super::super::list::CommunityList { entries, tombstones, extra: Default::default() };
        // Everywhere the List is read from, so this copy is the one every read finds.
        let relays = list_read_relays(relays).await;
        for (i, frag) in super::super::list_frag::fragment(&doc).iter().enumerate() {
            let event = super::super::list_frag::build_fragment_event_keys(me, frag, i, at_secs).unwrap();
            relay.publish(&event, &relays).await.unwrap();
        }
    }

    fn listed(community: &CommunityV2, added_at: u64) -> super::super::list::CommunityListEntry {
        let jm = join_material(community);
        super::super::list::CommunityListEntry {
            community_id: crate::simd::hex::bytes_to_hex_32(&community.id().0),
            seed: jm.clone(),
            current: jm,
            added_at,
            extra: Default::default(),
        }
    }

    /// A member holding `X`, and a second device of that member's account that holds nothing yet.
    async fn member_with_a_second_device() -> (TestBed, Actor, CommunityV2) {
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let x = create_community(&bed.relay, "Synced", bed.relays.clone(), None).await.unwrap();
        let link = mint_public_link(&bed.relay, &x, "https://vectorapp.io", None, None).await.unwrap();
        bed.swap_to(&member);
        let joined = accept_public_link(&bed.relay, &link.url).await.unwrap();
        let device = Actor { keys: member.keys.clone(), account: account_name((now_ms() % 1_000_000_000) as u32) };
        bed.swap_to(&device);
        (bed, device, joined)
    }

    #[tokio::test]
    async fn an_older_copy_of_the_list_never_brings_back_a_community_this_device_left() {
        let (bed, device, x) = member_with_a_second_device().await;
        let x_hex = crate::simd::hex::bytes_to_hex_32(&x.id().0);
        let joined_at = now_ms() - 60_000;
        // Left on this device; then a relay serves a copy from before the leave.
        note_local_removal(&x_hex, joined_at + 30_000);
        publish_remote_list(&bed.relay, &device.keys, &bed.relays, vec![listed(&x, joined_at)], vec![], now_ms() / 1000 + 5).await;

        let out = sync_community_list(&bed.relay, &bed.relays).await.unwrap();
        assert!(out.joined.is_empty() && out.removed.is_empty(), "the stale copy is never adopted, not even briefly");
        assert!(crate::db::community::load_community_v2(x.id()).unwrap().is_none(), "the stale copy did not rejoin it");
    }

    #[tokio::test]
    async fn a_leave_made_while_an_adoption_runs_answers_it() {
        let (bed, device, x) = member_with_a_second_device().await;
        let x_hex = crate::simd::hex::bytes_to_hex_32(&x.id().0);
        publish_remote_list(&bed.relay, &device.keys, &bed.relays, vec![listed(&x, now_ms() - 60_000)], vec![], now_ms() / 1000 + 5).await;

        // The leave lands while the adoption walks the community's planes.
        struct LeaveMidAdoption<'a> {
            relay: &'a MemoryRelay,
            community_id: String,
            left: std::sync::atomic::AtomicBool,
        }
        #[async_trait::async_trait]
        impl Transport for LeaveMidAdoption<'_> {
            async fn fetch_plane(&self, plane: &Keys, query: &Query, relays: &[String]) -> Result<crate::community::transport::PlaneFetch, String> {
                self.walked(query);
                self.relay.fetch_plane(plane, query, relays).await
            }
            async fn publish(&self, e: &Event, r: &[String]) -> Result<(), String> {
                self.relay.publish(e, r).await
            }
            async fn publish_durable(&self, e: &Event, r: &[String]) -> Result<(), String> {
                self.relay.publish_durable(e, r).await
            }
            async fn fetch(&self, q: &Query, r: &[String]) -> Result<Vec<Event>, String> {
                self.walked(q);
                self.relay.fetch(q, r).await
            }
        }
        impl LeaveMidAdoption<'_> {
            /// Past the List read, every fetch is the adoption's own walk.
            fn walked(&self, query: &Query) {
                if !query.kinds.contains(&crate::community::v2::kind::COMMUNITY_LIST_FRAG) && !self.left.swap(true, std::sync::atomic::Ordering::SeqCst) {
                    note_local_removal(&self.community_id, now_ms());
                }
            }
        }
        let transport = LeaveMidAdoption { relay: &bed.relay, community_id: x_hex.clone(), left: false.into() };
        let out = sync_community_list(&transport, &bed.relays).await.unwrap();
        assert!(out.joined.is_empty() && out.removed.iter().any(|(id, _)| *id == x_hex), "the adoption is undone, and said so");
        assert!(crate::db::community::load_community_v2(x.id()).unwrap().is_none(), "nothing of it is left held");
    }

    #[tokio::test]
    async fn an_adopted_community_dates_from_its_membership_so_a_later_leave_still_removes_it() {
        let (bed, device, x) = member_with_a_second_device().await;
        let x_hex = crate::simd::hex::bytes_to_hex_32(&x.id().0);
        let joined_at = now_ms() - 3_600_000;
        publish_remote_list(&bed.relay, &device.keys, &bed.relays, vec![listed(&x, joined_at)], vec![], now_ms() / 1000 + 5).await;
        sync_community_list(&bed.relay, &bed.relays).await.unwrap();
        let held = crate::db::community::load_community_v2(x.id()).unwrap().expect("adopted");
        assert!(held.created_at_ms <= joined_at, "held since the membership, not since the adoption");

        // A sibling's leave made after that membership, but before this adoption ran.
        let leave = super::super::list::Tombstone { community_id: x_hex.clone(), removed_at: joined_at + 5_000, extra: Default::default() };
        publish_remote_list(&bed.relay, &device.keys, &bed.relays, vec![listed(&x, joined_at)], vec![leave], now_ms() / 1000 + 10).await;
        sync_community_list(&bed.relay, &bed.relays).await.unwrap();
        assert!(crate::db::community::load_community_v2(x.id()).unwrap().is_none(), "the leave outranks the adopted copy");
        republish_community_list(&bed.relay, None).await.unwrap();
        let list = fetch_fragments(&bed.relay, &bed.relays).await.unwrap().unwrap().list;
        assert!(!list.is_live(&x_hex), "and nothing writes it back");
    }

    #[tokio::test]
    async fn a_rejoined_community_survives_a_stale_tombstone_on_sync() {
        // The re-join case must NOT be torn down: a fresh join re-adds live (beating
        // the tombstone), so a later sync keeps it.
        let (_tmp, _guard, me) = init_test_db();
        let relay = MemoryRelay::new();
        let x = create_community(&relay, "Rejoin", vec!["wss://r".into()], None).await.unwrap();
        let x_hex = crate::simd::hex::bytes_to_hex_32(&x.id().0);
        // A stale tombstone from a prior leave (OLDER than the current hold's re-add).
        publish_remote_tombstone(&relay, &me, &x.relays, &x_hex, 1).await;
        // Re-record the membership (a re-join) → live entry at now >> 1.
        republish_community_list(&relay, Some(x.id())).await.unwrap();
        sync_community_list(&relay, &x.relays).await.unwrap();
        assert!(crate::db::community::load_community_v2(x.id()).unwrap().is_some(), "a re-joined community is not torn down by a stale tombstone");
    }

    #[tokio::test]
    async fn a_join_outranks_a_removal_stamped_after_it() {
        // A removal noticed late (or on a skewed clock) can carry a time after a fresh join;
        // the join must still stand, here and at the next sync.
        let (_tmp, _guard, me) = init_test_db();
        let relay = MemoryRelay::new();
        let x = create_community(&relay, "Late", vec!["wss://r".into()], None).await.unwrap();
        let x_hex = crate::simd::hex::bytes_to_hex_32(&x.id().0);
        publish_remote_tombstone(&relay, &me, &x.relays, &x_hex, now_ms() + 60_000).await;
        assert!(republish_community_list(&relay, Some(x.id())).await.unwrap(), "the join landed");
        sync_community_list(&relay, &x.relays).await.unwrap();
        assert!(crate::db::community::load_community_v2(x.id()).unwrap().is_some(), "a join is not undone by a removal it already knew of");
    }

    #[tokio::test]
    async fn a_hold_is_never_ruled_older_than_a_removal_in_its_own_second() {
        // Rows keep whole seconds: a removal later in the join's second must not read as after it.
        let (_tmp, _guard, me) = init_test_db();
        let relay = MemoryRelay::new();
        let x = create_community(&relay, "Same second", vec!["wss://r".into()], None).await.unwrap();
        let x_hex = crate::simd::hex::bytes_to_hex_32(&x.id().0);
        let held = crate::db::community::load_community_v2(x.id()).unwrap().unwrap();
        assert_eq!(held.created_at_ms % 1000, 0, "the row keeps whole seconds");
        // Relays that only ever saw a sibling's removal, half a second into the join's second.
        let elsewhere = MemoryRelay::new();
        publish_remote_tombstone(&elsewhere, &me, &x.relays, &x_hex, held.created_at_ms + 500).await;
        sync_community_list(&elsewhere, &x.relays).await.unwrap();
        assert!(crate::db::community::load_community_v2(x.id()).unwrap().is_some(), "the hold is not torn down by a removal inside its own second");
    }

    #[tokio::test]
    async fn a_failed_remote_fetch_never_clobbers_the_published_list() {
        // W2: a transient fetch failure during republish must not drive the
        // replaceable-event write (which would drop other entries / regress seeds).
        let (_tmp, _guard, _me) = init_test_db();
        let good = MemoryRelay::new();
        let community = create_community(&good, "Seeded", vec!["wss://r".into()], None).await.unwrap();
        assert!(fetch_fragments(&good, &community.relays).await.unwrap().is_some());

        // A transport whose fetch always errors: republish must bail, publishing nothing.
        struct FetchErrors;
        #[async_trait::async_trait]
        impl Transport for FetchErrors {
            async fn fetch_plane(&self, _plane: &Keys, query: &Query, relays: &[String]) -> Result<crate::community::transport::PlaneFetch, String> { Ok(crate::community::transport::PlaneFetch::whole(self.fetch(query, relays).await?)) }
            async fn publish(&self, _e: &Event, _r: &[String]) -> Result<(), String> {
                panic!("republish must NOT publish when the remote fetch failed");
            }
            async fn publish_durable(&self, _e: &Event, _r: &[String]) -> Result<(), String> {
                Ok(())
            }
            async fn fetch(&self, _q: &Query, _r: &[String]) -> Result<Vec<Event>, String> {
                Err("relay unreachable".to_string())
            }
        }
        // Returns Ok (best-effort) but must not have published (the panic guards it).
        republish_community_list(&FetchErrors, Some(community.id())).await.unwrap();
    }

    #[tokio::test]
    async fn a_granted_member_survives_a_refounding_even_with_no_guestbook_join() {
        // B1 regression: refound_community's recipient set = memberlist. A member
        // the owner GRANTED a role to but who never left a (surviving) Guestbook
        // Join — a lurking admin, or one whose Join aged out of the window — must
        // still be a rekey recipient, or the Refounding SEVERS them. The folded
        // roster's granted members are the consensus-complete backstop.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Backstop", vec!["wss://r".into()], None).await.unwrap();

        // A lurker gets an admin grant but publishes NO Guestbook Join and no chat.
        let lurker = Keys::generate();
        let rid = "b1".repeat(32);
        publish_role(&relay, &community, &owner, &admin_role(&rid, Permissions::ADMIN_ALL), 1).await;
        publish_grant(&relay, &community, &owner, &lurker.public_key(), vec![rid.clone()], 1).await;

        // memberlist includes the lurker purely via the roster backstop.
        let members = memberlist(&relay, &community).await.unwrap();
        assert!(members.contains(&lurker.public_key()), "a granted member with no Join is still a member");

        // A banned grantee whose grant wasn't stripped is NOT re-admitted.
        let banned_grantee = Keys::generate();
        publish_grant(&relay, &community, &owner, &banned_grantee.public_key(), vec![rid], 1).await;
        set_banlist(&relay, &community, &[banned_grantee.public_key().to_hex()]).await.unwrap();
        let members = memberlist(&relay, &community).await.unwrap();
        assert!(members.contains(&lurker.public_key()), "the honest grantee still counts");
        assert!(!members.contains(&banned_grantee.public_key()), "a banned grantee is not re-admitted by the union");

        // And the Refounding actually delivers the new root to the lurker.
        let refounded = refound_community(&relay, &community, &[]).await.unwrap();
        assert_eq!(refounded.root_epoch, Epoch(1));
        let base_group = base_rekey_group_key(&community.community_root, community.id(), Epoch(1));
        let chunks = fetch_rekey_chunks(&relay, &community, &base_group).await.unwrap();
        let rotations = rekey::collect_rotations(&chunks);
        let lurker_x = lurker.public_key().to_bytes();
        let delivered = rotations.iter().any(|r| {
            rekey::find_my_blob(&r.blobs, &r.rotator.to_bytes(), &lurker_x, r.scope, r.new_epoch).is_some()
        });
        assert!(delivered, "the Refounding delivered the new root to the granted lurker");
    }

    #[tokio::test]
    async fn the_memberlist_pages_past_a_guestbook_flood() {
        // The roleless-member half of B1: >500 Guestbook events must not evict an
        // honest member's Join from the counted set (an insider can flood throwaway
        // Joins to force exactly this). The pager sees them all.
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "GBFlood", vec!["wss://r".into()], None).await.unwrap();
        let gb = super::super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);

        // An honest member's Join (oldest), then 600 throwaway Joins on top.
        let honest = Keys::generate();
        let join = guestbook::build_join_rumor(honest.public_key(), None, 1_000);
        let (w, _) = guestbook::seal_guestbook_rumor(&join, &gb, &honest, Timestamp::from_secs(1)).unwrap();
        relay.publish(&w, &community.relays).await.unwrap();
        for i in 0..600u64 {
            let throwaway = Keys::generate();
            let j = guestbook::build_join_rumor(throwaway.public_key(), None, 2_000 + i);
            let (w, _) = guestbook::seal_guestbook_rumor(&j, &gb, &throwaway, Timestamp::from_secs(2 + i)).unwrap();
            relay.publish(&w, &community.relays).await.unwrap();
        }

        let members = memberlist(&relay, &community).await.unwrap();
        assert!(members.contains(&honest.public_key()), "the honest member's aged-out Join is still counted past the flood");
    }

    #[tokio::test]
    async fn a_rekey_plane_flood_cannot_bury_a_genuine_rotation() {
        // An insider floods the next-epoch rekey address (community_root-derived,
        // so any member can seal there) with >200 junk 3303s to push the owner's
        // genuine rotation out of a single fetch window. The paginated fetch must
        // still recover it and adopt.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Flooded", vec!["wss://r".into()], None).await.unwrap();
        let new_root = [0xD9; 32];
        let new_epoch = Epoch(1);
        let group = base_rekey_group_key(&community.community_root, community.id(), new_epoch);

        // The GENUINE owner rotation lands first (oldest).
        publish_base_rotation(&relay, &community, &owner, &[owner.public_key()], &new_root, &community.community_root).await;

        // Then a member floods 260 well-formed-but-unauthorized junk chunks ON TOP
        // (newer), burying the genuine one past the 200 newest.
        let rogue = Keys::generate();
        let prev_commit = super::super::derive::epoch_key_commitment(Epoch(0), &community.community_root);
        for i in 0..260u64 {
            let blob = rekey::build_blob_local(rogue.secret_key(), &rogue.public_key().to_bytes(), &rogue.public_key(), RekeyScope::Root, new_epoch, &[0xEE; 32]).unwrap();
            let rumor = rekey::build_rekey_rumor(rogue.public_key(), RekeyScope::Root, new_epoch, Epoch(0), &prev_commit, &[blob], 1, 1, 3_000 + i, None, false).unwrap();
            let (wrap, _) = rekey::seal_rekey_chunk(&rumor, &group, &rogue, Timestamp::from_secs(3_000 + i)).unwrap();
            relay.publish(&wrap, &community.relays).await.unwrap();
        }

        let session = crate::db::current_session();
        let updated = follow_rekeys(&relay, &community, &session).await.unwrap().updated.expect("the genuine rotation is recovered past the flood");
        assert_eq!(updated.root_epoch, Epoch(1));
        assert_eq!(updated.community_root, new_root, "adopted the owner's root, not a junk one");
    }

    #[tokio::test]
    async fn a_swap_during_create_private_channel_lands_in_the_creating_account() {
        // create_private_channel publishes the key crate, then the channel
        // edition, then whole-row-saves. A swap in that window used to abandon
        // the whole thing — leaving the key crate published to relays but no
        // local channel to open it, which is the worse of the two outcomes.
        //
        // The operation is pinned to the account that started it, so it now
        // finishes into that account's storage, and the account swapped in gets
        // nothing.
        let (bed, owner, _member) = TestBed::new();
        bed.swap_to(&owner);
        let creator = crate::db::current_session();
        let community = create_community(&bed.relay, "SwapCreate", bed.relays.clone(), None).await.unwrap();
        let before = crate::db::community::load_community_v2(community.id()).unwrap().unwrap().channels.len();

        // The key-crate publish inside create swaps the account mid-flight.
        let swap_relay = SwapMidPublish { inner: MemoryRelay::new() };
        create_private_channel(&swap_relay, &community, "ghost").await.unwrap();

        let mine = crate::db::with_session(creator, async {
            crate::db::community::load_community_v2(community.id()).unwrap().unwrap()
        })
        .await;
        assert_eq!(mine.channels.len(), before + 1, "the channel is minted for the account that asked");
        assert!(mine.channels.iter().any(|c| c.name == "ghost"), "and it is the one requested");
    }

    #[tokio::test]
    async fn an_uncited_admin_rotation_is_not_adopted() {
        // CORD-06 §Authority: "a rotation cites the Grant it acts under like any
        // authority action, so a just-demoted admin's rotation is never honored by
        // a lagging client." An uncited rotation is skipped entirely — neither
        // adopted nor allowed to conclude a removal.
        use crate::community::roles::{CommunityRoles, MemberGrant, Role};
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let mut community = create_community(&relay, "Uncited", vec!["wss://r".into()], None).await.unwrap();
        let priv_id = ChannelId([0x8A; 32]);
        let key1 = [0x93; 32];
        add_private_channel(&mut community, priv_id, key1, Epoch(1));

        let admin = Keys::generate();
        let role = Role::admin("cf".repeat(32));
        let roster = CommunityRoles {
            roles: vec![role.clone()],
            grants: vec![MemberGrant { member: admin.public_key().to_hex(), role_ids: vec![role.role_id.clone()] }],
            everyone: None,
            overwrites: Vec::new(), syncs: Default::default(), legacy_channels: None, creators: Default::default(),
        };
        seed_roster_with_heads(&community, &roster, 1_000);

        let key2 = [0x94; 32];
        let pc = super::super::derive::epoch_key_commitment(Epoch(1), &key1);
        let g2 = channel_rekey_group_key(&community.community_root, &priv_id, Epoch(2));
        let me_pk = crate::state::MY_SECRET_KEY.to_keys().unwrap().public_key();
        let blob = rekey::build_blob_local(admin.secret_key(), &admin.public_key().to_bytes(), &me_pk, RekeyScope::Channel(priv_id), Epoch(2), &key2).unwrap();
        // Authorized admin, correct continuity, my blob present — but NO citation.
        for e in rekey::build_rekey_chunks_local(&admin, &g2, RekeyScope::Channel(priv_id), Epoch(2), Epoch(1), &pc, &[blob], 2_000, None, false).unwrap() {
            relay.publish(&e, &community.relays).await.unwrap();
        }

        let out = follow_rekeys(&relay, &community, &crate::db::current_session()).await.unwrap();
        assert!(out.updated.is_none(), "an uncited rotation is not adopted");

        // The SAME rotation, cited, is adopted — proving the refusal was the
        // citation and not the rank or the continuity.
        let cited = my_authority_citation(&community, &admin.public_key());
        assert!(cited.is_some(), "the seeded head yields a citation");
        let blob2 = rekey::build_blob_local(admin.secret_key(), &admin.public_key().to_bytes(), &me_pk, RekeyScope::Channel(priv_id), Epoch(2), &key2).unwrap();
        for e in rekey::build_rekey_chunks_local(&admin, &g2, RekeyScope::Channel(priv_id), Epoch(2), Epoch(1), &pc, &[blob2], 2_100, cited.as_ref(), false).unwrap() {
            relay.publish(&e, &community.relays).await.unwrap();
        }
        let out = follow_rekeys(&relay, &community, &crate::db::current_session()).await.unwrap();
        assert!(out.updated.is_some(), "the cited rotation IS adopted");
    }

    #[tokio::test]
    async fn two_admins_racing_a_channel_rotation_converge_on_one_key() {
        // CORD-06 §Failure-and-races: two DISTINCT authorized rotators mint the
        // same channel epoch concurrently (reachable — both hold MANAGE_CHANNELS).
        // Every follower must converge on the SAME key (the lexicographically
        // lowest), so the community never permanently forks. (Retaining the losing
        // fork's key for its race-window messages needs a multi-key-per-epoch
        // archive — a deferred refinement; convergence, the
        // security-critical property, is what this pins.)
        use crate::community::roles::{CommunityRoles, MemberGrant, Role};
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let mut community = create_community(&relay, "Race", vec!["wss://r".into()], None).await.unwrap();
        let priv_id = ChannelId([0xC0; 32]);
        let key1 = [0xC1; 32];
        add_private_channel(&mut community, priv_id, key1, Epoch(1));

        // Two admins (a, b) both hold the Admin role; I hold the channel key.
        let (a, b) = (Keys::generate(), Keys::generate());
        let role = Role::admin("ce".repeat(32));
        let roster = CommunityRoles {
            roles: vec![role.clone()],
            grants: [&a, &b].iter().map(|k| MemberGrant { member: k.public_key().to_hex(), role_ids: vec![role.role_id.clone()] }).collect(),
            everyone: None,
            overwrites: Vec::new(), syncs: Default::default(), legacy_channels: None, creators: Default::default(),
        };
        seed_roster_with_heads(&community, &roster, 1_000);

        // Both rotate 1 → 2, each delivering their OWN fresh key to me, off the
        // same prevcommit — a genuine same-epoch fork.
        let me_pk = crate::state::MY_SECRET_KEY.to_keys().unwrap().public_key();
        let pc = super::super::derive::epoch_key_commitment(Epoch(1), &key1);
        let group = channel_rekey_group_key(&community.community_root, &priv_id, Epoch(2));
        let key_a = [0x0A; 32];
        let key_b = [0xFB; 32]; // higher — a's must win regardless of publish order
        for (signer, k) in [(&a, &key_a), (&b, &key_b)] {
            let blob = rekey::build_blob_local(signer.secret_key(), &signer.public_key().to_bytes(), &me_pk, RekeyScope::Channel(priv_id), Epoch(2), k).unwrap();
            for e in rekey::build_rekey_chunks_local(signer, &group, RekeyScope::Channel(priv_id), Epoch(2), Epoch(1), &pc, &[blob], 2_000, my_authority_citation(&community, &signer.public_key()).as_ref(), false).unwrap() {
                relay.publish(&e, &community.relays).await.unwrap();
            }
        }

        let session = crate::db::current_session();
        let updated = follow_rekeys(&relay, &community, &session).await.unwrap().updated.expect("adopts a winner");
        let adopted = updated.channel(&priv_id).unwrap().key.unwrap();
        assert_eq!(adopted, key_a, "converges on the lexicographically lowest key (deterministic across clients)");

        // A SECOND follower (fresh, holding the same epoch-1 key) converges identically.
        let mut peer = community.clone();
        if let Some(c) = peer.channels.iter_mut().find(|c| c.id.0 == priv_id.0) {
            c.key = Some(key1);
            c.epoch = Epoch(1);
        }
        // Re-run the same fold from the peer's identical starting point → same winner.
        let updated2 = follow_rekeys(&relay, &peer, &session).await.unwrap().updated.expect("peer adopts");
        assert_eq!(updated2.channel(&priv_id).unwrap().key.unwrap(), key_a, "every follower lands on the identical key");
    }

    #[tokio::test]
    async fn create_private_channel_refuses_a_member_without_manage_channels() {
        // The local mirror of the reader's gate: an unauthorized member is refused
        // BEFORE any publish (no floor pollution, no orphan key crate).
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Gate", bed.relays.clone(), None).await.unwrap();
        send_direct_invite(&bed.relay, &community, &member.keys.public_key(), None, None).await.unwrap();

        bed.swap_to(&member);
        let invite_wrap = fetch_direct_invite(&bed.relay, &bed.relays, &member.keys.public_key()).await;
        let joined = accept_direct_invite(&bed.relay, &invite_wrap).await.unwrap();
        let err = create_private_channel(&bed.relay, &joined, "sneaky").await.unwrap_err();
        assert!(err.contains("MANAGE_CHANNELS"), "refused with the permission it lacks: {err}");
        let err = create_public_channel(&bed.relay, &joined, "sneaky-too").await.unwrap_err();
        assert!(err.contains("MANAGE_CHANNELS"), "public creation gates identically: {err}");
    }

    // ── Audit regressions ────────────────────────────────────────────────────

    #[tokio::test]
    async fn accept_rejects_a_bundle_with_a_forged_community_root() {
        // The eclipse: community_id commits only to (owner, salt) — both semi-public
        // — so a forged invite pairs the REAL triple with an attacker root, and every
        // plane derives from it. The join-time owner-genesis check must refuse.
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Real", bed.relays.clone(), None).await.unwrap();

        let fake = crate::simd::hex::bytes_to_hex_32(&[0xEE; 32]);
        let mut forged = bundle_of(&community, BundleAudience::Link, None, None, None);
        forged.community_root = fake.clone();
        for ch in &mut forged.channels {
            ch.key = fake.clone();
        }
        let attacker = Keys::generate();
        let wrap = invite::build_direct_invite(&attacker, &member.keys.public_key(), &forged).unwrap();
        bed.relay.publish(&wrap, &bed.relays).await.unwrap();

        bed.swap_to(&member);
        let invite_wrap = fetch_direct_invite(&bed.relay, &bed.relays, &member.keys.public_key()).await;
        let err = accept_direct_invite(&bed.relay, &invite_wrap).await.unwrap_err();
        assert!(err.contains("could not verify"), "a forged root fails the owner-genesis check: {err}");
        assert!(
            crate::db::community::load_community_v2(community.id()).unwrap().is_none(),
            "a rejected join persists nothing"
        );
    }

    #[tokio::test]
    async fn accept_verifies_a_rotated_plane_whose_metadata_head_is_admin_signed() {
        // CORD-06 compaction re-wraps CURRENT heads with their original signatures,
        // so a rotated plane whose metadata an admin last edited carries no
        // owner-signed vsk-0. The join anchor there is the community-bound metadata
        // head plus any owner-signed edition under the same root.
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Rotated", bed.relays.clone(), None).await.unwrap();
        let general = community.channels[0].id;

        let rotated = rotate_view(&community, [0x5A; 32], 1);
        let admin = Keys::generate();
        publish_community_meta(&bed.relay, &rotated, &admin, "Rotated", 3).await;
        publish_channel_edition(&bed.relay, &rotated, &owner.keys, &general, "general", false, 2, false).await;

        bed.swap_to(&member);
        let bundle = bundle_of(&rotated, BundleAudience::Link, None, None, None);
        let joined = accept_bundle(&bed.relay, &bundle, None, None).await.unwrap();
        assert_eq!(joined.root_epoch, Epoch(1), "the rotated root is adopted");
    }

    #[tokio::test]
    async fn only_an_actual_join_publishes_a_guestbook_join() {
        // A Guestbook Join is a member's own word that they JOINED. A re-accept of
        // a held community and a cross-device key sync (a `member_since`) must
        // both stay silent — each re-publish renders as "<user> has joined" spam.
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Quiet", bed.relays.clone(), None).await.unwrap();

        let gb_pk = super::super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch).pk_hex();
        async fn gb_count(relay: &MemoryRelay, gb_pk: &str, relays: &[String]) -> usize {
            let q = Query { kinds: vec![stream::KIND_WRAP], authors: vec![gb_pk.to_string()], ..Default::default() };
            relay.fetch(&q, relays).await.map(|v| v.len()).unwrap_or(0)
        }
        let baseline = gb_count(&bed.relay, &gb_pk, &bed.relays).await; // the owner's creation Join

        bed.swap_to(&member);
        let bundle = bundle_of(&community, BundleAudience::Link, None, None, None);
        accept_bundle(&bed.relay, &bundle, None, None).await.unwrap();
        assert_eq!(gb_count(&bed.relay, &gb_pk, &bed.relays).await, baseline + 1, "a first join announces exactly once");

        accept_bundle(&bed.relay, &bundle, None, None).await.unwrap();
        assert_eq!(gb_count(&bed.relay, &gb_pk, &bed.relays).await, baseline + 1, "a re-accept of a held community stays silent");

        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        crate::db::community::delete_community(&cid_hex).unwrap();
        // A key sync is not a membership event, and it is not a membership
        // RECORD either: the entry was just read from the very list a republish
        // would rewrite. A device adopting N entries used to rebuild and
        // publish the whole document N times over, concurrently, on boot.
        // 13302 is REPLACEABLE, so a republish swaps the stored event rather
        // than adding one — the id is the tell, and it always changes on a
        // real republish because the list is NIP-44 sealed with a random nonce.
        async fn list_id(relay: &MemoryRelay, me: &PublicKey, relays: &[String]) -> Option<String> {
            let q = Query { kinds: vec![crate::community::v2::kind::COMMUNITY_LIST_FRAG], authors: vec![me.to_hex()], ..Default::default() };
            let mut evs = relay.fetch(&q, relays).await.unwrap_or_default();
            evs.sort_by_key(|e| e.created_at.as_secs());
            evs.last().map(|e| e.id.to_hex())
        }
        let my_pk = me_pk().unwrap();
        let list_before = list_id(&bed.relay, &my_pk, &bed.relays).await;
        accept_bundle(&bed.relay, &bundle, None, Some(now_ms())).await.unwrap();
        assert_eq!(gb_count(&bed.relay, &gb_pk, &bed.relays).await, baseline + 1, "a cross-device key sync is not a membership event");
        assert_eq!(
            list_id(&bed.relay, &my_pk, &bed.relays).await,
            list_before,
            "adopting an entry FROM the list must not republish the list"
        );

        // A genuine join still records, so the storm fix can't have muted the
        // thing the republish exists for.
        crate::db::community::delete_community(&cid_hex).unwrap();
        accept_bundle(&bed.relay, &bundle, None, None).await.unwrap();
        assert_ne!(
            list_id(&bed.relay, &my_pk, &bed.relays).await,
            list_before,
            "a real join still records the membership across devices"
        );
    }

    #[tokio::test]
    async fn accept_refuses_a_rotated_plane_with_no_owner_signed_edition() {
        // The fallback's second half is load-bearing: a community-bound metadata
        // head alone is self-signable by anyone who knows the (public) community_id.
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "NoOwner", bed.relays.clone(), None).await.unwrap();

        let rotated = rotate_view(&community, [0x5B; 32], 1);
        let attacker = Keys::generate();
        publish_community_meta(&bed.relay, &rotated, &attacker, "NoOwner", 3).await;

        bed.swap_to(&member);
        let bundle = bundle_of(&rotated, BundleAudience::Link, None, None, None);
        let err = accept_bundle(&bed.relay, &bundle, None, None).await.unwrap_err();
        assert!(err.contains("could not verify"), "no owner-signed edition → refuse: {err}");
    }

    #[tokio::test]
    async fn accept_requires_the_strict_owner_genesis_on_an_epoch_zero_plane() {
        // The fallback applies to rotated planes only: at epoch 0 the spec guarantees
        // an owner-signed genesis, so owner material without it stays insufficient.
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Strict", bed.relays.clone(), None).await.unwrap();
        let general = community.channels[0].id;

        let mut fake = community.clone();
        fake.community_root = [0x5C; 32]; // epoch stays 0
        let admin = Keys::generate();
        publish_community_meta(&bed.relay, &fake, &admin, "Strict", 2).await;
        publish_channel_edition(&bed.relay, &fake, &owner.keys, &general, "general", false, 2, false).await;

        bed.swap_to(&member);
        let bundle = bundle_of(&fake, BundleAudience::Link, None, None, None);
        let err = accept_bundle(&bed.relay, &bundle, None, None).await.unwrap_err();
        assert!(err.contains("could not verify"), "epoch 0 demands the owner genesis: {err}");
    }

    #[tokio::test]
    async fn follow_control_heals_a_bundle_misclassified_public_channel() {
        // A bundle can set a PUBLIC channel's grant key to the attacker's, so the
        // joiner addresses it at a plane only the attacker reads. The owner's genuine
        // public:false edition must override it on follow.
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Heal", vec!["wss://r".into()], None).await.unwrap();
        let general = community.channels[0].id;
        let mut poisoned = community.clone();
        poisoned.channels[0].private = true;
        poisoned.channels[0].key = Some([0x66; 32]);
        crate::db::community::save_community_v2(&poisoned).unwrap();

        let healed = follow_control(&relay, &poisoned).await.unwrap().updated.expect("healed");
        let ch = healed.channel(&general).unwrap();
        assert!(!ch.private, "the owner's public declaration overrides the bundle");
        assert_eq!(ch.key, None, "a healed public channel derives from the root");
    }

    #[tokio::test]
    async fn a_deleted_channel_does_not_resurrect_on_reload() {
        // save_community_v2 must prune orphan channel rows, or a control-follow delete
        // reappears (with a stale key) on the next reload.
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Prune", vec!["wss://r".into()], None).await.unwrap();
        let extra = ChannelId([0x77; 32]);
        publish_channel_edition(&relay, &community, &owner, &extra, "temp", false, 1, false).await;
        let with_extra = follow_control(&relay, &community).await.unwrap().updated.unwrap();
        assert!(with_extra.channel(&extra).is_some());
        publish_channel_edition(&relay, &community, &owner, &extra, "temp", false, 2, true).await;
        let after = follow_control(&relay, &with_extra).await.unwrap().updated.unwrap();
        assert!(after.channel(&extra).is_none());

        let reloaded = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        assert!(reloaded.channel(&extra).is_none(), "a deleted channel must not resurrect on reload");
        assert_eq!(reloaded.channels.len(), 1);
    }

    #[tokio::test]
    async fn a_channel_owned_by_another_community_is_skipped_not_clobbered() {
        // channel_id is the sole DB primary key, so a bundle/replay reusing another
        // community's channel_id must NOT overwrite that row. It's skipped (not an
        // error — erroring would wedge all of this community's control persistence).
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let a = create_community(&relay, "A", vec!["wss://r".into()], None).await.unwrap();
        let a_channel = a.channels[0].id;
        let mut b = create_community(&relay, "B", vec!["wss://r".into()], None).await.unwrap();
        let b_channel = b.channels[0].id;
        // B's set includes a phantom whose id collides with A's channel.
        b.channels.push(ChannelV2 { id: a_channel, name: "phantom".into(), private: false, key: None, epoch: b.root_epoch, voice: None, meta_custom: None, meta_extra: Default::default(), writers: None, sealed: None });

        crate::db::community::save_community_v2(&b).expect("save succeeds, the phantom is skipped");
        // A's channel row is untouched.
        let a_reloaded = crate::db::community::load_community_v2(a.id()).unwrap().unwrap();
        assert!(!a_reloaded.channels.iter().any(|c| c.private), "A's channel is untouched");
        assert_eq!(a_reloaded.channels[0].id.0, a_channel.0);
        // B keeps its own channel but never acquired a row for the foreign id.
        let b_reloaded = crate::db::community::load_community_v2(b.id()).unwrap().unwrap();
        assert!(b_reloaded.channel(&b_channel).is_some(), "B's own channel persists");
        assert!(b_reloaded.channel(&a_channel).is_none(), "the foreign-owned channel is skipped, not stolen");
    }

    /// A single relay that CAPS every query below the page size (modelling a real
    /// relay's maxFilterLimit) and honors `until` — so the join-verify walk MUST
    /// paginate to reach an old genesis. MemoryRelay can't model this (it unions then
    /// truncates the whole set), which is why a MemoryRelay flood test gives false
    /// confidence about the production `LiveTransport` behaviour.
    struct CappedRelay {
        events: Vec<Event>,
        cap: usize,
    }
    #[async_trait::async_trait]
    impl Transport for CappedRelay {
        async fn fetch_plane(&self, _plane: &Keys, query: &Query, relays: &[String]) -> Result<crate::community::transport::PlaneFetch, String> { Ok(crate::community::transport::PlaneFetch::whole(self.fetch(query, relays).await?)) }
        async fn publish(&self, _e: &Event, _r: &[String]) -> Result<(), String> {
            Ok(())
        }
        async fn publish_durable(&self, _e: &Event, _r: &[String]) -> Result<(), String> {
            Ok(())
        }
        async fn fetch(&self, q: &Query, _r: &[String]) -> Result<Vec<Event>, String> {
            let mut m: Vec<Event> = self
                .events
                .iter()
                .filter(|e| q.authors.is_empty() || q.authors.contains(&e.pubkey.to_hex()))
                .filter(|e| q.until.is_none_or(|u| e.created_at.as_secs() <= u))
                .cloned()
                .collect();
            m.sort_by(|a, b| b.created_at.cmp(&a.created_at)); // newest first
            m.truncate(self.cap.min(q.limit.unwrap_or(usize::MAX)));
            Ok(m)
        }
    }

    #[tokio::test]
    async fn refound_aborts_when_the_control_plane_cannot_be_read_in_full() {
        // CORD-06 §3: a Refounder that cannot fold every Control Event must abort.
        // `until` is inclusive, so a page-wide block of same-second wraps is a wall
        // no cursor steps past — everything older (the genesis editions, a Banlist)
        // is unreachable. Compacting THAT view carries only what was read into the
        // new epoch, dropping the rest for every member, permanently. Any member can
        // build the wall: the plane key comes from the community root they hold.
        let (_tmp, _guard, _owner) = init_test_db();
        let memory = MemoryRelay::new();
        let community = create_community(&memory, "Walled", vec!["wss://r".into()], None).await.unwrap();
        // Post-split the plane is staff-write-only, so the wall is built with the
        // write group (any control_root holder can still flood; the pager
        // property under test is unchanged).
        let control = control::ControlPlane::of(&community).write_group().unwrap();

        let rogue = Keys::generate();
        let mut events: Vec<Event> = Vec::new();
        for i in 0..FOLLOW_PAGE {
            let content = format!("{{\"name\":\"junk{i}\",\"private\":false}}");
            let rumor = control::build_edition_rumor(
                rogue.public_key(),
                vsk::CHANNEL_METADATA,
                &[0xAB; 32],
                1,
                None,
                &content,
                9_000,
                None,
            );
            let (w, _) = control::seal_control_edition(&rumor, &control, &rogue, Timestamp::from_secs(9_000)).unwrap();
            events.push(w);
        }
        let relay = CappedRelay { events, cap: FOLLOW_PAGE };

        let err = refound_community(&relay, &community, &[])
            .await
            .expect_err("a plane that can't be read whole must never be compacted");
        assert!(err.contains("too deep to read in full"), "unexpected error: {err}");
    }

    #[tokio::test]
    async fn verify_pages_a_capped_relay_past_a_flood_to_the_genesis() {
        // The join-verify DoS mitigation, tested against a relay that caps below PAGE
        // (production behaviour MemoryRelay hides): a rogue root-holder buries the
        // genesis under junk, and the `until`-walk must page past it. Uses fixed OLD
        // timestamps so `until = now` includes everything and the walk is deterministic.
        let (_tmp, _guard, owner) = init_test_db();
        let meta = control::CommunityMetadata { name: "Capped".into(), relays: vec!["wss://r".into()], ..Default::default() };
        let g = control::genesis(&owner, meta, 1_000).unwrap();
        let community = CommunityV2::from_genesis(&g, "Capped", None, vec!["wss://r".into()], 1_000);

        let control = control::ControlPlane::of(&community).write_group().unwrap();
        let rogue = Keys::generate();
        let mut events: Vec<Event> = g.wraps.to_vec();
        for i in 0..250u64 {
            let rumor = control::build_edition_rumor(rogue.public_key(), vsk::CHANNEL_METADATA, &[0xAB; 32], 1, None, "{\"name\":\"junk\",\"private\":false}", 1_001 + i, None);
            let (wrap, _) = control::seal_control_edition(&rumor, &control, &rogue, Timestamp::from_secs(1_001 + i)).unwrap();
            events.push(wrap);
        }
        // Cap 100/query forces the walk across ~3 pages down to the genesis at ts 1000.
        let relay = CappedRelay { events, cap: 100 };
        let verified = verify_owner_root_and_reconcile(&relay, community.clone()).await;
        assert!(verified.is_ok(), "the until-walk pages a capped relay past the flood to the genesis: {:?}", verified.err());
    }

    #[tokio::test]
    async fn accept_parked_invite_joins_from_the_stored_bundle() {
        // The 3313 receive path: an invite is parked as its bundle JSON, then accepted
        // from the stored bundle (re-verifying the owner root over the network).
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Parked", bed.relays.clone(), None).await.unwrap();
        let general = community.channels[0].id;
        send_message(&bed.relay, &community, &general, "owner: hi").await.unwrap();
        let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
        let bundle_json = serde_json::to_string(&bundle).unwrap();
        let inviter_hex = owner.keys.public_key().to_hex();

        bed.swap_to(&member);
        let joined = accept_parked_invite(&bed.relay, &bundle_json, Some(&inviter_hex)).await.unwrap();
        assert_eq!(joined.id().0, community.id().0, "joined the community from the parked bundle");
        assert!(joined.identity.verify());
        assert_eq!(texts_in(&bed.relay, &joined, &general).await, vec!["owner: hi"]);
        // The join seeded the verified fold as the member's initial floor, so their
        // first follow can't roll below the state the join just showed.
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&joined.id().0);
        assert!(
            crate::db::community::get_edition_head(&cid_hex, &cid_hex).unwrap().is_some(),
            "the joiner's control floor is seeded from the join-time fold"
        );

        // The Guestbook memberlist now folds both participants.
        bed.swap_to(&owner);
        let members = memberlist(&bed.relay, &community).await.unwrap();
        assert!(members.contains(&member.keys.public_key()), "the parked-invite joiner is a member");
    }

    #[tokio::test]
    async fn accept_parked_invite_rejects_a_forged_root() {
        // A forged-root parked bundle (real identity triple, attacker-chosen root) fails
        // accept — the shared accept path re-verifies the owner root, so a parked invite
        // gets the same eclipse protection as a live one.
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Real", vec!["wss://r".into()], None).await.unwrap();
        let mut forged = bundle_of(&community, BundleAudience::Link, None, None, None);
        let fake = crate::simd::hex::bytes_to_hex_32(&[0xEE; 32]);
        forged.community_root = fake.clone();
        for ch in &mut forged.channels {
            ch.key = fake.clone();
        }
        let bundle_json = serde_json::to_string(&forged).unwrap();

        let err = accept_parked_invite(&relay, &bundle_json, None).await.unwrap_err();
        assert!(err.contains("could not verify"), "a forged-root parked bundle fails definitively: {err}");
    }

    #[tokio::test]
    async fn verify_rejects_a_cross_community_owner_edition_replay() {
        // The eclipse-via-replay: an owner-signed edition from community X (eid == X.id)
        // rewrapped onto a FORGED community T's fake control plane must NOT authenticate
        // T. T's genesis has eid == T.id, so X's edition — a genuine owner signature but
        // a different eid — is not a valid proof of T's root. This is why "any owner
        // edition" is unsound and the eid==community_id genesis pin is required.
        let (_tmp, _guard, owner) = init_test_db();

        // Community X (real), owned by `owner`.
        let gx = control::genesis(&owner, control::CommunityMetadata { name: "X".into(), ..Default::default() }, 1_000).unwrap();
        let x_control = control::split_write_group(&gx.control_root, &gx.community_root, &gx.identity.community_id, Epoch(0));
        let (_ed, opened) = control::open_control_edition(&gx.wraps[0], &x_control).unwrap();

        // Forged community T: the real owner triple but an ATTACKER-chosen root.
        let t_identity = control::CommunityIdentity::mint(&owner.public_key());
        let fake_root = [0xEE; 32];
        let t = CommunityV2 {
            identity: t_identity,
            community_root: fake_root,
            root_epoch: Epoch(0),
            control_pk: None,
            control_root: None,
            name: "T".into(),
            description: None,
            icon: None,
            banner: None,
            meta_custom: None,
            meta_extra: Default::default(),
            relays: vec!["wss://r".into()],
            channels: vec![],
            categories: Vec::new(),
            dissolved: false,
            created_at_ms: 0,
        };
        // Rewrap X's owner-signed genesis onto T's fake control plane (the attacker
        // controls the fake root, so they can derive its control group key).
        let t_control = control_group_key(&fake_root, t.id(), t.root_epoch);
        let (replayed, _) = stream::rewrap_seal(&opened.seal, &t_control, Timestamp::from_secs(1_000)).unwrap();
        let relay = MemoryRelay::new();
        relay.publish(&replayed, &t.relays).await.unwrap();

        let verified = verify_owner_root_and_reconcile(&relay, t.clone()).await;
        assert!(verified.is_err(), "a cross-community owner-edition replay must not authenticate a forged root");
    }

    /// LIVE smoke test (network) — ignored by default. Creates a v2 community on a
    /// REAL relay via `LiveTransport`, sends a message, fetches it back, and mints
    /// a public link. A fresh throwaway identity in an isolated temp data dir, so
    /// it never touches real accounts. Run explicitly:
    /// ```sh
    /// cargo test -p vector-core -- --ignored --nocapture live_smoke
    /// ```
    #[tokio::test]
    #[ignore = "hits a real relay over the network"]
    async fn live_smoke_create_send_fetch_on_a_real_relay() {
        use nostr_sdk::prelude::ToBech32;

        let relay = std::env::var("VECTOR_SMOKE_RELAY").unwrap_or_else(|_| "wss://jskitty.com/nostr".to_string());
        let relays = vec![relay.clone()];

        // Isolated account + data dir (a fresh throwaway key — never a real account).
        let _g = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
        crate::db::close_database();
        crate::db::clear_id_caches();
        let tmp = tempfile::tempdir().unwrap();
        // Bring your own key (VECTOR_SMOKE_NSEC) to create a community you can log
        // into elsewhere; otherwise a fresh throwaway.
        let keys = match std::env::var("VECTOR_SMOKE_NSEC") {
            Ok(n) => Keys::parse(&n).expect("VECTOR_SMOKE_NSEC is not a valid nsec"),
            Err(_) => Keys::generate(),
        };
        let npub = keys.public_key().to_bech32().unwrap();
        // Off by default (never leak secrets from a committed test); set
        // VECTOR_SMOKE_PRINT_NSEC=1 to print the owner nsec for cross-client login.
        if std::env::var("VECTOR_SMOKE_PRINT_NSEC").is_ok() {
            println!("[smoke] OWNER nsec (throwaway — do NOT reuse): {}", keys.secret_key().to_bech32().unwrap());
        }
        std::fs::create_dir_all(tmp.path().join(&npub)).unwrap();
        crate::db::set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());
        crate::db::set_current_account(npub.clone()).unwrap();
        crate::db::init_database(&npub).unwrap();
        crate::state::MY_SECRET_KEY.store_from_keys(&keys, &[]);
        crate::state::set_my_public_key(keys.public_key());
        println!("[smoke] throwaway identity {npub}");

        // A live client (LiveTransport rides the global NOSTR_CLIENT + warms relays).
        let client = crate::nostr_client_builder().build();
        client.add_managed_relay(relay.as_str()).await.ok();
        client.connect().await;
        crate::state::set_nostr_client(client);
        let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(15));

        // Create → send → fetch-back → verify.
        let community = create_community(&transport, "V2 Live Smoke", relays.clone(), None).await.expect("create");
        let general = community.channels[0].id;
        println!("[smoke] created community {} on {relay}", crate::simd::hex::bytes_to_hex_32(&community.id().0));

        let text = "hello from a Vector Concord v2 live smoke test";
        let sent_id = send_message(&transport, &community, &general, text).await.expect("send");
        println!("[smoke] sent message {sent_id}");

        // Give the relay a moment to store + be ready to serve it.
        crate::rt::time::sleep(std::time::Duration::from_secs(3)).await;

        let page = fetch_channel(&transport, &community, &general, 50).await.expect("fetch");
        let texts: Vec<String> = page
            .iter()
            .filter_map(|f| match &f.event {
                ChatEvent::Message { .. } => Some(f.event.opened().rumor.content.clone()),
                _ => None,
            })
            .collect();
        println!("[smoke] fetched {} message(s) back: {texts:?}", texts.len());
        assert!(texts.contains(&text.to_string()), "the message did not round-trip through the real relay");

        // Mint a shareable v2 link (the thing a bot hands out).
        let link = mint_public_link(&transport, &community, "https://vectorapp.io", None, None).await.expect("mint link");
        println!("[smoke] invite link: {}", link.url);
        println!("[smoke] PASS — v2 create+send+fetch+invite round-tripped on {relay}");
    }

    #[tokio::test]
    async fn chat_ops_react_edit_delete_round_trip() {
        let (bed, owner, _member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Ops", bed.relays.clone(), None).await.unwrap();
        let general = community.channels[0].id;
        let me_hex = owner.keys.public_key().to_hex();

        let msg_id = send_message(&bed.relay, &community, &general, "original").await.unwrap();
        send_reaction(&bed.relay, &community, &general, &msg_id, &me_hex, super::super::kind::MESSAGE, ":fire:", Some(("fire", "https://e/f.png")))
            .await
            .unwrap();
        send_edit(&bed.relay, &community, &general, &msg_id, "edited", &[]).await.unwrap();
        send_delete(&bed.relay, &community, &general, &msg_id, super::super::kind::MESSAGE, None).await.unwrap();

        let page = fetch_channel(&bed.relay, &community, &general, 50).await.unwrap();
        let target = crate::simd::hex::hex_to_bytes_32(&msg_id);
        let mut saw = (false, false, false);
        for f in &page {
            match &f.event {
                ChatEvent::Reaction { target: t, emoji, emoji_url, .. } if *t == target => {
                    assert_eq!(emoji, ":fire:");
                    assert_eq!(emoji_url.as_deref(), Some("https://e/f.png"));
                    saw.0 = true;
                }
                ChatEvent::Edit { target: t, new_content, .. } if *t == target => {
                    assert_eq!(new_content, "edited");
                    saw.1 = true;
                }
                ChatEvent::Delete { target: t, .. } if *t == target => saw.2 = true,
                _ => {}
            }
        }
        assert!(saw.0 && saw.1 && saw.2, "reaction/edit/delete all round-trip: {saw:?}");
    }

    #[tokio::test]
    async fn a_typing_signal_rides_the_ephemeral_wrap_and_is_never_stored() {
        let (bed, owner, _member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Typ", bed.relays.clone(), None).await.unwrap();
        let general = community.channels[0].id;
        let group = channel_group_key(&community.community_root, &general, community.root_epoch);

        // A live subscriber sees the 21059 wrap and it opens as Typing…
        let mut sub = bed.relay.subscribe(Query {
            kinds: vec![stream::KIND_WRAP_EPHEMERAL],
            authors: vec![group.pk_hex()],
            ..Default::default()
        });
        send_typing(&bed.relay, &community, &general).await.unwrap();
        let wrap = sub.try_recv().expect("the typing wrap streams to a live subscriber");
        let opened = match chat::open_chat_event(&wrap, &group, &general, community.root_epoch) {
            Ok(ChatEvent::Typing { opened }) => opened,
            other => panic!("the ephemeral wrap must open as a Typing event, got {other:?}"),
        };

        // …while nothing durable is stored (relays never keep the ephemeral tier),
        // so channel history stays free of typing noise…
        let page = fetch_channel(&bed.relay, &community, &general, 50).await.unwrap();
        assert!(page.iter().all(|f| !matches!(f.event, ChatEvent::Typing { .. })));

        // …and no delete key is kept (there is no durable wrap to ever delete).
        let rumor_hex = opened.rumor_id.to_hex();
        assert!(
            crate::db::community::get_message_key(&rumor_hex).unwrap().is_none() && !crate::db::community::has_wrap_owner(&rumor_hex).unwrap(),
            "ephemeral sends must not keep delete keys"
        );
    }

    /// The owner key my own wrap of `rumor_hex` at `address` derives to.
    fn derived_owner_of(me: &Keys, address: &PublicKey, rumor_hex: &str) -> PublicKey {
        let secret: [u8; 32] = me.secret_key().as_secret_bytes().try_into().unwrap();
        super::super::derive::wrap_owner_key(&secret, address, nostr_sdk::prelude::EventId::from_hex(rumor_hex).unwrap().as_bytes()).public_key()
    }

    #[tokio::test]
    async fn a_send_keeps_both_delete_keys_and_a_delete_takes_it_and_its_edits_off_every_relay() {
        let (bed, owner, _member) = TestBed::new();
        bed.swap_to(&owner);
        let relays = vec!["wss://r".to_string(), "wss://s".to_string()];
        bed.relay.follow_cord01(&relays[..1]);
        let community = create_community(&bed.relay, "Nuke", relays.clone(), None).await.unwrap();
        let general = community.channels[0].id;
        let group = channel_group_key(&community.community_root, &general, community.root_epoch);

        let id = send_message(&bed.relay, &community, &general, "scrub me").await.unwrap();
        let edit = send_edit(&bed.relay, &community, &general, &id, "scrub me too", &[]).await.unwrap();

        // The wrap is p-tagged to the key this identity derives for it, and both keys are kept.
        let owners = crate::db::community::wrap_owners(&id).unwrap();
        let (owner_keys, outer_hex, sent_to) = owners.first().expect("a durable send keeps its owner");
        assert_eq!(owner_keys.public_key(), derived_owner_of(&owner.keys, &group.pk(), &id));
        assert_eq!(sent_to, &community.relays);
        let by_id = |ids: Vec<String>| Query { ids, ..Default::default() };
        let wrap = bed.relay.fetch(&by_id(vec![outer_hex.clone()]), &relays).await.unwrap().pop().expect("the kept outer id is the published wrap");
        assert_eq!(stream::wrap_owner(&wrap), Some(owner_keys.public_key()));
        let (plane, plane_outer, _) = crate::db::community::get_message_key(&id).unwrap().expect("and its plane key");
        assert_eq!((plane.public_key(), &plane_outer), (group.pk(), outer_hex));
        let edit_outer = crate::db::community::wrap_owners(&edit).unwrap().pop().expect("an edit keeps its owner too").1;

        // Reactions ride the same keys (a revoke deletes them the same way).
        let me_hex = owner.keys.public_key().to_hex();
        let rid = send_reaction(&bed.relay, &community, &general, &id, &me_hex, super::super::kind::MESSAGE, "🔥", None)
            .await
            .unwrap();
        assert!(crate::db::community::has_wrap_owner(&rid).unwrap() && crate::db::community::has_message_key(&rid).unwrap());

        let scrubbed = crate::community::message_delete::scrub_own(&bed.relay, &community.relays, &id).await.unwrap();
        assert!(scrubbed.everywhere());
        for relay in &relays {
            let left = bed.relay.fetch(&by_id(vec![outer_hex.clone(), edit_outer.clone()]), std::slice::from_ref(relay)).await.unwrap();
            assert!(left.is_empty(), "the message and the edit carrying its text leave {relay}");
        }
        for spent in [&id, &edit] {
            assert!(!crate::db::community::has_wrap_owner(spent).unwrap() && !crate::db::community::has_message_key(spent).unwrap(), "keys spent");
        }
        assert!(crate::community::message_delete::in_plane_delete_expiry(&id, scrubbed).await.is_some(), "so its in-plane delete may leave in time");
    }

    #[tokio::test]
    async fn backfill_keeps_the_owner_my_other_devices_derived_and_never_a_strangers() {
        let (bed, owner, _member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Heal", bed.relays.clone(), None).await.unwrap();
        let general = community.channels[0].id;
        let group = channel_group_key(&community.community_root, &general, community.root_epoch);

        // Sent and edited from another device of mine: on the relay, nothing kept here.
        let id = send_message(&bed.relay, &community, &general, "elsewhere").await.unwrap();
        let edit = send_edit(&bed.relay, &community, &general, &id, "edited elsewhere", &[]).await.unwrap();
        for sent in [&id, &edit] {
            crate::db::community::delete_message_key(sent).unwrap();
            crate::db::community::forget_wrap_owners(sent).unwrap();
        }

        // Mine from before owners were kept: its p key was random and is gone.
        let old = chat::build_message_rumor(owner.keys.public_key(), &general, community.root_epoch, "before", None, &[], vec![], 6_000);
        let old_id = old.id.unwrap().to_hex();
        let (old_wrap, _) = chat::seal_chat_rumor(&old, &group, &owner.keys, Timestamp::from_secs(6), false).unwrap();
        bed.relay.publish(&old_wrap, &community.relays).await.unwrap();

        // A stranger's.
        let mkeys = Keys::generate();
        let rumor = chat::build_message_rumor(mkeys.public_key(), &general, community.root_epoch, "foreign", None, &[], vec![], 7_000);
        let foreign_id = rumor.id.unwrap().to_hex();
        let (fw, _) = chat::seal_chat_rumor(&rumor, &group, &mkeys, Timestamp::from_secs(7), false).unwrap();
        bed.relay.publish(&fw, &community.relays).await.unwrap();

        fetch_channel(&bed.relay, &community, &general, 50).await.unwrap();
        let has = |id: &str| (crate::db::community::has_wrap_owner(id).unwrap(), crate::db::community::has_message_key(id).unwrap());
        assert_eq!(has(&id), (true, true), "my other device's send is fully deletable here");
        assert_eq!(has(&edit), (true, true), "and so is its edit, which carries its text");
        assert_eq!(has(&old_id), (false, true), "an old send keeps only its plane key");
        assert_eq!(has(&foreign_id), (false, false), "a stranger's gets nothing");

        bed.relay.follow_cord01(&community.relays);
        crate::community::message_delete::scrub_own(&bed.relay, &community.relays, &id).await.unwrap();
        let old_scrub = crate::community::message_delete::scrub_own(&bed.relay, &community.relays, &old_id).await.unwrap();
        assert!(!old_scrub.everywhere());
        let left: Vec<String> = fetch_channel(&bed.relay, &community, &general, 50).await.unwrap().iter().map(|f| f.event.opened().rumor_id.to_hex()).collect();
        assert!(!left.contains(&id), "the healed owner deletes it where CORD-01 holds");
        assert!(!crate::db::community::has_wrap_owner(&edit).unwrap(), "its edit went with it");
        assert!(left.contains(&old_id), "where only the in-plane delete can hide an old send");
    }

    #[tokio::test]
    async fn a_remote_signer_keeps_a_random_owner_only_on_the_sending_device() {
        let (bed, owner, _member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Bunker", bed.relays.clone(), None).await.unwrap();
        let general = community.channels[0].id;
        let group = channel_group_key(&community.community_root, &general, community.root_epoch);

        // A remote signer's account: the vault holds only its client key.
        let client = Keys::generate();
        crate::state::MY_SECRET_KEY.store_from_keys(&client, &[]);
        crate::signer::set_test_signer(Some(crate::signer::ActiveSigner::Keys(owner.keys.clone())));
        let sent = send_message(&bed.relay, &community, &general, "signed elsewhere").await;
        crate::signer::set_test_signer(None);
        crate::state::MY_SECRET_KEY.store_from_keys(&owner.keys, &[]);
        let id = sent.unwrap();

        let (kept, outer, _) = crate::db::community::wrap_owners(&id).unwrap().pop().expect("the sending device keeps its owner");
        assert_ne!(kept.public_key(), derived_owner_of(&owner.keys, &group.pk(), &id), "a remote signer can't derive it");
        assert_ne!(kept.public_key(), derived_owner_of(&client, &group.pk(), &id), "nor is it the client key's, which is no one's identity");
        let wrap = bed.relay.fetch(&Query { ids: vec![outer], ..Default::default() }, &community.relays).await.unwrap().pop().unwrap();
        assert_eq!(stream::wrap_owner(&wrap), Some(kept.public_key()));
    }

    #[tokio::test]
    async fn my_delete_leaves_relays_in_time_only_once_the_message_is_gone_everywhere() {
        let (bed, owner, _member) = TestBed::new();
        bed.swap_to(&owner);
        bed.relay.follow_cord01(&bed.relays);
        let community = create_community(&bed.relay, "Expire", bed.relays.clone(), None).await.unwrap();
        let general = community.channels[0].id;
        let group = channel_group_key(&community.community_root, &general, community.root_epoch);
        let fresh = send_message(&bed.relay, &community, &general, "deletable everywhere").await.unwrap();
        let old = send_message(&bed.relay, &community, &general, "an old send").await.unwrap();
        crate::db::community::forget_wrap_owners(&old).unwrap();

        let mut sub = bed.relay.subscribe(Query { kinds: vec![stream::KIND_WRAP], authors: vec![group.pk_hex()], ..Default::default() });
        let mut delete_of = |target: &str| {
            let wrap = sub.try_recv().expect("the in-plane delete goes out");
            match chat::open_chat_event(&wrap, &group, &general, community.root_epoch) {
                Ok(ChatEvent::Delete { .. }) => {}
                other => panic!("expected the delete of {target}, got {other:?}"),
            }
            wrap.tags.iter().find_map(|t| {
                let s = t.as_slice();
                (s.len() >= 2 && s[0] == "expiration").then(|| s[1].parse::<u64>().unwrap())
            })
        };
        delete_own(&bed.relay, &community, &general, &fresh, super::super::kind::MESSAGE).await.unwrap();
        let now = Timestamp::now().as_secs();
        let until = delete_of(&fresh).expect("its copies are gone, so the delete leaves too");
        assert!(until > now + 29 * 24 * 3600 && until <= now + 30 * 24 * 3600 + 5);
        delete_own(&bed.relay, &community, &general, &old, super::super::kind::MESSAGE).await.unwrap();
        assert_eq!(delete_of(&old), None, "it alone hides a copy a CORD-01 relay still holds");
    }

    #[tokio::test]
    async fn an_owned_delete_leaves_relays_no_later_than_its_self_destructing_message() {
        let (bed, owner, _member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Soon", bed.relays.clone(), None).await.unwrap();
        let general = community.channels[0].id;
        let soon = Timestamp::now().as_secs() + 3_600;
        let id = send_chat_message(&bed.relay, &community, &general, "brief", None, &[], vec![nostr_sdk::prelude::Tag::expiration(Timestamp::from_secs(soon))]).await.unwrap();
        let scrubbed = crate::community::message_delete::scrub_own(&bed.relay, &community.relays, &id).await.unwrap();
        assert_eq!(crate::community::message_delete::in_plane_delete_expiry(&id, scrubbed).await, Some(soon));
    }

    #[tokio::test]
    async fn send_chat_message_threads_the_reply_and_extra_tags() {
        let (bed, owner, _member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Re", bed.relays.clone(), None).await.unwrap();
        let general = community.channels[0].id;
        let me_hex = owner.keys.public_key().to_hex();

        let parent_id = send_message(&bed.relay, &community, &general, "parent").await.unwrap();
        let imeta = nostr_sdk::prelude::Tag::custom(
            "imeta",
            ["url https://e/blob".to_string(), "m image/png".to_string()],
        );
        let child_id = send_chat_message(
            &bed.relay, &community, &general, "child",
            Some((parent_id.as_str(), me_hex.as_str())), &[], vec![imeta],
        )
        .await
        .unwrap();

        let page = fetch_channel(&bed.relay, &community, &general, 50).await.unwrap();
        let child = page
            .iter()
            .find_map(|f| match &f.event {
                ChatEvent::Message { opened, reply_to, .. } if opened.rumor_id.to_hex() == child_id => Some((opened, reply_to)),
                _ => None,
            })
            .expect("the reply message round-trips");
        let reply = child.1.as_ref().expect("the reply reference is carried");
        assert_eq!(crate::simd::hex::bytes_to_hex_32(&reply.id), parent_id);
        assert_eq!(reply.author, Some(owner.keys.public_key()));
        assert!(
            child.0.rumor.tags.iter().any(|t| t.kind() == "imeta"),
            "the imeta attachment tag rides the rumor verbatim"
        );
    }

    #[tokio::test]
    async fn a_kick_needs_kick_authority_and_removes_the_target() {
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Kick", bed.relays.clone(), None).await.unwrap();

        // The target announces a Join (as an accepted invite would).
        let gb = super::super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
        let join = guestbook::build_join_rumor(member.keys.public_key(), None, 2_000);
        let (wrap, _) = guestbook::seal_guestbook_rumor(&join, &gb, &member.keys, Timestamp::from_secs(2)).unwrap();
        bed.relay.publish(&wrap, &bed.relays).await.unwrap();
        let before = memberlist(&bed.relay, &community).await.unwrap();
        assert!(before.contains(&member.keys.public_key()), "the join lands first");

        // An unprivileged member's kick of the owner is refused locally…
        bed.swap_to(&member);
        let err = kick_member(&bed.relay, &community, &owner.keys.public_key()).await.unwrap_err();
        assert!(err.contains("not authorized"), "unprivileged kick refused: {err}");

        // …and the owner (supreme, no grant needed) kicks the member out.
        bed.swap_to(&owner);
        kick_member(&bed.relay, &community, &member.keys.public_key()).await.unwrap();
        let after = memberlist(&bed.relay, &community).await.unwrap();
        assert!(!after.contains(&member.keys.public_key()), "the kicked member leaves the fold");
        assert!(after.contains(&owner.keys.public_key()), "the owner remains");
    }

    #[tokio::test]
    async fn an_obeyed_kick_is_recorded_at_its_own_time() {
        let (bed, owner, _member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Evict", bed.relays.clone(), None).await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        record_eviction(&community, 9_000_000);
        assert!(load_pending().tombstones.iter().any(|t| t.community_id == cid_hex && t.removed_at == 9_000_000), "the List is told, so no boot re-adopts it");
        assert!(tombstone_suppresses(&cid_hex, 8_999), "an invite older than the Kick stays answered");
        assert!(!tombstone_suppresses(&cid_hex, 9_001), "a re-invite after the Kick lands");
    }

    #[tokio::test]
    async fn a_rejoin_survives_a_stale_kick_and_an_uncaught_up_store() {
        // The self-eviction race: on a REJOIN the guestbook store starts empty while the
        // control fold has already re-derived the member's old ban mark, so the MEMBERLIST
        // legitimately excludes them for that window. A stale Kick landing there used to
        // read as an authorized eviction and the client nuked its own community.
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Rejoin", bed.relays.clone(), None).await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let (o, m) = (owner.keys.public_key(), member.keys.public_key());
        let join = |at: u64, id: u8| guestbook::GuestbookEvent { epoch: None, observed_at: None,
            rumor_id: [id; 32],
            entry: guestbook::GuestbookEntry::Join { member: m, invited_by: None, at_ms: at },
        };
        let kick = |at: u64, id: u8| guestbook::GuestbookEvent { epoch: None, observed_at: None,
            rumor_id: [id; 32],
            entry: guestbook::GuestbookEntry::Kick { actor: o, target: m, citation: None, at_ms: at },
        };

        // An authorized kick after their join stands.
        crate::db::community::set_guestbook(&cid_hex, &[join(1_000, 1), kick(2_000, 2)], 2).unwrap();
        assert!(stored_kick_verdict(&community, &m), "an authorized kick after the join is honored");
        assert_eq!(stored_kick_at(&community, &m), Some(2_000), "the eviction carries the Kick's own time");

        // A rejoin supersedes it — latest entry wins (CORD-02 §5).
        crate::db::community::set_guestbook(&cid_hex, &[join(1_000, 1), kick(2_000, 2), join(3_000, 3)], 3).unwrap();
        assert!(!stored_kick_verdict(&community, &m), "a Join newer than the kick clears the verdict");

        // The catch-up window itself: nothing folded yet decides nothing.
        crate::db::community::set_guestbook(&cid_hex, &[], 0).unwrap();
        assert!(!stored_kick_verdict(&community, &m), "an empty store is not an eviction");

        // And the memberlist is NOT a substitute: with the store empty it excludes them,
        // which is exactly the false positive this verdict replaced.
        assert!(
            !stored_memberlist(&community).unwrap().contains(&m),
            "the memberlist excludes an un-caught-up member — why it can't gate a kick"
        );
    }

    /// Seed a roster the way production does: `follow_control` writes the roster
    /// AND the folded edition heads in one pass, so a citation against a grant is
    /// resolvable. Seeding the roster alone yields a client that can never satisfy
    /// any `vac` — a shape no v2 production path produces.
    fn seed_roster_with_heads(community: &CommunityV2, roster: &crate::community::roles::CommunityRoles, at: i64) {
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        crate::db::community::set_community_roles(&cid_hex, roster, at).unwrap();
        for g in &roster.grants {
            let Some(m) = crate::simd::hex::hex_to_bytes_32_checked(&g.member) else { continue };
            let eid = super::super::derive::grant_locator(community.id(), &m);
            let entity_hex = crate::simd::hex::bytes_to_hex_32(&eid);
            crate::db::community::set_edition_head_at_epoch(&cid_hex, &entity_hex, 1, &[0xA1; 32], &[0xA2; 32], &[0xA3; 32], community.root_epoch.0).unwrap();
        }
    }

    /// Publish an edition CITING a specific grant version (CORD-04 §5's `vac`).
    async fn publish_grant_citing(
        relay: &MemoryRelay,
        community: &CommunityV2,
        signer: &Keys,
        member: &PublicKey,
        role_ids: Vec<String>,
        version: u64,
        citation: Option<&crate::community::edition::AuthorityCitation>,
    ) {
        let group = control::ControlPlane::of(&community).write_group().unwrap();
        let eid = crate::community::v2::derive::grant_locator(community.id(), &member.to_bytes());
        let prev = head_hash_on_relay(relay, community, &eid).await;
        let grant = MemberGrant { member: member.to_hex(), role_ids };
        let content = crate::community::v2::roles::grant_content_json(&grant).unwrap();
        let rumor = control::build_edition_rumor(signer.public_key(), vsk::GRANT, &eid, version, prev.as_ref(), &content, 1_000, citation);
        let (wrap, _) = control::seal_control_edition(&rumor, &group, signer, Timestamp::from_secs(1_000)).unwrap();
        relay.publish(&wrap, &community.relays).await.unwrap();
    }

    #[tokio::test]
    async fn an_uncited_edition_cannot_self_promote_or_outlive_a_demotion() {
        // The two ways an ADD could escalate if the citation were the thing holding
        // the line. It is not — rank is — and rank is resolved against the CURRENT
        // roster, which is precisely what the spec says the verifier must do.
        let (bed, owner, admin) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "NoEscalate", bed.relays.clone(), None).await.unwrap();
        let admin_pk = admin.keys.public_key();

        // An admin at position 3, and a role ABOVE them at position 1.
        let mid = "d1".repeat(32);
        let mut mid_role = admin_role(&mid, Permissions::admin().0);
        mid_role.position = 3;
        publish_role(&bed.relay, &community, &owner.keys, &mid_role, 1).await;
        let high = "d2".repeat(32);
        let mut high_role = admin_role(&high, Permissions::admin().0);
        high_role.position = 1;
        publish_role(&bed.relay, &community, &owner.keys, &high_role, 1).await;
        publish_grant(&bed.relay, &community, &owner.keys, &admin_pk, vec![mid.clone()], 1).await;

        // 1. SELF-PROMOTION, uncited: the admin grants THEMSELVES the higher role.
        publish_grant_citing(&bed.relay, &community, &admin.keys, &admin_pk, vec![high.clone(), mid.clone()], 2, None).await;
        // Assert the PROPERTY, not the shape: the role must not be held, whether the
        // forged edition was refused outright or folded back to the owner's version.
        let view = fetch_authority(&bed.relay, &community).await;
        assert!(
            !view.roles.grants.iter().any(|g| g.member == admin_pk.to_hex() && g.role_ids.contains(&high)),
            "an uncited edition must not let an author grant themselves a role they do not \
             outrank — you cannot act at or above your own rank, citation or not",
        );

        // 2. OUTLIVING A DEMOTION, uncited: the owner demotes the admin to nothing,
        //    and the admin's uncited grant to a bystander must stop being honored the
        //    moment this client folds the demotion.
        let bystander = Keys::generate().public_key();
        publish_grant_citing(&bed.relay, &community, &admin.keys, &bystander, vec![mid.clone()], 1, None).await;
        let before = fetch_authority(&bed.relay, &community).await;
        assert!(
            !before.roles.grants.iter().any(|g| g.member == bystander.to_hex()),
            "an admin at position 3 cannot grant position 3 — equal cannot act on equal",
        );

        publish_grant(&bed.relay, &community, &owner.keys, &admin_pk, vec![], 3).await;
        let after = fetch_authority(&bed.relay, &community).await;
        assert!(
            !after.roles.is_admin(&admin_pk.to_hex()),
            "the owner's demotion folds",
        );
        assert!(
            !after.roles.grants.iter().any(|g| g.member == bystander.to_hex()),
            "and nothing the demoted author wrote is honored afterwards — authority is \
             resolved against the CURRENT roster, which is what the citation was only ever \
             a scheduling hint for",
        );
    }

    #[tokio::test]
    async fn an_uncited_edition_folds_on_rank_alone_and_never_escalates() {
        // CORD-04 §5 calls the `vac` a SYNC FLOOR, not the verdict: a verifier waits
        // until it has synced the cited Grant, then resolves rank against its CURRENT
        // roster. Refusing an edition that cites NOTHING promoted that sync aid into an
        // authority requirement — and pre-citation clients emitted no `vac` at all, so
        // whole live rosters folded to nothing while a lenient implementation read the
        // same plane fine.
        //
        // What actually prevents escalation is rank, and rank is unchanged. This pins
        // both halves: a genuine in-rank edition folds without a citation, and an
        // out-of-rank one does not, cited or otherwise.
        let (bed, owner, admin) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Uncited", bed.relays.clone(), None).await.unwrap();
        let admin_pk = admin.keys.public_key();
        let rid = "c3".repeat(32);
        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::admin().0), 1).await;
        publish_grant(&bed.relay, &community, &owner.keys, &admin_pk, vec![rid.clone()], 1).await;

        // A role BENEATH the admin (they sit at position 1).
        let low_rid = "c4".repeat(32);
        let mut low = admin_role(&low_rid, Permissions::admin().0);
        low.position = 5;
        publish_role(&bed.relay, &community, &owner.keys, &low, 1).await;

        // 1. GENUINE and in-rank, citing nothing → folds.
        let bystander = Keys::generate().public_key();
        publish_grant_citing(&bed.relay, &community, &admin.keys, &bystander, vec![low_rid.clone()], 1, None).await;
        let view = fetch_authority(&bed.relay, &community).await;
        assert!(
            view.roles.grants.iter().any(|g| g.member == bystander.to_hex()),
            "an uncited edition from an author the roster DOES authorize, acting beneath \
             their own rank, is genuine and must fold",
        );
        assert!(view.roles.is_admin(&admin_pk.to_hex()), "the owner-authored grant still folds");

        // 2. ESCALATION, uncited: a stranger the roster authorizes for nothing.
        let stranger = Keys::generate();
        let victim = Keys::generate().public_key();
        publish_grant_citing(&bed.relay, &community, &stranger, &victim, vec![low_rid.clone()], 1, None).await;
        let view = fetch_authority(&bed.relay, &community).await;
        assert!(
            !view.roles.grants.iter().any(|g| g.member == victim.to_hex()),
            "an uncited edition from an UNAUTHORIZED author must never fold — dropping the \
             citation requirement must not become a way in",
        );

        // 3. ESCALATION, uncited, by a real admin acting AT their own rank: equal
        //    cannot act on equal, citation or not.
        let peer = Keys::generate().public_key();
        publish_grant_citing(&bed.relay, &community, &admin.keys, &peer, vec![rid.clone()], 1, None).await;
        let view = fetch_authority(&bed.relay, &community).await;
        assert!(
            !view.roles.grants.iter().any(|g| g.member == peer.to_hex()),
            "an authorized author still cannot grant AT their own rank — rank is what \
             stops escalation, and it is untouched",
        );

        // 4. ESCALATION, uncited REVOCATION — the case that makes the citation
        //    load-bearing. A strip names no roles, so the rank gate has no position to
        //    check and passes vacuously; the citation is the only thing standing there.
        //    An uncited edition may ADD authority, never remove it.
        publish_grant_citing(&bed.relay, &community, &stranger, &bystander, vec![], 9, None).await;
        let view = fetch_authority(&bed.relay, &community).await;
        assert!(
            view.roles.grants.iter().any(|g| g.member == bystander.to_hex()),
            "an uncited empty grant must NOT strip a member — a revocation's rank check is \
             vacuous, so tolerating it uncited hands any stranger a demotion primitive",
        );
    }

    #[tokio::test]
    async fn a_join_landing_inside_the_ban_window_survives_the_unban() {
        // The invite is deliberately ungated, so a fresh Join can arrive seconds
        // BEFORE the unban edition. It must reach the store (banned = a fold
        // verdict, not a storage verdict) so the unban resurrects the member —
        // dropped at ingest, they stayed invisible forever.
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Window", bed.relays.clone(), None).await.unwrap();
        let member_pk = member.keys.public_key();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);

        // Locally banned (edition folded at t=1000s), with the outliving mark.
        crate::db::community::set_community_banlist(&cid_hex, &[member_pk.to_hex()], 1_000).unwrap();
        crate::db::community::merge_community_ban_marks(&cid_hex, &[(member_pk.to_hex(), 1_000u64)].into_iter().collect()).unwrap();

        // Their Join lands 60s after the ban mark, while the banlist still says banned.
        let join = guestbook::GuestbookEvent { epoch: None, observed_at: None,
            rumor_id: [9u8; 32],
            entry: guestbook::GuestbookEntry::Join { member: member_pk, invited_by: None, at_ms: 1_060_000 },
        };
        assert!(ingest_guestbook_event(&community, join, 1_060).unwrap(), "stored while banned");
        assert!(
            !stored_memberlist(&community).unwrap().contains(&member_pk),
            "while banned, the fold keeps them out"
        );

        // The unban folds: same store, no refetch needed — the Join resurrects them.
        crate::db::community::set_community_banlist(&cid_hex, &[], 2_000).unwrap();
        assert!(
            stored_memberlist(&community).unwrap().contains(&member_pk),
            "after the unban the raced Join makes them a member again"
        );
    }

    #[tokio::test]
    async fn lifting_a_ban_writes_its_departure_dated_at_the_ban() {
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Lift", bed.relays.clone(), None).await.unwrap();
        let member_pk = member.keys.public_key();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let join = guestbook::GuestbookEvent { epoch: None, observed_at: None, rumor_id: [7u8; 32],
            entry: guestbook::GuestbookEntry::Join { member: member_pk, invited_by: None, at_ms: 1_000_000 },
        };
        assert!(ingest_guestbook_event(&community, join, 0).unwrap());

        set_banlist(&bed.relay, &community, &[member_pk.to_hex()]).await.unwrap();
        set_members_banned(&bed.relay, community.id(), &[member_pk], false).await.unwrap();

        let fresh = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let mark = crate::db::community::get_community_ban_marks(&cid_hex).unwrap()[&member_pk.to_hex()];
        assert_eq!(stored_kick_at(&fresh, &member_pk), Some(mark * 1000), "the departure is dated at the ban");
        assert!(!stored_memberlist(&fresh).unwrap().contains(&member_pk), "the pre-ban Join no longer counts here");
        assert!(!wire_guestbook_members(&bed.relay, &fresh).await.unwrap().contains(&member_pk), "nor for a reader who never saw the ban");

        let back = guestbook::GuestbookEvent { epoch: None, observed_at: None, rumor_id: [8u8; 32],
            entry: guestbook::GuestbookEntry::Join { member: member_pk, invited_by: None, at_ms: mark * 1000 + 1 },
        };
        assert!(ingest_guestbook_event(&fresh, back, 0).unwrap());
        assert!(stored_memberlist(&fresh).unwrap().contains(&member_pk), "a Join after the ban is a return");
    }

    /// [`MemoryRelay`] that refuses one plane's publishes, as a relay that never took them.
    struct Refuses<'a>(&'a MemoryRelay, PublicKey);
    #[async_trait::async_trait]
    impl Transport for Refuses<'_> {
        async fn publish(&self, event: &Event, relays: &[String]) -> Result<(), String> {
            if event.pubkey == self.1 {
                return Err("refused".into());
            }
            self.0.publish(event, relays).await
        }
        async fn fetch(&self, query: &Query, relays: &[String]) -> Result<Vec<Event>, String> {
            self.0.fetch(query, relays).await
        }
        async fn fetch_plane(&self, plane: &Keys, query: &Query, relays: &[String]) -> Result<crate::community::transport::PlaneFetch, String> {
            self.0.fetch_plane(plane, query, relays).await
        }
        async fn publish_durable(&self, event: &Event, relays: &[String]) -> Result<(), String> {
            self.publish(event, relays).await
        }
    }

    #[tokio::test]
    async fn a_lost_join_is_restored_once_dated_by_the_plane() {
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Lost", bed.relays.clone(), None).await.unwrap();
        send_direct_invite(&bed.relay, &community, &member.keys.public_key(), None, None).await.unwrap();
        let plane = super::super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch).pk();

        bed.swap_to(&member);
        let me = member.keys.public_key();
        let invite_wrap = fetch_direct_invite(&bed.relay, &bed.relays, &me).await;
        let joined = accept_direct_invite(&Refuses(&bed.relay, plane), &invite_wrap).await.unwrap();
        assert!(!wire_guestbook_members(&bed.relay, &joined).await.unwrap().contains(&me), "the Join never landed");
        sync_guestbook(&bed.relay, &joined).await.unwrap();
        assert!(!heal_my_join(&bed.relay, &joined).await.unwrap(), "the session that sent it waits for the next");

        // A later session reads the whole plane and finds no Join of theirs.
        bed.swap_to(&owner);
        bed.swap_to(&member);
        sync_guestbook(&bed.relay, &joined).await.unwrap();
        assert!(heal_my_join(&bed.relay, &joined).await.unwrap());
        assert!(!heal_my_join(&bed.relay, &joined).await.unwrap(), "once a session");

        let (events, _, _) = fetch_guestbook_events(&bed.relay, &joined, 0).await.unwrap();
        let mine: Vec<u64> = events
            .iter()
            .filter_map(|e| match &e.entry {
                guestbook::GuestbookEntry::Join { member, at_ms, .. } if *member == me => Some(*at_ms),
                _ => None,
            })
            .collect();
        let oldest = events.iter().filter(|e| !matches!(&e.entry, guestbook::GuestbookEntry::Join { member, .. } if *member == me)).map(|e| e.entry.at_ms()).min();
        assert_eq!(mine.len(), 1, "one Join on the wire");
        assert_eq!(Some(mine[0]), oldest, "dated by the plane's oldest entry, the same from any of their devices");
        assert!(wire_guestbook_members(&bed.relay, &joined).await.unwrap().contains(&me));
    }

    #[tokio::test]
    async fn a_stale_root_admin_write_is_refused_not_misdirected() {
        // The ban→unban race: a Ban's refound buries the old root over several
        // publishes while a concurrently-issued command still holds the
        // pre-commit struct. That unban used to land on the buried control
        // plane — "succeeding" while no reader would ever fold it — and a
        // concurrently-minted invite stranded its joiner on the dead epoch.
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Race", bed.relays.clone(), None).await.unwrap();
        let member_pk = member.keys.public_key();

        set_banlist(&bed.relay, &community, &[member_pk.to_hex()]).await.unwrap();
        let _rotated = refound_community(&bed.relay, &community, &[member_pk]).await.unwrap();

        // The stale-struct unban is REFUSED (retryable), never misdirected.
        let err = set_banlist(&bed.relay, &community, &[]).await.unwrap_err();
        assert!(err.contains("re-founded"), "unban: {err}");
        // A stale invite must not mint dead-epoch key material.
        let err = send_direct_invite(&bed.relay, &community, &member_pk, None, None).await.unwrap_err();
        assert!(err.contains("re-founded"), "invite: {err}");
        // Neither is a kick allowed to ride the buried guestbook.
        let err = kick_member(&bed.relay, &community, &member_pk).await.unwrap_err();
        assert!(err.contains("re-founded"), "kick: {err}");

        // The retry path: a fresh load lands the unban on the LIVING plane.
        let fresh = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        set_banlist(&bed.relay, &fresh, &[]).await.unwrap();
        let view = fetch_authority(&bed.relay, &fresh).await;
        assert!(view.banned.is_empty(), "the retried unban actually unbans");
    }

    /// [`MemoryRelay`] with a cooperative yield before every call, so two units
    /// driven by one `join!` genuinely interleave at each network boundary — on
    /// the single-threaded test runtime the bare relay resolves without yielding,
    /// the first unit runs to completion, and the race never happens.
    struct YieldyRelay<'a>(&'a MemoryRelay);
    #[async_trait::async_trait]
    impl Transport for YieldyRelay<'_> {
        async fn publish(&self, event: &Event, relays: &[String]) -> Result<(), String> {
            crate::rt::yield_now().await;
            self.0.publish(event, relays).await
        }
        async fn fetch(&self, query: &Query, relays: &[String]) -> Result<Vec<Event>, String> {
            crate::rt::yield_now().await;
            self.0.fetch(query, relays).await
        }
        async fn fetch_plane(&self, plane: &Keys, query: &Query, relays: &[String]) -> Result<crate::community::transport::PlaneFetch, String> {
            crate::rt::yield_now().await;
            self.0.fetch_plane(plane, query, relays).await
        }
        async fn publish_durable(&self, event: &Event, relays: &[String]) -> Result<(), String> {
            crate::rt::yield_now().await;
            self.0.publish_durable(event, relays).await
        }
    }

    #[tokio::test]
    async fn concurrent_bans_compose_instead_of_erasing_each_other() {
        // The SDK spawns a handler task per message, so a spam wave runs N ban
        // units concurrently. Unserialized, both read the pre-sibling banlist,
        // the second head erases the first target at every reader, and the
        // refound compacts that erasure into the new epoch permanently.
        let (bed, owner, _member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Wave", bed.relays.clone(), None).await.unwrap();
        let a = Keys::generate().public_key();
        let b = Keys::generate().public_key();

        let yieldy = YieldyRelay(&bed.relay);
        let (wave_a, wave_b) = ([a], [b]);
        let (ra, rb) = tokio::join!(
            set_members_banned(&yieldy, community.id(), &wave_a, true),
            set_members_banned(&yieldy, community.id(), &wave_b, true),
        );
        ra.unwrap();
        rb.unwrap();

        let fresh = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        assert_eq!(fresh.root_epoch, Epoch(2), "each single ban still performed its own read cut");
        let view = fetch_authority(&bed.relay, &fresh).await;
        assert!(
            view.banned.contains(&a.to_hex()) && view.banned.contains(&b.to_hex()),
            "both racing bans landed: {:?}",
            view.banned
        );
    }

    #[tokio::test]
    async fn bans_stacked_behind_a_rotation_coalesce_into_one_read_cut() {
        // Human-speed serial bans: the leader's read cut holds the lock for a
        // whole rotation, so bans arriving meanwhile deposit intents. The next
        // lock holder drains ALL of them — one edition, one rotation, however
        // many stacked. Worst case for a burst of N is 2 rotations, never N.
        let (bed, owner, _member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Stack", bed.relays.clone(), None).await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let banlist_hex = crate::simd::hex::bytes_to_hex_32(&super::super::derive::banlist_locator(community.id()));
        let (a, b, c, d) = (
            Keys::generate().public_key(),
            Keys::generate().public_key(),
            Keys::generate().public_key(),
            Keys::generate().public_key(),
        );

        let yieldy = YieldyRelay(&bed.relay);
        let (wa, wb, wc, wd) = ([a], [b], [c], [d]);
        // The first future drains itself and rotates; the other three stack
        // behind that rotation and coalesce under the next leader.
        let (ra, rb, rc, rd) = tokio::join!(
            set_members_banned(&yieldy, community.id(), &wa, true),
            set_members_banned(&yieldy, community.id(), &wb, true),
            set_members_banned(&yieldy, community.id(), &wc, true),
            set_members_banned(&yieldy, community.id(), &wd, true),
        );
        ra.unwrap();
        rb.unwrap();
        rc.unwrap();
        rd.unwrap();

        let fresh = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        assert_eq!(fresh.root_epoch, Epoch(2), "leader rotation + ONE coalesced rotation, never four");
        let (version, _) = crate::db::community::get_edition_head(&cid_hex, &banlist_hex).unwrap().unwrap();
        assert_eq!(version, 2, "two editions total: the leader's and the coalesced drain's");
        let view = fetch_authority(&bed.relay, &fresh).await;
        for pk in [a, b, c, d] {
            assert!(view.banned.contains(&pk.to_hex()), "{} missing from the fold", pk.to_hex());
        }
    }

    #[tokio::test]
    async fn a_stacked_ban_and_unban_coalesce_in_arrival_order() {
        // The drain applies intents in arrival order over the evolving list, so
        // ban(X) … unban(X) stacked behind one rotation nets X out entirely and
        // only the net newly-banned member costs a read cut.
        let (bed, owner, _member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Net", bed.relays.clone(), None).await.unwrap();
        let x = Keys::generate().public_key();
        let y = Keys::generate().public_key();

        let yieldy = YieldyRelay(&bed.relay);
        let (wx, wy) = ([x], [y]);
        let (rx1, ry, rx2) = tokio::join!(
            set_members_banned(&yieldy, community.id(), &wx, true),  // leader: rotates on X
            set_members_banned(&yieldy, community.id(), &wy, true),  // stacked
            set_members_banned(&yieldy, community.id(), &wx, false), // stacked: nets X back out
        );
        rx1.unwrap();
        ry.unwrap();
        rx2.unwrap();

        let fresh = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        assert_eq!(fresh.root_epoch, Epoch(2), "X's rotation + one coalesced rotation for Y");
        let view = fetch_authority(&bed.relay, &fresh).await;
        assert!(!view.banned.contains(&x.to_hex()), "the stacked unban netted X out");
        assert!(view.banned.contains(&y.to_hex()), "Y's stacked ban landed");
    }

    #[tokio::test]
    async fn a_second_member_folds_every_stacked_ban() {
        // Derek's observer divergence, inverted: the whole point of composing the
        // batch correctly is that an INDEPENDENT reader folding the same plane
        // agrees. A fresh joiner (separate account DB, post-rotation bundle) must
        // see every stacked ban — not just the leader's own echo.
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Agree", bed.relays.clone(), None).await.unwrap();
        let a = Keys::generate().public_key();
        let b = Keys::generate().public_key();

        let yieldy = YieldyRelay(&bed.relay);
        let (wa, wb) = ([a], [b]);
        let (ra, rb) = tokio::join!(
            set_members_banned(&yieldy, community.id(), &wa, true),
            set_members_banned(&yieldy, community.id(), &wb, true),
        );
        ra.unwrap();
        rb.unwrap();

        // Post-rotation bundle, exactly what a live link would serve now.
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let bundle = bundle_of(&held, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
        let bundle_json = serde_json::to_string(&bundle).unwrap();

        bed.swap_to(&member);
        let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
        let _ = follow_control(&bed.relay, &joined).await;
        let view = fetch_authority(&bed.relay, &joined).await;
        assert!(
            view.banned.contains(&a.to_hex()) && view.banned.contains(&b.to_hex()),
            "an independent reader folds BOTH stacked bans: {:?}",
            view.banned
        );
    }

    #[tokio::test]
    async fn a_net_zero_batch_publishes_no_edition() {
        // ban(X) + unban(X) stacked in one drain nets to the original list — the
        // batch must not spend an edition (or a rotation) publishing a no-op.
        let (bed, owner, _member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Noop", bed.relays.clone(), None).await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let banlist_hex = crate::simd::hex::bytes_to_hex_32(&super::super::derive::banlist_locator(community.id()));
        let x = Keys::generate().public_key();

        // The leader's slot is taken by a harmless real ban so X's ban+unban land
        // in ONE coalesced drain together.
        let decoy = Keys::generate().public_key();
        let yieldy = YieldyRelay(&bed.relay);
        let (wd, wx) = ([decoy], [x]);
        let (rd, r1, r2) = tokio::join!(
            set_members_banned(&yieldy, community.id(), &wd, true),
            set_members_banned(&yieldy, community.id(), &wx, true),
            set_members_banned(&yieldy, community.id(), &wx, false),
        );
        rd.unwrap();
        r1.unwrap();
        r2.unwrap();

        let fresh = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        assert_eq!(fresh.root_epoch, Epoch(1), "only the decoy's rotation — the net-zero drain rotated nothing");
        let (version, _) = crate::db::community::get_edition_head(&cid_hex, &banlist_hex).unwrap().unwrap();
        assert_eq!(version, 1, "only the decoy's edition — the net-zero drain published nothing");
        let view = fetch_authority(&bed.relay, &fresh).await;
        assert!(!view.banned.contains(&x.to_hex()));
        assert!(view.banned.contains(&decoy.to_hex()));
    }

    /// Fetches fine, refuses every publish — the dead-network shape.
    struct BrokenPublish<'a>(&'a MemoryRelay);
    #[async_trait::async_trait]
    impl Transport for BrokenPublish<'_> {
        async fn publish(&self, _e: &Event, _r: &[String]) -> Result<(), String> {
            crate::rt::yield_now().await;
            Err("relay refused".to_string())
        }
        async fn fetch(&self, query: &Query, relays: &[String]) -> Result<Vec<Event>, String> {
            crate::rt::yield_now().await;
            self.0.fetch(query, relays).await
        }
        async fn fetch_plane(&self, plane: &Keys, query: &Query, relays: &[String]) -> Result<crate::community::transport::PlaneFetch, String> {
            crate::rt::yield_now().await;
            self.0.fetch_plane(plane, query, relays).await
        }
        async fn publish_durable(&self, _e: &Event, _r: &[String]) -> Result<(), String> {
            crate::rt::yield_now().await;
            Err("relay refused".to_string())
        }
    }

    #[tokio::test]
    async fn a_failed_publish_answers_every_stacked_caller_and_never_hangs() {
        // The batch's shared fate: when the edition can't land, every stacked
        // intent must resolve with the error — a waiter left parked on a dead
        // oneshot would hang a moderation bot forever.
        let (bed, owner, _member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Dead", bed.relays.clone(), None).await.unwrap();
        let a = Keys::generate().public_key();
        let b = Keys::generate().public_key();

        let broken = BrokenPublish(&bed.relay);
        let (wa, wb) = ([a], [b]);
        let (ra, rb) = crate::rt::time::timeout(
            std::time::Duration::from_secs(30),
            async {
                tokio::join!(
                    set_members_banned(&broken, community.id(), &wa, true),
                    set_members_banned(&broken, community.id(), &wb, true),
                )
            },
        )
        .await
        .expect("stacked callers must resolve, never hang");
        assert!(ra.is_err(), "the leader surfaced the publish failure");
        assert!(rb.is_err(), "the stacked caller surfaced it too");

        // Nothing landed: a later fold shows no bans.
        let fresh = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let view = fetch_authority(&bed.relay, &fresh).await;
        assert!(view.banned.is_empty(), "no half-published state: {:?}", view.banned);
        assert_eq!(fresh.root_epoch, Epoch(0), "no rotation on a failed edition");
    }

    #[tokio::test]
    async fn a_poison_intent_fails_alone_not_its_batchmates() {
        // Per-intent verdicts: an add that busts the 500 ceiling answers ITS
        // caller with the refusal while its batch-mates publish normally.
        let (bed, owner, _member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Poison", bed.relays.clone(), None).await.unwrap();
        // Pre-fill to 498 so the leader lands 499, the first stacked ban lands
        // exactly 500, and the second stacked ban would be 501.
        let filler: Vec<String> = (0..498).map(|i| format!("{i:064x}")).collect();
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        set_banlist(&bed.relay, &held, &filler).await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        crate::db::community::set_community_banlist(&cid_hex, &filler, 1).unwrap();

        let (a, x, y) = (Keys::generate().public_key(), Keys::generate().public_key(), Keys::generate().public_key());
        let yieldy = YieldyRelay(&bed.relay);
        let (wa, wx, wy) = ([a], [x], [y]);
        let (ra, rx, ry) = tokio::join!(
            set_members_banned(&yieldy, community.id(), &wa, true),
            set_members_banned(&yieldy, community.id(), &wx, true),
            set_members_banned(&yieldy, community.id(), &wy, true),
        );
        ra.unwrap();
        rx.unwrap();
        let err = ry.unwrap_err();
        assert!(err.contains("ceiling"), "the over-cap intent failed alone: {err}");

        let list = crate::db::community::get_community_banlist(&cid_hex).unwrap();
        assert_eq!(list.len(), 500, "the batch published up to the ceiling");
        assert!(list.contains(&x.to_hex()) && !list.contains(&y.to_hex()));
    }

    #[tokio::test]
    async fn ban_many_is_one_edition_one_refound_for_the_whole_wave() {
        let (bed, owner, _member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Purge", bed.relays.clone(), None).await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let banlist_hex = crate::simd::hex::bytes_to_hex_32(&super::super::derive::banlist_locator(community.id()));
        let wave: Vec<PublicKey> = (0..3).map(|_| Keys::generate().public_key()).collect();

        set_members_banned(&bed.relay, community.id(), &wave, true).await.unwrap();

        let fresh = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        assert_eq!(fresh.root_epoch, Epoch(1), "one refound for the whole wave, not one per target");
        let (version, _) = crate::db::community::get_edition_head(&cid_hex, &banlist_hex).unwrap().unwrap();
        assert_eq!(version, 1, "one banlist edition carried the whole wave");
        let view = fetch_authority(&bed.relay, &fresh).await;
        for pk in &wave {
            assert!(view.banned.contains(&pk.to_hex()), "{} missing from the fold", pk.to_hex());
        }

        // The reductive mirror: unban two of three in one edition, no read cut.
        set_members_banned(&bed.relay, community.id(), &wave[..2], false).await.unwrap();
        let fresh = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        assert_eq!(fresh.root_epoch, Epoch(1), "an unban rotates nothing");
        let view = fetch_authority(&bed.relay, &fresh).await;
        assert_eq!(view.banned.len(), 1, "reductive: exactly the un-unbanned target remains");
        assert!(view.banned.contains(&wave[2].to_hex()));
    }

    #[tokio::test]
    async fn a_batch_past_the_banlist_cap_refuses_before_publishing() {
        let (bed, owner, _member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Cap", bed.relays.clone(), None).await.unwrap();
        let wave: Vec<PublicKey> = (0..=crate::community::v2::roles::MAX_BANLIST).map(|_| Keys::generate().public_key()).collect();

        let err = set_members_banned(&bed.relay, community.id(), &wave, true).await.unwrap_err();
        assert!(err.contains("ceiling"), "refused at the cap: {err}");
        let fresh = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        assert_eq!(fresh.root_epoch, Epoch(0), "nothing rotated");
        let view = fetch_authority(&bed.relay, &fresh).await;
        assert!(view.banned.is_empty(), "nothing published");
    }

    #[tokio::test]
    async fn an_uncited_kick_from_an_admin_is_not_honored() {
        // CORD-04 §5: a non-owner authority action must name the Grant it acts
        // under, and the reader refuses until it holds that Grant. Emitting the
        // `vac` without checking it buys nothing — a demoted admin's kick would
        // still land on any client that hadn't synced the demotion.
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Uncited", bed.relays.clone(), None).await.unwrap();
        let admin = Keys::generate();
        let member_pk = member.keys.public_key();
        grant_admin(&bed.relay, &community, &admin.public_key()).await.unwrap();

        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let view = fetch_authority(&bed.relay, &community).await;
        crate::db::community::set_community_roles(&cid_hex, &view.roles, 1_000).unwrap();

        let entity_id = super::super::derive::grant_locator(community.id(), &admin.public_key().to_bytes());
        let entity_hex = crate::simd::hex::bytes_to_hex_32(&entity_id);
        let (version, edition_hash) = crate::db::community::get_edition_head(&cid_hex, &entity_hex).unwrap().unwrap();
        let cite = crate::community::edition::AuthorityCitation { entity_id, version, edition_hash };

        let joined = guestbook::GuestbookEvent { epoch: None, observed_at: None,
            rumor_id: [1u8; 32],
            entry: guestbook::GuestbookEntry::Join { member: member_pk, invited_by: None, at_ms: 1_000 },
        };
        let kick = |citation, id: u8, at| guestbook::GuestbookEvent { epoch: None, observed_at: None,
            rumor_id: [id; 32],
            entry: guestbook::GuestbookEntry::Kick { actor: admin.public_key(), target: member_pk, citation, at_ms: at },
        };
        let roles = crate::db::community::get_community_roles(&cid_hex).unwrap();
        let empty_bans = std::collections::BTreeSet::new();
        let empty_marks = std::collections::BTreeMap::new();
        let fold = |evs: &[guestbook::GuestbookEvent]| {
            fold_members(&community, evs, Default::default(), &roles, &empty_bans, &empty_marks).unwrap()
        };

        assert!(
            fold(&[joined.clone(), kick(None, 2, 2_000)]).contains(&member_pk),
            "an uncited kick from an admin is not honored"
        );
        assert!(
            !fold(&[joined.clone(), kick(Some(cite.clone()), 3, 3_000)]).contains(&member_pk),
            "the same kick WITH its synced citation removes them"
        );
        crate::db::community::set_community_banlist(&cid_hex, &[admin.public_key().to_hex()], 4_000).unwrap();
        assert!(
            fold(&[joined, kick(Some(cite), 3, 3_000)]).contains(&member_pk),
            "a banned admin's Guestbook events count for nothing (CORD-04 §4)"
        );
    }

    #[tokio::test]
    async fn kicking_an_admin_strips_their_roles_first() {
        // CORD-04 §6 composition: Role Removal THEN the directive. Kicking without the
        // strip leaves the target out of the memberlist but still holding every
        // management bit, so every client keeps honoring their control editions.
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Compose", bed.relays.clone(), None).await.unwrap();
        let member_pk = member.keys.public_key();
        let member_hex = member_pk.to_hex();
        let owner_hex = owner.keys.public_key().to_hex();

        grant_admin(&bed.relay, &community, &member_pk).await.unwrap();
        assert!(fetch_authority(&bed.relay, &community).await.roles.is_admin(&member_hex));

        kick_member(&bed.relay, &community, &member_pk).await.unwrap();

        let view = fetch_authority(&bed.relay, &community).await;
        assert!(!view.roles.is_admin(&member_hex), "the kick stripped their rank");
        assert!(
            !view.roles.is_authorized(&member_hex, Some(&owner_hex), Permissions::MANAGE_ROLES),
            "a kicked admin holds no bit"
        );
        assert!(
            !memberlist(&bed.relay, &community).await.unwrap().contains(&member_pk),
            "and the directive still removed them"
        );
    }

    #[tokio::test]
    async fn grant_admin_mints_one_deterministic_role_and_revoke_strips_it() {
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Adm", bed.relays.clone(), None).await.unwrap();
        let member_pk = member.keys.public_key();
        let member_hex = member_pk.to_hex();
        let owner_hex = owner.keys.public_key().to_hex();

        grant_admin(&bed.relay, &community, &member_pk).await.unwrap();
        let view = fetch_authority(&bed.relay, &community).await;
        assert!(view.roles.is_admin(&member_hex), "the grant folds as admin");
        assert!(view.roles.is_authorized(&member_hex, Some(&owner_hex), Permissions::MANAGE_ROLES));

        // A second grant (any device) converges on the SAME role entity — and a
        // repeat is a no-op, not a version bump.
        let second = Keys::generate().public_key();
        grant_admin(&bed.relay, &community, &second).await.unwrap();
        grant_admin(&bed.relay, &community, &member_pk).await.unwrap();
        let view = fetch_authority(&bed.relay, &community).await;
        assert_eq!(view.roles.roles.len(), 1, "one Admin role, never a fork");
        assert!(view.roles.is_admin(&member_hex) && view.roles.is_admin(&second.to_hex()));
        let grant = view.roles.grants.iter().find(|g| g.member == member_hex).unwrap();
        assert_eq!(grant.role_ids.len(), 1, "no duplicate role id in the grant");

        // Revoke strips ONLY the admin role and de-authorizes.
        revoke_admin(&bed.relay, &community, &member_pk).await.unwrap();
        let view = fetch_authority(&bed.relay, &community).await;
        assert!(!view.roles.is_admin(&member_hex), "revoked");
        assert!(view.roles.is_admin(&second.to_hex()), "the other admin is untouched");
        assert!(!view.roles.is_authorized(&member_hex, Some(&owner_hex), Permissions::KICK));
    }

    #[tokio::test]
    async fn follow_control_persists_the_roster_for_sync_local_reads() {
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Persist", bed.relays.clone(), None).await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let member_hex = member.keys.public_key().to_hex();
        grant_admin(&bed.relay, &community, &member.keys.public_key()).await.unwrap();

        // The passive follow folds + persists; the read is then LOCAL.
        follow_control(&bed.relay, &community).await.unwrap().updated;
        let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
        assert!(roster.is_admin(&member_hex), "the persisted roster reads back without a fetch");

        // A withholding relay serves nothing — an empty fold raises no gap flag, and
        // the stored roster must be RETAINED, never wiped.
        let withholding = MemoryRelay::new();
        let _ = follow_control(&withholding, &community).await;
        let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
        assert!(roster.is_admin(&member_hex), "withholding never shrinks standing");

        // A real revocation (a NEWER grant edition) does replace it.
        revoke_admin(&bed.relay, &community, &member.keys.public_key()).await.unwrap();
        follow_control(&bed.relay, &community).await.unwrap().updated;
        let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
        assert!(!roster.is_admin(&member_hex), "the revoke folds + persists");
    }

    #[tokio::test]
    async fn grant_admin_is_refused_for_a_non_owner_and_publishes_nothing() {
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "NoSquat", bed.relays.clone(), None).await.unwrap();

        bed.swap_to(&member);
        let err = grant_admin(&bed.relay, &community, &member.keys.public_key()).await.unwrap_err();
        assert!(err.contains("owner"), "refused before any publish: {err}");

        // The deterministic admin-role entity stays unsquatted — the owner's later
        // legitimate mint is version 1 and folds cleanly.
        bed.swap_to(&owner);
        let view = fetch_authority(&bed.relay, &community).await;
        assert!(view.roles.roles.is_empty(), "no role edition landed");
        grant_admin(&bed.relay, &community, &member.keys.public_key()).await.unwrap();
        let view = fetch_authority(&bed.relay, &community).await;
        assert!(view.roles.is_admin(&member.keys.public_key().to_hex()));
    }

    #[tokio::test]
    async fn grant_admin_merges_other_roles_and_refuses_a_withheld_grant() {
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Merge", bed.relays.clone(), None).await.unwrap();
        let member_pk = member.keys.public_key();

        // The member already holds a Mod role, granted through the real send path
        // (so this device's floors track both entities).
        let mod_rid = crate::simd::hex::bytes_to_hex_32(&[0x66; 32]);
        set_role(&bed.relay, &community, &admin_role(&mod_rid, Permissions::BAN)).await.unwrap();
        grant_roles(&bed.relay, &community, &member_pk, vec![mod_rid.clone()]).await.unwrap();

        // With no wrap of the grant held and a relay that serves none, the merge must refuse: a
        // blind push would erase the Mod role at a higher version.
        let withholding = MemoryRelay::new();
        forget_held(&community);
        let err = grant_admin(&withholding, &community, &member_pk).await.unwrap_err();
        assert!(err.contains("could not be fetched"), "withheld grant refused: {err}");

        // Against the full relay the merge preserves the Mod role.
        grant_admin(&bed.relay, &community, &member_pk).await.unwrap();
        let view = fetch_authority(&bed.relay, &community).await;
        let grant = view.roles.grants.iter().find(|g| g.member == member_pk.to_hex()).unwrap();
        assert_eq!(grant.role_ids.len(), 2, "admin ADDED to the existing grant, not replacing it");
        assert!(grant.role_ids.contains(&mod_rid));
    }

    #[tokio::test]
    async fn fetch_authority_reflects_a_granted_admin() {
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Auth", bed.relays.clone(), None).await.unwrap();
        let rid = crate::simd::hex::bytes_to_hex_32(&[0x5a; 32]);
        publish_role(&bed.relay, &community, &owner.keys, &admin_role(&rid, Permissions::ADMIN_ALL), 1).await;
        publish_grant(&bed.relay, &community, &owner.keys, &member.keys.public_key(), vec![rid], 1).await;

        let view = fetch_authority(&bed.relay, &community).await;
        let member_hex = member.keys.public_key().to_hex();
        assert!(view.roles.is_admin(&member_hex), "the granted member folds as admin");
        assert!(
            view.roles.is_authorized(&member_hex, Some(&owner.keys.public_key().to_hex()), Permissions::KICK),
            "an ADMIN_ALL grant carries KICK"
        );
        assert!(view.banned.is_empty());
    }

    // ── Pins (CORD-04 §7) — fold, authority, and the silent Admin widening ──

    /// The full wire round trip: a real message pinned into a published
    /// edition, folded by the control follow, persisted, and read back proven.
    #[tokio::test]
    async fn a_pin_edition_folds_persists_and_reads_back() {
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Pinsville", vec!["wss://r".into()], None).await.unwrap();
        let general = community.channels[0].id;
        let ch_hex = crate::simd::hex::bytes_to_hex_32(&general.0);

        send_message(&relay, &community, &general, "pin-worthy").await.unwrap();
        let page = fetch_channel(&relay, &community, &general, 10).await.unwrap();
        let opened = page
            .iter()
            .find_map(|f| match &f.event {
                ChatEvent::Message { opened, .. } => Some(opened.clone()),
                _ => None,
            })
            .expect("the sent message reads back");

        let ch = community.channels[0].clone();
        let conv = channel_conv_key_at(&community, &ch, 0).expect("owner holds the public plane key");
        let entry = crate::community::v2::pins::build_pin_entry(&opened, &conv, &ch_hex).unwrap();
        let content = crate::community::v2::pins::serialize_public_pin_list(&[entry]).unwrap();

        let eid = crate::community::v2::derive::pins_locator(community.id(), &general);
        publish_control_edition(&relay, &community, vsk::PINS, &eid, &content).await.unwrap();
        follow_control(&relay, &community).await.unwrap().updated;

        let read = read_channel_pins(&community, &general).unwrap();
        assert!(!read.sealed);
        assert!(read.version >= 1, "the folded head persisted");
        assert_eq!(read.pins.len(), 1);
        assert_eq!(read.pins[0].content, "pin-worthy");
        assert_eq!(read.pins[0].rumor_id, opened.rumor_id.to_hex());
    }

    #[tokio::test]
    async fn a_fresh_join_sees_pins_and_the_banlist_without_waiting_for_a_follow() {
        // The join's verification walk already folds the control plane, so pins and
        // the banlist must persist FROM THE JOIN — deferring them to the follow
        // worker's queued re-walk left a fresh member pins-blind (and rendering a
        // banned author) for the whole queue delay.
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "PinJoin", bed.relays.clone(), None).await.unwrap();
        let general = community.channels[0].id;
        let ch_hex = crate::simd::hex::bytes_to_hex_32(&general.0);

        send_message(&bed.relay, &community, &general, "pin-worthy").await.unwrap();
        let page = fetch_channel(&bed.relay, &community, &general, 10).await.unwrap();
        let opened = page
            .iter()
            .find_map(|f| match &f.event {
                ChatEvent::Message { opened, .. } => Some(opened.clone()),
                _ => None,
            })
            .expect("the sent message reads back");
        let ch = community.channels[0].clone();
        let conv = channel_conv_key_at(&community, &ch, 0).unwrap();
        let entry = crate::community::v2::pins::build_pin_entry(&opened, &conv, &ch_hex).unwrap();
        let content = crate::community::v2::pins::serialize_public_pin_list(&[entry]).unwrap();
        let eid = crate::community::v2::derive::pins_locator(community.id(), &general);
        publish_control_edition(&bed.relay, &community, vsk::PINS, &eid, &content).await.unwrap();
        let spammer = Keys::generate().public_key().to_hex();
        set_banlist(&bed.relay, &community, std::slice::from_ref(&spammer)).await.unwrap();
        let bundle = bundle_of(&community, BundleAudience::Link, Some(owner.keys.public_key()), None, None);
        let bundle_json = serde_json::to_string(&bundle).unwrap();

        bed.swap_to(&member);
        let joined = accept_parked_invite(&bed.relay, &bundle_json, None).await.unwrap();
        // Deliberately NO follow_control here — the join alone must suffice.
        let read = read_channel_pins(&joined, &general).unwrap();
        assert!(!read.sealed);
        assert_eq!(read.pins.len(), 1, "pins visible the instant the join returns");
        assert_eq!(read.pins[0].content, "pin-worthy");
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&joined.id().0);
        let banlist = crate::db::community::get_community_banlist(&cid_hex).unwrap();
        assert!(banlist.contains(&spammer), "the banlist is enforced from the join, not the first follow");
    }

    /// CORD-04 §5: a pins edition from an author holding no PIN_MESSAGES never
    /// becomes the head — the fold's authority gate covers the new entity.
    #[tokio::test]
    async fn an_unauthorized_pin_edition_never_folds() {
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Gated", vec!["wss://r".into()], None).await.unwrap();
        let general = community.channels[0].id;

        let rogue = Keys::generate();
        let group = control::ControlPlane::of(&community).write_group().unwrap();
        let eid = crate::community::v2::derive::pins_locator(community.id(), &general);
        let rumor = control::build_edition_rumor(rogue.public_key(), vsk::PINS, &eid, 1, None, r#"{"entries":[]}"#, 2_000, None);
        let (wrap, _) = control::seal_control_edition(&rumor, &group, &rogue, Timestamp::from_secs(2_000)).unwrap();
        relay.publish(&wrap, &community.relays).await.unwrap();

        follow_control(&relay, &community).await.unwrap().updated;
        let read = read_channel_pins(&community, &general).unwrap();
        assert_eq!(read.version, 0, "an unauthorized edition never persists a head");
        assert!(read.pins.is_empty());
    }

    /// The silent owner-side widening: a pre-pins Admin role (founding mask)
    /// gains PIN_MESSAGES as one edition of the same entity; idempotent after.
    #[tokio::test]
    async fn owner_silently_widens_a_legacy_admin_role() {
        let (_tmp, _guard, owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Legacy", vec!["wss://r".into()], None).await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let rid = crate::simd::hex::bytes_to_hex_32(&[0x5d; 32]);

        // An Admin role exactly as a pre-pins build published it.
        let legacy = Role {
            role_id: rid.clone(),
            name: "Admin".into(),
            position: 1,
            permissions: Permissions(Permissions::ADMIN_FOUNDING_MASK),
            scope: RoleScope::Server,
            color: 0, rank: None, display: false, mentionable: false, extra: Default::default(),
        };
        publish_role(&relay, &community, &owner, &legacy, 1).await;
        follow_control(&relay, &community).await.unwrap().updated;

        assert!(upgrade_admin_role_pin_bit(&relay, &community).await.unwrap(), "the widening publishes");
        follow_control(&relay, &community).await.unwrap().updated;
        let roles = crate::db::community::get_community_roles(&cid_hex).unwrap();
        let widened = roles.roles.iter().find(|r| r.role_id == rid).expect("same entity");
        assert!(widened.permissions.contains(Permissions::PIN_MESSAGES), "bit 11 landed");
        assert!(widened.permissions.contains(Permissions::ADMIN_FOUNDING_MASK), "nothing stripped");

        // Second call: nothing left to widen.
        assert!(!upgrade_admin_role_pin_bit(&relay, &community).await.unwrap());
    }

    /// §7 deletion duty: the author-curator's own deleted message leaves the
    /// list as an immediate omitting edition.
    #[tokio::test]
    async fn the_deletion_duty_omits_a_pinned_message() {
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Duties", vec!["wss://r".into()], None).await.unwrap();
        let general = community.channels[0].id;
        let ch_hex = crate::simd::hex::bytes_to_hex_32(&general.0);

        let rumor_id = send_message(&relay, &community, &general, "soon deleted").await.unwrap();
        let page = fetch_channel(&relay, &community, &general, 10).await.unwrap();
        let opened = page
            .iter()
            .find_map(|f| match &f.event {
                ChatEvent::Message { opened, .. } => (opened.rumor_id.to_hex() == rumor_id).then(|| opened.clone()),
                _ => None,
            })
            .unwrap();
        let ch = community.channels[0].clone();
        let conv = channel_conv_key_at(&community, &ch, 0).unwrap();
        let entry = crate::community::v2::pins::build_pin_entry(&opened, &conv, &ch_hex).unwrap();
        publish_pin_list(&relay, &community, &ch, &[entry]).await.unwrap();
        assert_eq!(read_channel_pins(&community, &general).unwrap().pins.len(), 1);

        // The author holds the bit (owner) → the duty publishes the omission at once.
        run_pin_duty(&relay, &ch_hex, &rumor_id, None).await.unwrap();
        let after = read_channel_pins(&community, &general).unwrap();
        assert!(after.pins.is_empty(), "the omitting edition landed");
        assert!(after.version >= 2, "a NEW edition, not a local erase");
    }

    /// §7 edit duty: an edited pinned message gets its proof bundle refreshed,
    /// so keyless readers see the revision — and the duty is idempotent.
    #[tokio::test]
    async fn the_edit_duty_refreshes_a_pinned_proof() {
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Edits", vec!["wss://r".into()], None).await.unwrap();
        let general = community.channels[0].id;
        let ch_hex = crate::simd::hex::bytes_to_hex_32(&general.0);

        let rumor_id = send_message(&relay, &community, &general, "first words").await.unwrap();
        let page = fetch_channel(&relay, &community, &general, 10).await.unwrap();
        let opened = page
            .iter()
            .find_map(|f| match &f.event {
                ChatEvent::Message { opened, .. } => (opened.rumor_id.to_hex() == rumor_id).then(|| opened.clone()),
                _ => None,
            })
            .unwrap();
        let ch = community.channels[0].clone();
        let conv = channel_conv_key_at(&community, &ch, 0).unwrap();
        let entry = crate::community::v2::pins::build_pin_entry(&opened, &conv, &ch_hex).unwrap();
        publish_pin_list(&relay, &community, &ch, &[entry]).await.unwrap();

        send_edit(&relay, &community, &general, &rumor_id, "second thoughts", &[]).await.unwrap();
        let page = fetch_channel(&relay, &community, &general, 10).await.unwrap();
        let edit_opened = page
            .iter()
            .find_map(|f| match &f.event {
                ChatEvent::Edit { opened, .. } => Some(opened.clone()),
                _ => None,
            })
            .expect("the edit reads back");

        run_pin_duty(&relay, &ch_hex, &rumor_id, Some(edit_opened.clone())).await.unwrap();
        let after = read_channel_pins(&community, &general).unwrap();
        assert_eq!(after.pins.len(), 1);
        assert_eq!(
            after.pins[0].content, "second thoughts",
            "the refreshed bundle proves the revision"
        );
        let v = after.version;

        // Same revision again → monotonic guard, no new edition.
        run_pin_duty(&relay, &ch_hex, &rumor_id, Some(edit_opened)).await.unwrap();
        assert_eq!(read_channel_pins(&community, &general).unwrap().version, v, "idempotent");
    }

    /// §7 author-side trigger: an own edit's relay echo is a dedup'd duplicate
    /// at ingest, so publish_chat's SEND echo must decide the duty itself —
    /// otherwise the author's own pin lags behind their message while every
    /// other client's follows ("the affected author acts at once").
    #[tokio::test]
    async fn an_own_edit_echo_carries_the_pin_duty_trigger() {
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "OwnEdit", vec!["wss://r".into()], None).await.unwrap();
        let general = community.channels[0].id;

        let rumor_id = send_message(&relay, &community, &general, "before").await.unwrap();
        send_edit(&relay, &community, &general, &rumor_id, "after", &[]).await.unwrap();
        let page = fetch_channel(&relay, &community, &general, 10).await.unwrap();
        let edit_event = &page.iter().find(|f| matches!(&f.event, ChatEvent::Edit { .. })).expect("the edit reads back").event;
        let msg_event = &page.iter().find(|f| matches!(&f.event, ChatEvent::Message { .. })).expect("the message reads back").event;

        let updated = crate::community::v2::inbound::ChatPersist::Updated {
            message: crate::types::Message::default(),
            edit_event: None,
        };
        let (target_hex, opened) = own_echo_pin_duty(&updated, edit_event).expect("an applied own edit fires the duty");
        assert_eq!(target_hex, rumor_id, "the duty targets the EDITED message, not the edit rumor");
        assert_ne!(opened.rumor_id.to_hex(), rumor_id, "and carries the edit's own opened stream for the bundle");

        // A fresh message echo is not a duty…
        let new = crate::community::v2::inbound::ChatPersist::New(crate::types::Message::default());
        assert!(own_echo_pin_duty(&new, msg_event).is_none());
        // …and neither is a reaction-shaped Updated on a non-edit event.
        assert!(own_echo_pin_duty(&updated, msg_event).is_none());
    }

    /// §7 Rotator duty: a private-channel rotation republishes the Pin List
    /// sealed under the NEW epoch — a member who joins after the rotation
    /// (holding only the new key) must not read the channel's pins as dark.
    #[tokio::test]
    async fn a_rotation_reseals_the_pin_list_under_the_new_epoch() {
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Reseal", vec!["wss://r".into()], None).await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let chan = create_private_channel(&relay, &community, "vault").await.unwrap();
        let community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let ch_hex = crate::simd::hex::bytes_to_hex_32(&chan.0);

        let rumor_id = send_message(&relay, &community, &chan, "sealed wisdom").await.unwrap();
        let page = fetch_channel(&relay, &community, &chan, 10).await.unwrap();
        let opened = page
            .iter()
            .find_map(|f| match &f.event {
                ChatEvent::Message { opened, .. } => (opened.rumor_id.to_hex() == rumor_id).then(|| opened.clone()),
                _ => None,
            })
            .unwrap();
        let ch = community.channel(&chan).unwrap().clone();
        let old_epoch = ch.epoch.0;
        let conv = channel_conv_key_at(&community, &ch, old_epoch).unwrap();
        let entry = crate::community::v2::pins::build_pin_entry(&opened, &conv, &ch_hex).unwrap();
        publish_pin_list(&relay, &community, &ch, &[entry]).await.unwrap();
        let (_, v_before) = crate::db::community::get_community_pins(&cid_hex, &ch_hex).unwrap().unwrap();

        // Rotate the channel away from a (never-granted) member.
        let roster = crate::db::community::get_community_roles(&cid_hex).unwrap();
        rekey_channel_excluding(&relay, &community, &chan, &roster, &[], &[Keys::generate().public_key()])
            .await
            .unwrap();

        // The stored head is a NEW edition, sealed under the NEW epoch.
        let (content, version) = crate::db::community::get_community_pins(&cid_hex, &ch_hex).unwrap().unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&content).unwrap();
        assert_eq!(
            parsed["epoch"].as_str().unwrap(),
            (old_epoch + 1).to_string(),
            "the reseal names the rotated epoch"
        );
        assert!(version > v_before, "a real edition, not a local rewrite");

        // The rotator's own post-rotation view still verifies the pin.
        let community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let read = read_channel_pins(&community, &chan).unwrap();
        assert!(!read.sealed);
        assert_eq!(read.pins.len(), 1);
        assert_eq!(read.pins[0].content, "sealed wisdom");
    }

    /// The production ban-eraser: set_banlist must ECHO its published list
    /// into the local cache immediately. Before this, the cache moved only on
    /// a successful control fold — and a composing caller (ban = banlist →
    /// grant strip → refound) whose refound tripped re-read the stale list,
    /// so each of 19 real bans erased its predecessors.
    #[tokio::test]
    async fn a_published_banlist_echoes_locally_before_any_fold() {
        let (_tmp, _guard, _owner) = init_test_db();
        let relay = MemoryRelay::new();
        let community = create_community(&relay, "Modtown", vec!["wss://r".into()], None).await.unwrap();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let spammer_a = "aa".repeat(32);
        let spammer_b = "bb".repeat(32);

        // Ban A. NO fold runs — the cache must hold the publish regardless.
        set_banlist(&relay, &community, &[spammer_a.clone()]).await.unwrap();
        assert_eq!(
            crate::db::community::get_community_banlist(&cid_hex).unwrap(),
            vec![spammer_a.clone()],
            "the publish echoes without waiting for a fold"
        );

        // Ban B composes from the cache, exactly as the SDK does.
        let mut list = crate::db::community::get_community_banlist(&cid_hex).unwrap();
        list.push(spammer_b.clone());
        set_banlist(&relay, &community, &list).await.unwrap();
        let held = crate::db::community::get_community_banlist(&cid_hex).unwrap();
        assert!(
            held.contains(&spammer_a) && held.contains(&spammer_b),
            "sequential bans UNION; the second must not erase the first: {held:?}"
        );

        // The wire agrees: a real fold confirms rather than regresses.
        follow_control(&relay, &community).await.unwrap().updated;
        let folded = crate::db::community::get_community_banlist(&cid_hex).unwrap();
        assert!(folded.contains(&spammer_a) && folded.contains(&spammer_b));
    }

    /// Publishes everywhere but `refusing`, serves nothing from `hollow`, and has `throttled` turn
    /// away every third publish.
    struct PickyRelays<'a> {
        inner: &'a MemoryRelay,
        refusing: Option<&'static str>,
        hollow: Option<&'static str>,
        throttled: Option<&'static str>,
        sent: std::sync::atomic::AtomicUsize,
    }
    impl PickyRelays<'_> {
        fn only(relays: &[String], which: Option<&str>) -> bool {
            relays.len() == 1 && which == Some(relays[0].as_str())
        }
    }
    #[async_trait::async_trait]
    impl Transport for PickyRelays<'_> {
        async fn publish(&self, e: &Event, r: &[String]) -> Result<(), String> {
            if Self::only(r, self.refusing) {
                return Err("blocked: not on the allow list".into());
            }
            if Self::only(r, self.throttled) && self.sent.fetch_add(1, std::sync::atomic::Ordering::Relaxed) % 3 == 2 {
                return Err("rate-limited: slow down".into());
            }
            self.inner.publish(e, r).await
        }
        async fn fetch(&self, query: &Query, relays: &[String]) -> Result<Vec<Event>, String> {
            if Self::only(relays, self.hollow) {
                return Ok(Vec::new());
            }
            self.inner.fetch(query, relays).await
        }
        async fn fetch_plane(&self, plane: &Keys, query: &Query, relays: &[String]) -> Result<crate::community::transport::PlaneFetch, String> {
            if Self::only(relays, self.hollow) {
                return Ok(crate::community::transport::PlaneFetch::whole(Vec::new()));
            }
            self.inner.fetch_plane(plane, query, relays).await
        }
        async fn publish_durable(&self, e: &Event, r: &[String]) -> Result<(), String> {
            self.publish(e, r).await
        }
    }

    async fn wraps_by(relay: &MemoryRelay, author: &str, on: &str) -> std::collections::HashSet<nostr_sdk::prelude::EventId> {
        let q = Query { kinds: vec![stream::KIND_WRAP], authors: vec![author.to_string()], ..Default::default() };
        relay.fetch(&q, &[on.to_string()]).await.unwrap().into_iter().map(|e| e.id).collect()
    }

    #[tokio::test]
    async fn a_relay_move_lands_members_on_a_whole_community() {
        let (bed, owner, member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Guild", bed.relays.clone(), None).await.unwrap();
        let general = community.channels[0].id;
        send_message(&bed.relay, &community, &general, "before the move").await.unwrap();
        send_direct_invite(&bed.relay, &community, &member.keys.public_key(), None, None).await.unwrap();
        bed.swap_to(&member);
        let invite = fetch_direct_invite(&bed.relay, &bed.relays, &member.keys.public_key()).await;
        let joined = accept_direct_invite(&bed.relay, &invite).await.unwrap();

        // The owner leaves every old relay for one of their own.
        bed.swap_to(&owner);
        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let new = vec!["wss://new".to_string()];
        let moved = move_relays(&bed.relay, &held, &new).await.unwrap();
        assert_eq!((moved.relays.clone(), moved.removed.clone()), (new.clone(), bed.relays.clone()));
        assert!(moved.copied > 0);
        assert_eq!(crate::db::community::load_community_v2(community.id()).unwrap().unwrap().relays, new);

        // Every Control edition and Guestbook event the old relay held is on the new one.
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let control = control::ControlPlane::of(&held).pk_hex();
        let guestbook = crate::community::v2::derive::guestbook_group_key(&held.community_root, held.id(), held.root_epoch).pk_hex();
        for plane in [&control, &guestbook] {
            let old = wraps_by(&bed.relay, plane, "wss://r").await;
            assert!(!old.is_empty() && old.is_subset(&wraps_by(&bed.relay, plane, "wss://new").await), "the new relay holds the whole plane");
        }

        // A member still reading only the old relay folds the move from the edition announced there.
        bed.swap_to(&member);
        assert_eq!(joined.relays, bed.relays);
        let followed = follow_control(&bed.relay, &joined).await.unwrap().updated.expect("the move folds");
        assert_eq!(followed.relays, new);
        assert_eq!(retired_relays(&cid_hex), bed.relays, "and listens a while longer where members who haven't moved still write");

        // History moved with it: the member reads the old post from the new relay alone.
        assert_eq!(texts_in(&bed.relay, &followed, &general).await, vec!["before the move"]);
    }

    #[tokio::test]
    async fn a_relay_move_carries_a_locked_channels_seal() {
        use crate::community::roles::OverwriteTarget;
        let (bed, owner, _member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Sealed move", bed.relays.clone(), None).await.unwrap();
        let held = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        activate_roles_v2(&bed.relay, &held(), crate::community::v2::roles::EVERYONE_DEFAULT).await.unwrap();
        let general = community.channels[0].id;
        for i in 0..4 {
            send_message(&bed.relay, &held(), &general, &format!("kept{i}")).await.unwrap();
        }
        let nothing = Permissions::SEND_MESSAGES | Permissions::ADD_REACTIONS | Permissions::CONNECT;
        set_overwrite(&bed.relay, &held(), general.0, OverwriteTarget::Everyone, 0, nothing).await.unwrap();
        assert_eq!(sealing::seal_history(&bed.relay, &held(), held().channel(&general).unwrap()).await.unwrap(), Some(4));
        let new = vec!["wss://new".to_string()];
        let moved = move_relays(&bed.relay, &held(), &new).await.unwrap();
        assert_eq!(moved.relays, new);
        let after = held();
        assert_eq!(after.relays, new);
        // Read from the new relay alone: the seal's pages and the ids they name came with it.
        let got = fetch_channel_history(&bed.relay, &after, &general, 50, 6, None, Some(now_ms() / 1000 + 3600), crate::community::transport::Evidence::Quorum, |_, _| true, |_| Default::default()).await.unwrap();
        let mut texts: Vec<String> = got.into_iter().filter_map(|f| match f.event { ChatEvent::Message { opened, .. } => Some(opened.rumor.content), _ => None }).collect();
        texts.sort();
        assert_eq!(texts, vec!["kept0", "kept1", "kept2", "kept3"]);
    }

    #[tokio::test]
    async fn a_relay_that_wont_hold_the_community_moves_nobody() {
        let (bed, owner, _member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Guild", bed.relays.clone(), None).await.unwrap();
        let control = control::ControlPlane::of(&community).pk_hex();
        let before = wraps_by(&bed.relay, &control, "wss://r").await;
        let unchanged = || crate::db::community::load_community_v2(community.id()).unwrap().unwrap().relays;

        let refusing = PickyRelays { inner: &bed.relay, refusing: Some("wss://new"), hollow: None, throttled: None, sent: Default::default() };
        let err = move_relays(&refusing, &community, &["wss://new".to_string()]).await.unwrap_err();
        assert!(err.contains("wss://new") && err.contains("nothing was changed"), "{err}");
        assert_eq!(unchanged(), bed.relays);

        // A relay that takes the events but doesn't serve them back is no home either.
        let hollow = PickyRelays { inner: &bed.relay, refusing: None, hollow: Some("wss://new"), throttled: None, sent: Default::default() };
        let err = move_relays(&hollow, &community, &["wss://r".to_string(), "wss://new".to_string()]).await.unwrap_err();
        assert!(err.contains("doesn't serve"), "{err}");
        assert_eq!(unchanged(), bed.relays);
        assert_eq!(wraps_by(&bed.relay, &control, "wss://r").await, before, "and no move was announced");
    }

    #[tokio::test]
    async fn the_check_before_a_move_names_a_relay_that_throttles() {
        let (bed, owner, _member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Guild", bed.relays.clone(), None).await.unwrap();
        let picky = PickyRelays { inner: &bed.relay, refusing: Some("wss://closed"), hollow: None, throttled: Some("wss://busy"), sent: Default::default() };
        let checks = check_relays(&picky, &community, &["wss://r".into(), "wss://fine".into(), "wss://busy".into(), "wss://closed".into()]).await.unwrap();
        let by = |r: &str| checks.iter().find(|c| c.relay == r).unwrap();
        assert_eq!(checks.len(), 3, "a relay already listed isn't checked");
        assert!(by("wss://fine").ok && !by("wss://fine").rate_limited);
        assert!(by("wss://busy").ok && by("wss://busy").rate_limited, "a relay that turns away part of a burst is flagged before anything moves");
        assert!(!by("wss://closed").ok && by("wss://closed").reason.as_deref().is_some_and(|r| r.contains("blocked")));
        assert_eq!(crate::db::community::load_community_v2(community.id()).unwrap().unwrap().relays, bed.relays, "checking moves nothing");
    }

    #[tokio::test]
    async fn dropping_a_relay_tops_up_the_ones_kept() {
        let (bed, owner, _member) = TestBed::new();
        bed.swap_to(&owner);
        let both = vec!["wss://r".to_string(), "wss://s".to_string()];
        let community = create_community(&bed.relay, "Guild", both.clone(), None).await.unwrap();
        // An edit only the relay being dropped took.
        let mut only_r = community.clone();
        only_r.relays = vec!["wss://r".to_string()];
        let mut meta = community.metadata();
        meta.description = Some("only on r".into());
        edit_community_metadata(&bed.relay, &only_r, &meta).await.unwrap();
        let control = control::ControlPlane::of(&community).pk_hex();
        assert!(!wraps_by(&bed.relay, &control, "wss://r").await.is_subset(&wraps_by(&bed.relay, &control, "wss://s").await));

        let held = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        move_relays(&bed.relay, &held, &["wss://s".to_string()]).await.unwrap();
        assert!(
            wraps_by(&bed.relay, &control, "wss://r").await.is_subset(&wraps_by(&bed.relay, &control, "wss://s").await),
            "what only the dropped relay held is on the one kept"
        );
    }

    #[tokio::test]
    async fn a_move_the_old_relays_wont_hear_moves_nobody() {
        let (bed, owner, _member) = TestBed::new();
        bed.swap_to(&owner);
        let community = create_community(&bed.relay, "Guild", bed.relays.clone(), None).await.unwrap();
        let control = control::ControlPlane::of(&community).pk_hex();
        // The old relay still serves reads but takes no writes.
        let deaf = PickyRelays { inner: &bed.relay, refusing: Some("wss://r"), hollow: None, throttled: None, sent: Default::default() };
        let err = move_relays(&deaf, &community, &["wss://new".to_string()]).await.unwrap_err();
        assert!(err.contains("None of the current relays took the announcement"), "{err}");
        assert_eq!(crate::db::community::load_community_v2(community.id()).unwrap().unwrap().relays, bed.relays, "nothing moved here");
        assert_eq!(
            wraps_by(&bed.relay, &control, "wss://new").await,
            wraps_by(&bed.relay, &control, "wss://r").await,
            "and the new relay holds no announcement the old one doesn't"
        );
    }

    #[tokio::test]
    async fn a_rename_made_during_a_move_survives_it() {
        let (bed, owner, _member) = TestBed::new();
        bed.swap_to(&owner);
        let stale = create_community(&bed.relay, "Guild", bed.relays.clone(), None).await.unwrap();
        let mut meta = stale.metadata();
        meta.name = "Guild Two".into();
        edit_community_metadata(&bed.relay, &stale, &meta).await.unwrap();
        move_relays(&bed.relay, &stale, &["wss://r".to_string(), "wss://new".to_string()]).await.unwrap();
        let held = crate::db::community::load_community_v2(stale.id()).unwrap().unwrap();
        assert_eq!((held.name.as_str(), held.relays.len()), ("Guild Two", 2), "the move is built on what the community holds now");
    }
}

#[cfg(test)]
mod folded_chain_tests {
    use super::*;
    use nostr_sdk::prelude::Keys;

    #[tokio::test]
    async fn a_fold_tells_the_feed_each_edition_on_the_heads_chain_since_its_floor() {
        let (_tmp, _guard, _owner) = super::tests::init_test_db();
        let relay = crate::community::transport::memory::MemoryRelay::new();
        let community = create_community(&relay, "Chain", vec!["wss://r".into()], None).await.unwrap();
        let entity = [0x5e; 32];
        let (a, b, c) = (Keys::generate().public_key(), Keys::generate().public_key(), Keys::generate().public_key());
        let edition = |version: u64, hash: u8, prev: Option<u8>, author: PublicKey| ParsedEdition {
            author,
            vsk: String::new(),
            entity_id: entity,
            version,
            prev_hash: prev.map(|p| [p; 32]),
            content: String::new(),
            self_hash: [hash; 32],
            created_at: version * 10,
            inner_id: [hash; 32],
            authority: None,
            binding: None,
        };
        // v1 ← v2 (b) ← v3 (a), a rival v2 (c) off the chain, and v2's content re-signed by c.
        let mut resigned = edition(2, 2, Some(1), c);
        resigned.inner_id = [0x22; 32];
        let editions = vec![edition(1, 1, None, a), edition(2, 2, Some(1), b), edition(3, 3, Some(2), a), edition(2, 9, Some(1), c), resigned];
        let entity_hex = crate::simd::hex::bytes_to_hex_32(&entity);
        let head = FoldedHead { entity_hex: entity_hex.clone(), version: 3, self_hash: [3; 32], inner_id: [3; 32], author: a.to_bytes(), rebased: false };
        let mut floors = Floors::default();
        floors.insert(entity_hex.clone(), (1, [1; 32], None, None, None));

        note_folded_chains(&community, &floors, std::iter::once(&head), &editions, |id| *id != [0x22; 32]);
        assert_eq!(super::super::changes::folded_marks(community.id(), &entity_hex), vec![(2, b), (3, a)]);
    }
}