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
//! v2 realtime โ€” the `authors`-based live subscription + dispatch.
//!
//! v2 addresses planes by their group pubkey (CORD-01), so the subscription is `{kinds:[1059,21059], authors:[โ€ฆplane pubkeysโ€ฆ]}`. A
//! received event is routed to the owning community and handed to the shared
//! [`inbound::dispatch_wrap`], which fires the protocol-agnostic
//! `InboundEventHandler` the SDK's `on_message` consumes.
//!
//! The kind-1059 dispatch rule (CLAUDE.md A4): the listen loop tries this v2
//! path for events on the v2 subscription; DM gift wraps and 3313 Direct Invites
//! (both `#p=me`) stay on the DM subscription โ€” the author-set here never
//! includes an identity key, so the two never collide.

use std::collections::{BTreeMap, HashMap, HashSet};
use std::sync::{Arc, LazyLock, Mutex as StdMutex};

use nostr_sdk::prelude::{Client, Event, Filter, Kind, PublicKey, RelayStatus, RelayUrl, SubscriptionId, Timestamp};
use tokio::sync::mpsc::UnboundedSender;
use tokio::sync::Mutex;

use super::community::CommunityV2;
use super::stream;
use super::{derive, inbound};
use crate::community::{CommunityId, Epoch};
use crate::event_handler::InboundEventHandler;
use crate::ClientRelayExt;

/// The targeted subscription id (streams on desktop).
static V2_SUB_ID: LazyLock<Mutex<Option<SubscriptionId>>> = LazyLock::new(|| Mutex::new(None));
/// The pool-wide subscription id (the path that streams on Android).
static V2_POOLWIDE_SUB_ID: LazyLock<Mutex<Option<SubscriptionId>>> = LazyLock::new(|| Mutex::new(None));
/// Fingerprint of the relayโ†’authors plan the live subs carry โ€” an unchanged plan
/// skips a churny unsubscribe+resubscribe.
static V2_SUB_FP: LazyLock<Mutex<Option<u64>>> = LazyLock::new(|| Mutex::new(None));

/// Session generation of the last COMPLETED [`refresh_subscription`] pass, or
/// `u64::MAX` before any. Generation-keyed rather than a bare bool so an account
/// swap invalidates it automatically โ€” a per-account global that survived a swap
/// would report account A's readiness for account B.
static V2_SUB_READY_GEN: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(u64::MAX);

#[inline]
fn mark_subscription_ready() {
    V2_SUB_READY_GEN.store(
        crate::db::current_session_id(),
        std::sync::atomic::Ordering::Release,
    );
}

/// Whether the v2 Community subscription pass has COMPLETED for the active
/// session: live channel events are being delivered (or there is genuinely
/// nothing to subscribe to). `false` during the cold-start window where the
/// relay-connect wait + stream-auth priming are still running โ€” the state a
/// health-checking bot could previously not distinguish from "subscribed to
/// nothing".
pub fn subscription_ready() -> bool {
    V2_SUB_READY_GEN.load(std::sync::atomic::Ordering::Acquire)
        == crate::db::current_session_id()
}
/// Outer-wrap ids already dispatched, so the handler fires EXACTLY ONCE per
/// message. The relay pool delivers the same wrap under both the targeted and
/// pool-wide subs and from every relay independently, so without this a bot's
/// `on_message` (and its reply) would run several times per message โ€” the DM
/// path dedups by outer id for the same reason. Per session; a message's
/// duplicates all arrive within a short window, so a recent-set suffices.
///
/// Two generations of each id's first 8 bytes (ids are SHA-256): a full `cur`
/// ages into `prev`, so the newest [`SEEN_WRAPS_GEN`] ids are always remembered.
#[derive(Default)]
struct SeenWraps {
    cur: HashSet<u64>,
    prev: HashSet<u64>,
}
const SEEN_WRAPS_GEN: usize = 2048;

impl SeenWraps {
    /// `true` the first time `id` is offered.
    fn first_sight(&mut self, id: &[u8; 32]) -> bool {
        let key = u64::from_le_bytes([id[0], id[1], id[2], id[3], id[4], id[5], id[6], id[7]]);
        if self.cur.contains(&key) || self.prev.contains(&key) {
            return false;
        }
        if self.cur.len() >= SEEN_WRAPS_GEN {
            // Swap then clear: the new `cur` reuses the retired table instead of regrowing one.
            std::mem::swap(&mut self.cur, &mut self.prev);
            self.cur.clear();
        }
        self.cur.insert(key);
        true
    }

    /// Let `id` be offered again: a wrap held for its time comes back through here.
    fn forget(&mut self, id: &[u8; 32]) {
        let key = u64::from_le_bytes([id[0], id[1], id[2], id[3], id[4], id[5], id[6], id[7]]);
        self.cur.remove(&key);
        self.prev.remove(&key);
    }
}

struct SeenWrapsKey;
fn seen_wraps() -> Arc<StdMutex<SeenWraps>> {
    crate::db::current_session().scoped::<SeenWrapsKey, StdMutex<SeenWraps>>()
}

/// The per-community follow QUEUE. dispatch, boot catch-up, reconnect, and manual
/// sync all just [`enqueue_follow`] โ€” non-blocking + coalesced. A single spawned
/// worker ([`spawn_follow_worker`]) drains it and runs one combined rekey+control
/// follow per community at a time, so two triggers can never concurrently
/// whole-row-save and clobber each other. This replaces the old gate/rerun/
/// spawn-vs-await machinery: an enqueue never blocks its caller, and a junk-wrap
/// flood coalesces to at most one queued + one running follow per community.
/// Reset on session swap (the worker exits when its `std::sync::Arc<crate::db::Session>` invalidates or
/// its channel closes).
static V2_FOLLOW_TX: LazyLock<StdMutex<Option<UnboundedSender<CommunityId>>>> = LazyLock::new(|| StdMutex::new(None));
/// Community ids currently queued or processing โ€” coalesces a burst to one follow.
static V2_FOLLOW_PENDING: LazyLock<StdMutex<HashSet<[u8; 32]>>> = LazyLock::new(|| StdMutex::new(HashSet::new()));
/// Queued ids that a LIVE rotation triggered, which the worker takes ahead of the
/// rest of its batch. Every follow is a network walk, so a boot backlog of dozens
/// of communities is minutes โ€” spent sitting on the dead epoch of the one that
/// just rotated, unable to read it and indistinguishable from a strand.
static V2_FOLLOW_URGENT: LazyLock<StdMutex<HashSet<[u8; 32]>>> = LazyLock::new(|| StdMutex::new(HashSet::new()));
/// Per-community follow serialization, shared by the queue worker AND the inline
/// (headless) follow path. The worker-vs-inline CHOICE is a benign race
/// (`follow_worker_running` is check-then-act; a worker can spawn right after a
/// `false`), so correctness can't ride on it: whichever path runs, the follow body
/// executes under this lock and two follows of one community can never interleave
/// their whole-row saves. Bounded by the held-community count; reset on swap.
type FollowLocks = std::collections::HashMap<[u8; 32], Arc<Mutex<()>>>;

static V2_FOLLOW_LOCKS: LazyLock<StdMutex<FollowLocks>> =
    LazyLock::new(|| StdMutex::new(std::collections::HashMap::new()));

/// A Community's held state moved: the renderer redraws, and a handler that asked hears what changed.
fn refreshed(handler: &dyn InboundEventHandler, community_id: &str) {
    handler.on_community_refreshed(community_id);
    super::changes::notify(handler, community_id);
}

/// This account no longer holds the Community: the change feed's view of it goes too.
fn self_removed(handler: &dyn InboundEventHandler, community_id: &str) {
    super::changes::forget(community_id);
    handler.on_community_self_removed(community_id);
}

fn dissolved(handler: &dyn InboundEventHandler, community_id: &str) {
    super::changes::forget(community_id);
    handler.on_community_dissolved(community_id);
}

struct LiveAuthorityMoves;

fn live_authority_moves() -> Arc<StdMutex<HashSet<[u8; 32]>>> {
    crate::db::current_session().scoped::<LiveAuthorityMoves, _>()
}

/// A live fold moved `id`'s Roster or banlist. The full pass it queues re-reads a plane that
/// already holds the change, so alone it would find nothing moved: no key looked for, no
/// holder's duty run, and whoever the change let in left waiting on a clock.
fn note_live_authority_move(id: &CommunityId) {
    live_authority_moves().lock().unwrap_or_else(|e| e.into_inner()).insert(id.0);
}

/// Whether a live fold moved `id`'s authority since its last full pass. Asked once a pass.
fn take_live_authority_move(id: &CommunityId) -> bool {
    live_authority_moves().lock().unwrap_or_else(|e| e.into_inner()).remove(&id.0)
}

/// Whether a follow of this community is queued.
pub(crate) fn follow_pending(id: &CommunityId) -> bool {
    V2_FOLLOW_PENDING.lock().unwrap_or_else(|e| e.into_inner()).contains(&id.0)
}

/// Bumped each time a relay's live subscriptions are sent again: what it carried in between never
/// arrived, so a control window read before then may lack it.
struct LinkGeneration;

pub(crate) fn note_resubscribe() {
    crate::db::current_session().scoped::<LinkGeneration, std::sync::atomic::AtomicU64>().fetch_add(1, std::sync::atomic::Ordering::SeqCst);
}

pub(crate) fn link_generation() -> u64 {
    crate::db::current_session().scoped::<LinkGeneration, std::sync::atomic::AtomicU64>().load(std::sync::atomic::Ordering::SeqCst)
}

/// The follow lock for one community (created on first use).
pub(crate) fn follow_lock(id: &CommunityId) -> Arc<Mutex<()>> {
    let mut locks = V2_FOLLOW_LOCKS.lock().unwrap();
    if let Some(lock) = locks.get(&id.0) {
        return Arc::clone(lock);
    }
    // A lock only the map holds has no holder or waiter, so a left community's goes here.
    locks.retain(|_, lock| Arc::strong_count(lock) > 1);
    Arc::clone(locks.entry(id.0).or_default())
}

/// The author set the live v2 subscriptions CURRENTLY carry (sorted hex), read
/// from the client's own table. Diagnostics: comparing this against the freshly-
/// derived plane authors is the one-glance test for "did a rotation leave this
/// client subscribed to a dead epoch" โ€” the failure that otherwise only shows up
/// as silent missing events.
pub async fn subscribed_author_set() -> Vec<String> {
    let Some(client) = crate::state::nostr_client() else {
        return Vec::new();
    };
    let ids = [V2_SUB_ID.lock().await.clone(), V2_POOLWIDE_SUB_ID.lock().await.clone()];
    let mut authors: std::collections::BTreeSet<[u8; 32]> = std::collections::BTreeSet::new();
    for id in ids.into_iter().flatten() {
        for filters in client.subscription(&id).await.into_values() {
            for f in filters {
                authors.extend(f.authors.into_iter().flatten().map(|pk| pk.to_bytes()));
            }
        }
    }
    authors.iter().map(crate::simd::hex::bytes_to_hex_32).collect()
}

/// Diagnostics: run the three follow stages once for `id` UNDER the follow lock
/// (so it can't race the worker into a whole-row clobber) and return each
/// stage's outcome as a display string. Reloads freshly-persisted state between
/// stages, exactly like `follow_community`. Mutating โ€” same writes a live
/// follow makes; the lock serializes it against the worker.
#[cfg(debug_assertions)]
pub async fn debug_run_follow_stages(id: &CommunityId, session: &std::sync::Arc<crate::db::Session>) -> (String, String, String) {
    let lock = follow_lock(id);
    let _guard = lock.lock().await;
    let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));

    let Ok(Some(c)) = crate::db::community::load_community_v2(id) else {
        return ("community gone".into(), "-".into(), "-".into());
    };
    let rekeys = match super::service::follow_rekeys(&transport, &c, session).await {
        Ok(f) => format!(
            "Ok(updated={} self_removed={} dissolved={})",
            f.updated.as_ref().map(|u| format!("root_e{}", u.root_epoch.0)).unwrap_or_else(|| "no".into()),
            f.self_removed, f.dissolved
        ),
        Err(e) => format!("ERR: {e}"),
    };
    let Ok(Some(c)) = crate::db::community::load_community_v2(id) else {
        return (rekeys, "community gone".into(), "-".into());
    };
    let control = match super::service::follow_control(&transport, &c).await {
        Ok(v) => format!("Ok(changed={} authority={})", v.updated.is_some(), v.authority_changed),
        Err(e) => format!("ERR: {e}"),
    };
    let Ok(Some(c)) = crate::db::community::load_community_v2(id) else {
        return (rekeys, control, "community gone".into());
    };
    let guestbook = match super::service::sync_guestbook(&transport, &c).await {
        Ok(fresh) => format!("Ok(fresh={})", fresh.len()),
        Err(e) => format!("ERR: {e}"),
    };
    (rekeys, control, guestbook)
}

/// Whether `id` is one of the live Concord subscriptions, without waiting: while a refresh holds
/// them, every id answers yes.
pub fn is_live_subscription(id: &SubscriptionId) -> bool {
    if V2_RETIRED_SUBS.lock().unwrap_or_else(|e| e.into_inner()).contains(id) {
        return true;
    }
    match (V2_SUB_ID.try_lock(), V2_POOLWIDE_SUB_ID.try_lock()) {
        (Ok(targeted), Ok(poolwide)) => targeted.as_ref() == Some(id) || poolwide.as_ref() == Some(id),
        _ => true,
    }
}

/// How long after a live subscription is swapped what the planes carried is read once more,
/// and how far back that read reaches.
const SWAP_REPLAY_DELAY_MS: u64 = 2_000;
const SWAP_REPLAY_BACK_MS: u64 = 15_000;

/// How long after a Channel's writer epoch moves its last one is still listened to.
const WRITER_TAIL_MS: u64 = 5 * 60 * 1000;

/// The writer address a Channel left within [`WRITER_TAIL_MS`]: a writer who has not yet taken
/// the new epoch goes on posting there for a moment, and the ledger still stands behind them.
fn just_left_writer(ch: &super::community::ChannelV2) -> Option<PublicKey> {
    let now = crate::clock::now_ms();
    let ledger = ch.writers.as_ref()?;
    let (live, _) = ledger.current_writer()?;
    let began = ledger.writer_start(live)?;
    if now.saturating_sub(began) > WRITER_TAIL_MS {
        return None;
    }
    let (_, pk, _) = ledger.writers().filter(|(e, _, _)| *e < live).max_by_key(|(e, _, _)| e.0)?;
    PublicKey::from_slice(&pk).ok()
}

/// Live subscriptions a refresh replaced, newest last. A relay pushes what it took in before it
/// registered the new REQ down the old one, so the old one's events still count as live.
static V2_RETIRED_SUBS: LazyLock<StdMutex<std::collections::VecDeque<SubscriptionId>>> = LazyLock::new(|| StdMutex::new(std::collections::VecDeque::new()));

/// The live subscriptions now standing, read without waiting on a refresh: the listener asks
/// for every event, and one held up while a refresh subscribes falls behind a ring that drops
/// what it overwrites without a word.
static V2_LIVE_SUBS: LazyLock<StdMutex<Vec<SubscriptionId>>> = LazyLock::new(|| StdMutex::new(Vec::new()));

fn note_live_subscription(id: &SubscriptionId) {
    let mut live = V2_LIVE_SUBS.lock().unwrap_or_else(|e| e.into_inner());
    if !live.contains(id) {
        live.push(id.clone());
    }
}

/// How many replaced subscriptions are still listened to.
const RETIRED_SUBS_KEPT: usize = 8;

fn retire_subscription(id: SubscriptionId) {
    V2_LIVE_SUBS.lock().unwrap_or_else(|e| e.into_inner()).retain(|l| *l != id);
    let mut retired = V2_RETIRED_SUBS.lock().unwrap_or_else(|e| e.into_inner());
    if retired.len() >= RETIRED_SUBS_KEPT {
        retired.pop_front();
    }
    retired.push_back(id);
}

/// Whether an event that came in under `id` is a Concord live event: one of the live
/// subscriptions, or one a refresh just replaced.
pub fn routes_live(id: &SubscriptionId) -> bool {
    V2_LIVE_SUBS.lock().unwrap_or_else(|e| e.into_inner()).contains(id) || V2_RETIRED_SUBS.lock().unwrap_or_else(|e| e.into_inner()).contains(id)
}

pub async fn subscription_id() -> Option<SubscriptionId> {
    V2_SUB_ID.lock().await.clone()
}

pub async fn poolwide_subscription_id() -> Option<SubscriptionId> {
    V2_POOLWIDE_SUB_ID.lock().await.clone()
}

/// Clear the v2 realtime state on a session reset (called from `swap_session`), so a
/// stale sub id / author-set can't leak across accounts.
pub async fn clear() {
    *V2_SUB_ID.lock().await = None;
    *V2_POOLWIDE_SUB_ID.lock().await = None;
    *V2_SUB_FP.lock().await = None;
    V2_RETIRED_SUBS.lock().unwrap_or_else(|e| e.into_inner()).clear();
    V2_LIVE_SUBS.lock().unwrap_or_else(|e| e.into_inner()).clear();
    *seen_wraps().lock().unwrap_or_else(|e| e.into_inner()) = SeenWraps::default();
    // Drop the queue sender so the worker's channel closes and it exits; the
    // next login spawns a fresh worker.
    *V2_FOLLOW_TX.lock().unwrap() = None;
    // Replaced, not cleared: a cleared table keeps its peak allocation.
    *V2_FOLLOW_PENDING.lock().unwrap() = HashSet::new();
    *V2_FOLLOW_URGENT.lock().unwrap() = HashSet::new();
    *V2_FOLLOW_LOCKS.lock().unwrap() = FollowLocks::new();
    // Account A's stream keys must not keep authenticating (or answering relay
    // challenges) once account B is live.
    super::streamauth::clear();
}

/// Every plane pubkey a set of v2 communities publishes under that
/// [`inbound::dispatch_wrap`] handles โ€” the subscription author-set. Per
/// community: the guestbook, the control plane, and each channel's current
/// Chat-Plane address. Pure + deterministic (deduped, sorted) โ€” the testable core.
///
/// The **control plane** rides here so a long-running bot follows metadata +
/// public-channel edits live ([`super::service::follow_control`] re-folds on a
/// recognized wrap), and the next-epoch rekey planes ride via `rekey_authors`
/// (each subscribed author has its `dispatch_wrap` arm โ€” never one without the
/// other).
pub fn plane_authors(communities: &[CommunityV2]) -> Vec<PublicKey> {
    let mut out: Vec<PublicKey> = communities.iter().flat_map(community_addresses).collect();
    // Byte order is the hex order, without a String per comparison.
    out.sort_unstable_by_key(|p| p.to_bytes());
    out.dedup();
    out
}

/// Take back what a Writers ledger folded anywhere on this device no longer stands behind, then
/// read those Channels again from there: a stale ledger may have dropped what the new one admits
/// (CORD-03 ยง1). What a failed read leaves undone stays owed.
pub(crate) async fn settle_owed_retractions<T: crate::community::transport::Transport + ?Sized>(id: &crate::community::CommunityId, transport: &T, handler: &dyn InboundEventHandler) {
    let Ok(Some(community)) = crate::db::community::load_community_v2(id) else { return };
    let cid = crate::simd::hex::bytes_to_hex_32(&id.0);
    // A departure is one member's: only their posts are read again, and nothing new is admitted.
    for (chan, author, since, until, generation) in crate::db::community::owed_author_retractions(&cid).unwrap_or_default() {
        let (Some(ch), Ok(pk)) = (community.channels.iter().find(|c| crate::simd::hex::bytes_to_hex_32(&c.id.0) == chan), nostr_sdk::prelude::PublicKey::from_hex(&author)) else {
            let _ = crate::db::community::settle_author_retraction(&cid, &chan, &author, since, until, generation);
            continue;
        };
        if super::service::retract_by(transport, &community, ch, &pk, since, until, handler).await.is_err() {
            return;
        }
        let _ = crate::db::community::settle_author_retraction(&cid, &chan, &author, since, until, generation);
    }
    // Cleared only once done: a drain cut short leaves it owed.
    for (chan, since, generation) in crate::db::community::owed_retractions(&cid).unwrap_or_default() {
        let Some(ch) = community.channels.iter().find(|c| crate::simd::hex::bytes_to_hex_32(&c.id.0) == chan) else {
            let _ = crate::db::community::settle_retraction(&cid, &chan, since, generation);
            continue;
        };
        // One failed read means the network is down: the rest waits for the next pass.
        if super::service::retract_since(transport, &community, ch, since, handler).await.is_err() {
            break;
        }
        let _ = crate::db::community::settle_retraction(&cid, &chan, since, generation);
        let (after, channel) = (community.clone(), ch.id);
        crate::db::spawn_bound(async move {
            let Some(me) = crate::state::my_public_key() else { return };
            let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
            let since = since.saturating_sub(60_000) / 1000;
            let settled = |wraps: &[nostr_sdk::prelude::EventId]| {
                let hex: Vec<String> = wraps.iter().map(|w| w.to_hex()).collect();
                let settled = crate::db::events::community_wraps_settled(&hex);
                wraps.iter().zip(&hex).filter(|(_, h)| settled.contains(*h)).map(|(w, _)| *w).collect()
            };
            if let Ok(page) = super::service::fetch_channel_history(&transport, &after, &channel, 200, 3, Some(since), None, crate::community::transport::Evidence::Quorum, |_, _| true, settled).await {
                crate::VectorCore::v2_ingest_chat_page(&crate::simd::hex::bytes_to_hex_32(&channel.0), me, crate::db::current_session(), page).await;
            }
        });
    }
}

/// How long after a Channel's epoch moves the epoch it left is read once more.
const MOVED_TAIL_SECS: u64 = 8;

/// Each Channel left the epoch beside it for a later one just now. A member who has not yet taken
/// the new one goes on posting at the old for a moment, where nobody who moved is listening any
/// more: read from that epoch up again once they have had time to, so what they said there is
/// not lost. One after another: a Refounding moves every Channel at once.
pub(crate) fn reread_tails(id: CommunityId, left: Vec<(crate::community::ChannelId, Epoch)>) {
    // Nothing to read with: a rotation minted where no client is connected.
    if left.is_empty() || crate::state::nostr_client().is_none() {
        return;
    }
    let moved_at = crate::clock::now_secs();
    crate::db::spawn_bound(async move {
        crate::rt::time::sleep(std::time::Duration::from_secs(MOVED_TAIL_SECS)).await;
        let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
        let since = Some(moved_at.saturating_sub(60));
        let settled = |wraps: &[nostr_sdk::prelude::EventId]| {
            let hex: Vec<String> = wraps.iter().map(|w| w.to_hex()).collect();
            let settled = crate::db::events::community_wraps_settled(&hex);
            wraps.iter().zip(&hex).filter(|(_, h)| settled.contains(*h)).map(|(w, _)| *w).collect()
        };
        for (channel, from) in left {
            if !crate::db::current_session().is_live() {
                return;
            }
            let (Some(me), Ok(Some(community))) = (crate::state::my_public_key(), crate::db::community::load_community_v2(&id)) else { return };
            let read = super::service::fetch_channel_history_since_epoch(&transport, &community, &channel, 200, 2, since, None, crate::community::transport::Evidence::Quorum, |_, _, _| true, settled, Some((from, since)), &[]).await;
            if let Ok((page, ..)) = read {
                crate::VectorCore::v2_ingest_chat_page(&crate::simd::hex::bytes_to_hex_32(&channel.0), me, crate::db::current_session(), page).await;
            }
        }
    });
}

/// Read again each Channel whose live epoch moved, or whose published history grew, since `before`:
/// the live subscription carries only what arrives next, and what those planes hold is history.
fn reread_moved_channels(before: &CommunityV2) {
    let Ok(Some(after)) = crate::db::community::load_community_v2(before.id()) else { return };
    let moved: Vec<String> = after
        .channels
        .iter()
        .filter(|ch| !(ch.private && ch.key.is_none()))
        .filter(|ch| {
            before.channel(&ch.id).is_none_or(|was| {
                let held: HashSet<PublicKey> = was.published_history().into_iter().map(|(_, g)| g.pk()).collect();
                before.channel_secret(was).1 != after.channel_secret(ch).1 || ch.published_history().iter().any(|(_, g)| !held.contains(&g.pk()))
            })
        })
        .map(|ch| crate::simd::hex::bytes_to_hex_32(&ch.id.0))
        .collect();
    if moved.is_empty() {
        return;
    }
    let id = *after.id();
    // Only a Channel read before and still read now has an epoch it left behind.
    let readable = |ch: &super::community::ChannelV2| !(ch.private && ch.key.is_none());
    let left = after
        .channels
        .iter()
        .filter(|ch| readable(ch))
        .filter_map(|ch| before.channel(&ch.id).filter(|was| readable(was)).map(|was| (ch.id, before.channel_secret(was).1, after.channel_secret(ch).1)))
        .filter(|(_, left, now)| left != now)
        .map(|(channel, left, _)| (channel, left))
        .collect();
    reread_tails(id, left);
    crate::db::spawn_bound(async move {
        for channel in moved {
            if !crate::db::current_session().is_live() {
                return;
            }
            crate::VectorCore::v2_backfill_channel(&id, &channel, 50, 8, None, None, crate::community::transport::Evidence::Fast, 12).await;
        }
    });
}

/// One community's plane addresses: the subscription's author set and the dispatch routes are
/// both built from this, so what is subscribed and what is recognized can't drift.
fn community_addresses(c: &CommunityV2) -> Vec<PublicKey> {
    let mut out = vec![
        derive::guestbook_group_key(&c.community_root, c.id(), c.root_epoch).pk(),
        control_author(c),
        // The dissolved plane (CORD-02 ยง9) โ€” so a mid-session dissolution seals live.
        super::derive::dissolved_group_key(c.id()).pk(),
    ];
    for ch in &c.channels {
        // A KEYLESS private channel has no readable chat plane โ€” channel_secret's
        // root fallback would subscribe the PUBLIC plane for it. Its rekey plane
        // (below) is still watched, which is how its key arrives.
        if ch.private && ch.key.is_none() {
            continue;
        }
        let (secret, epoch) = c.channel_secret(ch);
        // A Locked Channel takes nothing new at its read address: nobody listens there.
        if !ch.locked() {
            out.push(derive::channel_group_key(&secret, &ch.id, epoch).pk());
        }
        if let Some(pk) = ch.writers.as_ref().and_then(|l| l.current_writer()).and_then(|(_, pk)| PublicKey::from_slice(&pk).ok()) {
            out.push(pk);
        }
        out.extend(just_left_writer(ch));
    }
    out.extend(rekey_authors(c));
    out
}

/// The live subscription split by relay: each relay is asked only for the planes of
/// the communities that list it, so the pool stores no relay's copy of everyone's.
struct SubPlan {
    /// Every plane address, sorted and deduped โ€” [`plane_authors`], the pool-wide filter.
    authors: Vec<PublicKey>,
    /// Each community relay's share, sorted and deduped.
    per_relay: BTreeMap<RelayUrl, Vec<PublicKey>>,
}

fn sort_dedup(pks: &mut Vec<PublicKey>) {
    pks.sort_unstable_by_key(|p| p.to_bytes());
    pks.dedup();
}

/// Where a community is listened for: its relays, then any it dropped within the grace a member
/// who hasn't folded the move yet still writes to.
fn listen_relays(c: &CommunityV2) -> Vec<String> {
    let mut out = c.relays.clone();
    out.extend(super::service::retired_relays(&crate::simd::hex::bytes_to_hex_32(&c.id().0)));
    out
}

fn subscription_plan(communities: &[CommunityV2]) -> SubPlan {
    let mut authors = Vec::new();
    let mut per_relay: BTreeMap<RelayUrl, Vec<PublicKey>> = BTreeMap::new();
    let mut unplaced = Vec::new();
    for c in communities {
        let addresses = community_addresses(c);
        let mut placed = false;
        for r in &listen_relays(c) {
            // Keyed by the parsed url: two spellings of one relay must merge, not overwrite.
            let Ok(url) = RelayUrl::parse(r) else { continue };
            per_relay.entry(url).or_default().extend_from_slice(&addresses);
            placed = true;
        }
        if !placed {
            unplaced.extend_from_slice(&addresses);
        }
        authors.extend(addresses);
    }
    // A community with no usable relay is asked of every relay rather than of none.
    if !unplaced.is_empty() {
        for share in per_relay.values_mut() {
            share.extend_from_slice(&unplaced);
        }
    }
    per_relay.values_mut().for_each(sort_dedup);
    sort_dedup(&mut authors);
    SubPlan { authors, per_relay }
}

/// Keyed per process, so no community's chosen addresses can steer a collision.
fn plan_fingerprint(plan: &SubPlan) -> u64 {
    use std::hash::{BuildHasher, Hash, Hasher};
    static KEYS: LazyLock<std::collections::hash_map::RandomState> = LazyLock::new(Default::default);
    let mut h = KEYS.build_hasher();
    plan.authors.len().hash(&mut h);
    for pk in &plan.authors {
        h.write(pk.as_bytes());
    }
    for (url, share) in &plan.per_relay {
        url.as_str().hash(&mut h);
        share.len().hash(&mut h);
        for pk in share {
            h.write(pk.as_bytes());
        }
    }
    h.finish()
}

fn live_filter(authors: impl IntoIterator<Item = PublicKey>, since: Timestamp) -> Filter {
    Filter::new()
        .kinds([Kind::Custom(stream::KIND_WRAP), Kind::Custom(stream::KIND_WRAP_EPHEMERAL)])
        .authors(authors)
        .since(since)
        // limit(0) suppresses the stored dump at REQ time, but a relay that
        // ACCEPTS a backfilled old event later pushes it to matching live subs
        // regardless โ€” the `since` floor excludes those at the relay.
        .limit(0)
}

fn live_since() -> Timestamp {
    Timestamp::from_secs(crate::clock::timestamp().as_secs().saturating_sub(crate::community::REALTIME_FRESH_WINDOW_MS / 1000))
}

/// This community's Control Plane address at the current root epoch โ€” the single
/// source of truth shared by [`plane_authors`] (subscribe) and
/// [`inbound::dispatch_wrap`] (recognize) so the two can't drift.
pub(crate) fn control_author(c: &CommunityV2) -> PublicKey {
    // A split epoch's address is the HELD control_pk (CORD-02 ยง5); a legacy
    // epoch derives it from the community_root as always.
    super::control::ControlPlane::of(c).pk()
}

/// The next-epoch rekey plane addresses for a community: the base rotation
/// (`root_epoch + 1`) and each Private channel's rotation (`channel epoch + 1`),
/// both under the CURRENT community_root. This is the single source of truth for
/// which rekey wraps we subscribe AND recognize (`inbound::dispatch_wrap` calls
/// it), so the two can never drift. A Public channel has no independent rotation
/// (it rides the base), so only Private channels contribute a channel address.
pub(crate) fn rekey_authors(c: &CommunityV2) -> Vec<PublicKey> {
    // saturating: a bundle's epoch isn't covered by the community_id commitment, so
    // it's attacker-influenced โ€” never let `epoch + 1` overflow (a u64::MAX epoch
    // just yields a dead address, never a panic).
    let mut out = vec![derive::base_rekey_group_key(&c.community_root, c.id(), Epoch(c.root_epoch.0.saturating_add(1))).pk()];
    for ch in &c.channels {
        if ch.private {
            out.push(derive::channel_rekey_group_key(&c.community_root, &ch.id, Epoch(ch.epoch.0.saturating_add(1))).pk());
        }
    }
    out
}

/// Load every locally-held, LIVE **v2** community (dispatching each id by its
/// stored protocol). The realtime layer folds these into the subscription +
/// routing, so excluding a DISSOLVED community here is what enforces CORD-02 ยง9
/// on the receive side: its chat/control/rekey planes stop being subscribed and
/// an arriving wrap for it is `NotOurs` (dropped, never honored). Held keys still
/// open old history through the explicit read paths โ€” this only stops NEW events.
pub fn load_held_v2() -> Vec<CommunityV2> {
    let ids = crate::db::community::list_community_ids().unwrap_or_default();
    ids.iter()
        .filter(|id| crate::db::community::community_held(id).unwrap_or(false))
        .filter(|id| !crate::db::community::get_community_dissolved(&crate::simd::hex::bytes_to_hex_32(&id.0)).unwrap_or(false))
        .filter_map(|id| crate::db::community::load_community_v2(id).ok().flatten())
        .collect()
}

/// Communities a dissolution has sealed. Excluded from [`load_held_v2`] because
/// nothing about them is live any more, but their chat rows still need the seal.
pub fn load_dissolved_v2() -> Vec<CommunityV2> {
    let ids = crate::db::community::list_community_ids().unwrap_or_default();
    ids.iter()
        .filter(|id| crate::db::community::community_held(id).unwrap_or(false))
        .filter(|id| crate::db::community::get_community_dissolved(&crate::simd::hex::bytes_to_hex_32(&id.0)).unwrap_or(false))
        .filter_map(|id| crate::db::community::load_community_v2(id).ok().flatten())
        .collect()
}

/// Carry a dissolution onto the community's chat rows. The fold flags the
/// community row, but the chats the app boots from are rows of their own, and the
/// boot re-stamp walks only held communities: without this a dissolved community
/// reloads unsealed, its composer open and its end marker gone.
async fn stamp_dissolved_chats(id: &CommunityId) {
    if let Ok(Some(c)) = crate::db::community::load_community_v2(id) {
        crate::register_v2_chats_inner(&c).await;
    }
}

/// Session-scoped cache over [`load_held_v2`] for the dispatch hot path: dispatch runs per
/// arriving wrap (typing indicators included), and a fresh load vault-decrypts EVERY community
/// row. Every writer of what a load reads moves `generation` once its write has committed, naming
/// the community it wrote, and a snapshot serves only the generation it was loaded under, so a
/// load overlapping a write is never served past it. The next load reads again only the rows
/// written since. The TTL only backstops a writer outside `db::community`.
#[derive(Default)]
struct HeldV2Cache {
    generation: u64,
    /// Communities written since the snapshot, each with the generation of its latest write.
    written: HashMap<[u8; 32], u64>,
    /// The generation of the latest write that named no community: the next load reads every row.
    whole: Option<u64>,
    snapshot: Option<(web_time::Instant, u64, Arc<HeldV2>)>,
}
fn held_v2_cache() -> Arc<std::sync::Mutex<HeldV2Cache>> {
    struct Key;
    crate::db::current_session().scoped::<Key, std::sync::Mutex<HeldV2Cache>>()
}

/// The held communities, and which of them each plane address belongs to: a wrap's author is
/// its plane's address, so it routes straight to its community instead of being tried against
/// every one held.
pub struct HeldV2 {
    communities: Box<[CommunityV2]>,
    /// Built on the first route, from the same snapshot, so it can't disagree with it.
    routes: std::sync::OnceLock<HashMap<[u8; 32], usize>>,
}

impl HeldV2 {
    pub fn communities(&self) -> &[CommunityV2] {
        &self.communities
    }

    /// The held community whose plane `author` addresses.
    pub fn route(&self, author: &PublicKey) -> Option<&CommunityV2> {
        let routes = self.routes.get_or_init(|| {
            let mut map = HashMap::new();
            for (i, c) in self.communities.iter().enumerate() {
                for pk in community_addresses(c) {
                    map.entry(pk.to_bytes()).or_insert(i);
                }
            }
            map
        });
        routes.get(&author.to_bytes()).map(|&i| &self.communities[i])
    }
}

#[cfg(feature = "bench")]
impl HeldV2 {
    pub fn for_bench(communities: Vec<CommunityV2>) -> Self {
        HeldV2 { communities: communities.into_boxed_slice(), routes: std::sync::OnceLock::new() }
    }
}

#[cfg(feature = "bench")]
pub fn bench_cache_age_secs() -> u64 {
    held_v2_cache().lock().unwrap().snapshot.as_ref().map_or(u64::MAX, |(at, ..)| at.elapsed().as_secs())
}

#[cfg(feature = "bench")]
pub fn bench_addresses(c: &CommunityV2) -> usize {
    community_addresses(c).len()
}

/// One held community as [`load_held_v2`] reads it: `None` when it is gone or dissolved.
fn load_held_one(id: &CommunityId) -> Result<Option<CommunityV2>, String> {
    if crate::db::community::get_community_dissolved(&crate::simd::hex::bytes_to_hex_32(&id.0))? {
        return Ok(None);
    }
    crate::db::community::load_community_v2(id)
}

pub fn load_held_v2_cached() -> Arc<HeldV2> {
    let cache = held_v2_cache();
    let load = {
        let held = cache.lock().unwrap_or_else(|e| e.into_inner());
        match &held.snapshot {
            // Marks left at the snapshot's own generation are rows it failed to read: read them again.
            Some((at, loaded_under, snapshot)) if *loaded_under == held.generation && held.written.is_empty() && at.elapsed() < HELD_TTL => return Arc::clone(snapshot),
            Some((at, _, snapshot)) if held.whole.is_none() && at.elapsed() < HELD_TTL => HeldLoad {
                generation: held.generation,
                written: held.written.clone(),
                whole: None,
                previous: Some((*at, Arc::clone(snapshot))),
                unread: Vec::new(),
            },
            _ => HeldLoad { generation: held.generation, written: HashMap::new(), whole: held.whole, previous: None, unread: Vec::new() },
        }
    };
    let mut load = load;
    let communities: Vec<CommunityV2> = match &load.previous {
        // Only the rows written since are read again; the rest stand as they were loaded. A row
        // that fails to read keeps the copy loaded before and is read again next time.
        Some((_, previous)) => match crate::db::community::list_community_ids() {
            Ok(ids) => ids
                .iter()
                .filter_map(|id| {
                    let kept = previous.communities.iter().find(|c| c.id() == id);
                    match kept {
                        Some(kept) if !load.written.contains_key(&id.0) => Some(kept.clone()),
                        _ => load_held_one(id).unwrap_or_else(|_| {
                            load.unread.push(id.0);
                            kept.cloned()
                        }),
                    }
                })
                .collect(),
            Err(_) => return Arc::clone(previous),
        },
        None => load_held_v2(),
    };
    let fresh = Arc::new(HeldV2 { communities: communities.into_boxed_slice(), routes: std::sync::OnceLock::new() });
    load.settle(&mut cache.lock().unwrap_or_else(|e| e.into_inner()), Arc::clone(&fresh), web_time::Instant::now());
    fresh
}

/// The backstop for a writer outside `db::community`: a snapshot this old is read whole again.
const HELD_TTL: std::time::Duration = std::time::Duration::from_secs(30);

/// What one load of the held set captured before it read.
struct HeldLoad {
    generation: u64,
    written: HashMap<[u8; 32], u64>,
    whole: Option<u64>,
    /// For a load of only the rows written since: when the snapshot it builds on was read whole.
    previous: Option<(web_time::Instant, Arc<HeldV2>)>,
    /// Rows it failed to read.
    unread: Vec<[u8; 32]>,
}

impl HeldLoad {
    fn settle(self, held: &mut HeldV2Cache, fresh: Arc<HeldV2>, now: web_time::Instant) {
        // A write that landed during the load keeps its mark for the next one.
        for (id, at) in &self.written {
            if held.written.get(id) == Some(at) && !self.unread.contains(id) {
                held.written.remove(id);
            }
        }
        if self.previous.is_none() {
            held.written.retain(|_, at| *at > self.generation);
            if held.whole == self.whole {
                held.whole = None;
            }
        }
        // A loader that captured an older generation finishing after a newer one keeps its result
        // to itself: installed, it would stand as current over what the newer one read.
        if held.snapshot.as_ref().is_none_or(|(_, under, _)| *under <= self.generation) {
            let read_whole_at = self.previous.map_or(now, |(at, _)| at);
            held.snapshot = Some((read_whole_at, self.generation, fresh));
        }
    }
}

/// Retire the held-communities snapshot. Call after ANY committed write that changes what
/// [`load_held_v2`] returns; when the write is one community's, [`invalidate_held_v2_community`]
/// lets the next load read that row alone.
pub fn invalidate_held_v2_cache() {
    let cache = held_v2_cache();
    let mut held = cache.lock().unwrap_or_else(|e| e.into_inner());
    held.generation += 1;
    held.whole = Some(held.generation);
}

/// [`invalidate_held_v2_cache`] for a committed write to the community `community_id` (hex).
pub fn invalidate_held_v2_community(community_id: &str) {
    let Some(id) = crate::community::id32_from_hex(community_id) else {
        return invalidate_held_v2_cache();
    };
    let cache = held_v2_cache();
    let mut held = cache.lock().unwrap_or_else(|e| e.into_inner());
    held.generation += 1;
    let at = held.generation;
    held.written.insert(id, at);
}

/// Refresh the v2 subscription for the held communities: register
/// `{kinds:[1059,21059], authors:[โ€ฆ]}` on their relays (targeted + pool-wide).
/// Idempotent on an unchanged author-set.
/// Re-subscribe unconditionally, even if the author set is unchanged.
///
/// `refresh_subscription` short-circuits when the set has not moved, on the
/// assumption that the pool re-applies live subs across reconnects. That holds for
/// a relay that DISCONNECTS. It does not hold for one that silently drops a REQ
/// under load โ€” the boot sweep floods every relay for ~50s, and a relay that sheds
/// our subscription there never reconnects, so nothing re-applies it while our own
/// state still says it is live. The result is a client that looks subscribed and
/// hears nothing until the author set happens to change.
///
/// So the post-sweep re-assert forgets the ids first: the next refresh cannot take
/// the fast path and genuinely re-subscribes.
pub async fn force_refresh_subscription(client: &Client) {
    crate::log_info!("[v2-sub] force re-assert begin");
    {
        let mut sub_guard = V2_SUB_ID.lock().await;
        if let Some(old) = sub_guard.take() {
            crate::live_subs::forget(&old);
            let _ = client.unsubscribe(&old).await;
            retire_subscription(old);
        }
        let mut pw = V2_POOLWIDE_SUB_ID.lock().await;
        if let Some(old) = pw.take() {
            crate::live_subs::forget(&old);
            let _ = client.unsubscribe(&old).await;
            retire_subscription(old);
        }
        // Clearing the remembered plan too, so the equality check cannot match.
        *V2_SUB_FP.lock().await = None;
    }
    refresh_subscription(client).await;
}

pub async fn refresh_subscription(client: &Client) {
    // Phase 1, LOCK-FREE: make sure the community relays are added + connected โ€”
    // the slow part (a connect wait of up to ~6s). Holding the sub locks across
    // this stalled every concurrent dispatch/refresh behind one caller's connect.
    {
        let communities = load_held_v2();
        let mut relays: Vec<String> = communities.iter().flat_map(listen_relays).collect();
        relays.sort();
        relays.dedup();
        if !relays.is_empty() {
            // Community relays ride GOSSIP|PING (warm but excluded from pool-wide DM ops).
            for r in &relays {
                let _ = client.add_managed_relay(r.as_str()).capabilities(crate::community_relay_capabilities()).await;
            }
            client.connect().await;
            // Wait briefly for at least one relay to actually connect (a subscribe
            // against a still-connecting relay silently fails to register).
            let wanted: Vec<RelayUrl> = relays.iter().filter_map(|r| RelayUrl::parse(r).ok()).collect();
            let wait_t = web_time::Instant::now();
            // 6 s on clearnet, the connect floor over Tor (a circuit build alone outlasts 6 s).
            let polls = crate::relay_connect_timeout(std::time::Duration::from_secs(6)).as_millis() / 250;
            for _ in 0..polls {
                let pool = client.relays().all().await;
                if wanted.iter().any(|u| pool.get(u).map(|r| r.status() == RelayStatus::Connected).unwrap_or(false)) {
                    break;
                }
                crate::rt::time::sleep(std::time::Duration::from_millis(250)).await;
            }
            {
                let pool = client.relays().all().await;
                let up: Vec<String> = wanted.iter()
                    .filter(|u| pool.get(u).map(|r| r.status() == RelayStatus::Connected).unwrap_or(false))
                    .map(|u| u.to_string()).collect();
                crate::log_info!("[v2-sub] connect-wait {:?}: {}/{} wanted relays up: {:?}", wait_t.elapsed(), up.len(), wanted.len(), up);
            }
            // Register every held plane's key BEFORE subscribing, so the responder
            // can answer any NIP-42 challenge our REQs trigger. Cheap + local.
            for c in &communities {
                super::streamauth::register_community(c);
            }
        }
    }

    // Phase 2, LOCKED + bounded (no connect waits): RE-snapshot the held state
    // INSIDE the sub locks โ€” the follow worker runs concurrently and may have just
    // adopted a rotation, so the LAST locker must read the freshest persisted
    // authors. An out-of-lock read lets a stale caller commit an old author-set
    // over a fresh one and silently mute a rotated community. (A community whose
    // relays appeared between the phases subscribes now and connects on the next
    // refresh โ€” the follow that discovers it always triggers one.)
    let mut sub_guard = V2_SUB_ID.lock().await;
    let mut fp_guard = V2_SUB_FP.lock().await;

    let communities = load_held_v2();
    let plan = subscription_plan(&communities);
    let mut relays: Vec<String> = communities.iter().flat_map(listen_relays).collect();
    relays.sort();
    relays.dedup();

    let fingerprint = plan_fingerprint(&plan);

    // Unchanged-plan fast path โ€” but only when BOTH subs actually registered (a
    // failed pool-wide subscribe would otherwise stay absent until the author-set
    // changes, and Android streams via the pool-wide path).
    if sub_guard.is_some() && *fp_guard == Some(fingerprint) && (plan.authors.is_empty() || V2_POOLWIDE_SUB_ID.lock().await.is_some()) {
        mark_subscription_ready(); // an unchanged live sub is a completed pass
        return; // the pool re-applies the live subs across reconnects.
    }
    // The old subscriptions close only once the new ones stand: a relay sends a fresh REQ only what
    // arrives after it, so closing first drops whatever is published in between.
    let old_targeted = sub_guard.take();
    *fp_guard = Some(fingerprint);

    if plan.authors.is_empty() {
        if let Some(old) = old_targeted {
            crate::live_subs::forget(&old);
            let _ = client.unsubscribe(&old).await;
            retire_subscription(old);
        }
        if let Some(old_pw) = V2_POOLWIDE_SUB_ID.lock().await.take() {
            crate::live_subs::forget(&old_pw);
            let _ = client.unsubscribe(&old_pw).await;
            retire_subscription(old_pw);
        }
        // Completed with nothing to hear: READY with zero planes, which is a
        // different observable state from "still connecting".
        mark_subscription_ready();
        return;
    }

    let since = live_since();
    let SubPlan { authors, per_relay } = plan;

    let mut retired: Vec<SubscriptionId> = old_targeted.into_iter().collect();
    {
        let mut pw = V2_POOLWIDE_SUB_ID.lock().await;
        retired.extend(pw.take());
        let filter = live_filter(authors, since);
        match client.subscribe(filter.clone()).await {
            Ok(out) => {
                crate::live_subs::keep_output(&out, vec![filter]);
                crate::log_info!(
                    "[v2-sub] poolwide {}: ok {:?} failed {:?}",
                    *out,
                    out.success.keys().map(|r| r.to_string()).collect::<Vec<_>>(),
                    out.failed.iter().map(|(r, e)| format!("{r}: {e:?}")).collect::<Vec<_>>()
                );
                note_live_subscription(&out.value);
                *pw = Some(out.value);
            }
            Err(e) => crate::log_warn!("[v2-sub] poolwide subscribe FAILED: {e}"),
        }
    }
    let targeted: std::collections::HashMap<RelayUrl, Vec<Filter>> =
        per_relay.into_iter().map(|(url, share)| (url, vec![live_filter(share, since)])).collect();
    match client.subscribe(nostr_sdk::prelude::ReqTarget::manual(targeted.clone())).await {
        Ok(out) => {
            crate::live_subs::keep(&out.value, targeted);
            crate::log_info!(
                "[v2-sub] targeted {}: ok {:?} failed {:?}",
                *out,
                out.success.keys().map(|r| r.to_string()).collect::<Vec<_>>(),
                out.failed.iter().map(|(r, e)| format!("{r}: {e:?}")).collect::<Vec<_>>()
            );
            note_live_subscription(&out.value);
            *sub_guard = Some(out.value);
        }
        Err(e) => crate::log_warn!("[v2-sub] targeted subscribe FAILED: {e}"),
    }
    for old in retired {
        crate::live_subs::forget(&old);
        let _ = client.unsubscribe(&old).await;
        retire_subscription(old);
    }
    mark_subscription_ready();
    // However the swap went, what was published while it ran is read once more: a relay may push
    // it down neither subscription, and a listener held up meanwhile loses it to the ring.
    let swapped_at = crate::clock::now_ms();
    crate::db::spawn_bound(async move {
        crate::rt::time::sleep(std::time::Duration::from_millis(SWAP_REPLAY_DELAY_MS)).await;
        crate::VectorCore::owe_live_replay(swapped_at.saturating_sub(SWAP_REPLAY_BACK_MS));
    });
    drop(fp_guard);
    drop(sub_guard);

    // AUTH-gating relays serve the planes only to a stream-authenticated
    // connection, and a live subscription isn't auto-retried after the gate. The
    // priming used to run BEFORE the subscribe, which gated the whole registration
    // on the slowest relay: a set with dead or auth-refusing members left the
    // client deaf for a minute while healthy relays sat idle. Prime in the
    // BACKGROUND instead โ€” healthy relays stream from the registration above, and
    // each gating relay's auth completion re-sends the subs (`resubscribe_relay`
    // via the responder), so it joins the moment IT is ready, gating nobody else.
    prime_auth_in_background(client, relays);
}

/// In-flight coalescer for the background auth prime: boot fires many refreshes
/// (dispatch, absorb, reconnect) and each spawning its own prime would stampede
/// the gating relays with duplicate auth fetches.
static PRIME_IN_FLIGHT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);

fn prime_auth_in_background(client: &Client, relays: Vec<String>) {
    use std::sync::atomic::Ordering;
    if relays.is_empty() || PRIME_IN_FLIGHT.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire).is_err() {
        return;
    }
    let client = client.clone();
    crate::db::spawn_bound(async move {
        super::streamauth::prime_auth(&client, &relays).await;
        PRIME_IN_FLIGHT.store(false, Ordering::Release);
    });
}

/// Fetch what the held planes carried since `since` and dispatch it as if it had arrived live:
/// an event published while a subscription was down or being made reaches the handler all the
/// same, and one already held is dropped as a duplicate. Each relay its own share, paged down to
/// `since`; `only` keeps to one relay.
pub(crate) async fn replay(client: &Client, since: Timestamp, only: Option<&str>, handler: Arc<dyn InboundEventHandler>) {
    const PAGE: usize = 500;
    const MAX_PAGES: usize = 20;
    let SubPlan { per_relay, .. } = subscription_plan(&load_held_v2());
    let budget = crate::relay_request_timeout(std::time::Duration::from_secs(10));
    for (url, share) in per_relay.into_iter().filter(|(url, _)| only.is_none_or(|o| url.as_str().trim_end_matches('/') == o.trim_end_matches('/'))) {
        let mut got: Vec<Event> = Vec::new();
        let mut ids = HashSet::new();
        let mut until: Option<Timestamp> = None;
        for _ in 0..MAX_PAGES {
            let mut filter = Filter::new().kinds([Kind::Custom(stream::KIND_WRAP)]).authors(share.clone()).since(since).limit(PAGE);
            if let Some(until) = until {
                filter = filter.until(until);
            }
            let page = match client.fetch_events(nostr_sdk::prelude::ReqTarget::single(url.clone(), [filter])).timeout(budget).await {
                Ok(page) => page,
                Err(e) => {
                    crate::log_debug!("[v2-sub] replay of {url} since {} failed: {e}", since.as_secs());
                    break;
                }
            };
            let mut new = 0;
            for e in page.into_iter() {
                until = Some(until.map_or(e.created_at, |u| u.min(e.created_at)));
                if ids.insert(e.id) {
                    got.push(e);
                    new += 1;
                }
            }
            // Short of a page, or nothing older left: what the relay holds since `since` is in.
            if new == 0 || until.is_none_or(|u| u <= since) {
                break;
            }
        }
        // Oldest first, so a reaction or edit follows the message it names.
        got.sort_by_key(|e| e.created_at);
        crate::log_debug!("[v2-sub] replay of {url} since {}: {} event(s)", since.as_secs(), got.len());
        for event in got {
            dispatch_event(event, handler.clone()).await;
        }
    }
}

/// Re-send the CURRENT v2 subscriptions (same ids) to ONE relay. An AUTH-gating
/// relay CLOSEs a sub REQ that raced ahead of the stream AUTHs on a fresh
/// connection, and it never re-challenges once the connection is authenticated โ€”
/// so the moment the streams finish authenticating is exactly when the subs must
/// be re-sent. nostr-sdk re-sends them only when ITS OWN auth completes (it
/// can't see ours), which usually wins by socket ordering; this makes the heal
/// deterministic and independent of that internal. Same-id REQs are idempotent.
/// The targeted id carries this relay's share only; one no held community lists
/// gets none.
pub(crate) async fn resubscribe_relay(client: &Client, relay: &RelayUrl) {
    note_resubscribe();
    // What the relay carried before it let these subscriptions in reaches a listener too.
    crate::VectorCore::owe_catch_up(false, false, [(relay.to_string(), crate::clock::now_ms().saturating_sub(10 * 60_000))]);
    let targeted = V2_SUB_ID.lock().await.clone();
    let poolwide = V2_POOLWIDE_SUB_ID.lock().await.clone();
    if targeted.is_none() && poolwide.is_none() {
        return; // nothing subscribed yet โ€” the first refresh registers on an authed socket.
    }
    let communities = load_held_v2();
    let SubPlan { authors, mut per_relay } = subscription_plan(&communities);
    if authors.is_empty() {
        return;
    }
    let since = live_since();
    let sends = [
        targeted.zip(per_relay.remove(relay)),
        poolwide.map(|id| (id, authors)),
    ];
    for (id, share) in sends.into_iter().flatten() {
        let _ = client
            .subscribe(nostr_sdk::prelude::ReqTarget::single(relay.clone(), [live_filter(share, since)]))
            .with_id(id)
            .await;
    }
}

/// Fold a Guestbook entry that came in live into the store, and record its wrap as read so a
/// sync never asks a relay for it. Returns whether the entry was new.
fn ingest_live(c: &CommunityV2, entry: super::guestbook::GuestbookEvent, wrap: &Event) -> bool {
    let stored = super::service::ingest_guestbook_event(c, entry, wrap.created_at.as_secs());
    if stored.is_ok() {
        super::service::hold_guestbook_wrap(c, wrap);
    }
    stored.unwrap_or(false)
}

/// Fold a live control edition without re-reading the plane. `false` when it can't (a follow
/// holds the community, or the held window can't decide it), so the caller queues the follow.
/// A change that moves planes, keys, writers or authority still queues a full pass, for the rekey
/// walk, key vends, writer keys and self-removal; the change itself is already on screen.
async fn apply_live_control(c: &CommunityV2, wrap: &Event, handler: &dyn InboundEventHandler) -> bool {
    // A queued follow means this device knows it is behind.
    if follow_pending(c.id()) {
        return false;
    }
    let lock = follow_lock(c.id());
    let Ok(_guard) = lock.try_lock() else {
        return false;
    };
    let Ok(Some(current)) = crate::db::community::load_community_v2(c.id()) else {
        return false;
    };
    let Some(follow) = super::service::follow_control_live(&current, wrap).await else {
        return false;
    };
    let community_id = crate::simd::hex::bytes_to_hex_32(&c.id().0);
    let planes = |c: &CommunityV2| {
        let mut chans: Vec<_> = c
            .channels
            .iter()
            .map(|ch| (ch.id.0, ch.private, ch.key, ch.epoch.0, ch.writers.clone(), ch.sealed.clone()))
            .collect();
        chans.sort_unstable_by_key(|ch| ch.0);
        (chans, c.relays.clone(), c.control_pk, c.control_root)
    };
    let moved_planes = follow.updated.as_ref().is_some_and(|u| planes(u) != planes(&current));
    let banned = crate::my_public_key().is_some_and(|me| crate::db::community::is_author_banned(&community_id, &me));
    if moved_planes {
        if let Some(client) = crate::state::nostr_client() {
            refresh_subscription(&client).await;
        }
    }
    if follow.updated.is_some() {
        refreshed(handler, &community_id);
    } else if follow.authority_changed {
        super::changes::notify(handler, &community_id);
    }
    if follow.authority_changed {
        note_live_authority_move(c.id());
    }
    if moved_planes || follow.authority_changed || banned {
        enqueue_follow_urgent(c.id());
    }
    true
}

/// Route an arriving v2 wrap: find the held community whose plane it opens under
/// and fire the matching handler callback (via the shared bridge). `session` gates
/// against a mid-flight account swap.
pub async fn dispatch_event(event: Event, handler: Arc<dyn InboundEventHandler>) {
    crate::db::scoped(async move {
        let Some(my_pk) = crate::my_public_key() else {
            return;
        };
        // Fire EXACTLY ONCE per wrap: the pool re-delivers the same event under both
        // subs and from every relay.
        if !seen_wraps().lock().unwrap_or_else(|e| e.into_inner()).first_sight(event.id.as_bytes()) {
            return;
        }
        // Handled in an earlier session (the Concord ledger), or a message stored under this
        // outer id before v2 kept the ledger: opening it again would find nothing new.
        let (wrap_id, wrap_at) = (event.id.to_bytes(), event.created_at.as_secs());
        let durable = event.kind.as_u16() == stream::KIND_WRAP;
        if durable
            && (crate::db::wrappers::processed_wrapper_exists(&wrap_id)
                || crate::db::events::wrapper_event_exists(&event.id.to_hex()).unwrap_or(false))
        {
            return;
        }
        // Handled for good: every later session skips it before opening it.
        let remember = || {
            if durable {
                let _ = crate::db::wrappers::save_processed_wrapper(&wrap_id, wrap_at, crate::db::wrappers::TRANSPORT_CONCORD);
            }
        };
        let held = load_held_v2_cached();
        let Some(c) = held.route(&event.pubkey) else {
            return;
        };
        {
            let wrap = &event;
            match inbound::dispatch_wrap(&event, c, &my_pk, &*handler) {
                inbound::DispatchedV2::NotOurs => return,
                // A control edition folds in place when the window it extends is in hand;
                // anything else, and every rekey wrap, goes to the follow worker, which
                // serializes control and rekey per community off this hot path.
                inbound::DispatchedV2::Control { .. } => {
                    if !apply_live_control(c, wrap, &*handler).await {
                        enqueue_follow_urgent(c.id());
                    }
                    return;
                }
                inbound::DispatchedV2::Rekey { .. } => {
                    enqueue_follow_urgent(c.id());
                    return;
                }
                inbound::DispatchedV2::Dissolved { community_id } => {
                    // Death wins (CORD-02 ยง9): seal read-only + surface the grave, ONCE
                    // (a re-wrapped tombstone with a fresh outer id must not re-fire the
                    // handler). The next load_held_v2 excludes it, so its planes also
                    // stop being subscribed + routed.
                    if crate::db::community::set_community_dissolved(&community_id).unwrap_or(false) {
                        stamp_dissolved_chats(c.id()).await;
                        dissolved(&*handler, &community_id);
                        if let Some(client) = crate::state::nostr_client() {
                            refresh_subscription(&client).await;
                        }
                    }
                    return;
                }
                // A chat event, opened but NOT yet applied: persist first (dedup by inner
                // id + the author-scoped edit/delete checks), then fire the callback from
                // the outcome. A re-wrapped duplicate (any keyholder
                // can re-seal a signed rumor into a fresh 1059), the relay echo of our
                // own send, or a forged edit/delete yields no outcome and re-fires
                // nothing.
                // Dated ahead of this device: back through here once its time comes.
                inbound::DispatchedV2::Early { at_ms } => {
                    seen_wraps().lock().unwrap_or_else(|e| e.into_inner()).forget(wrap.id.as_bytes());
                    crate::early::hold(wrap.clone(), crate::early::Via::Community, at_ms);
                    return;
                }
                inbound::DispatchedV2::Chat { channel_id, event } => {
                    if event.opened().author == my_pk {
                        let plane = crate::community::id32_from_hex(&channel_id)
                            .and_then(|ch| super::service::plane_key_of(c, &crate::community::ChannelId(ch), wrap));
                        super::service::heal_own_wrap_key(&event, wrap, plane.as_ref(), &c.relays);
                    }
                    let outcome = inbound::persist_routed_chat_event(&event, &channel_id, &c.id().0, &my_pk).await;
                    // A reaction or edit whose message hasn't arrived stays retryable.
                    if outcome.is_some() || !inbound::awaits_target(&event).await {
                        remember();
                    }
                    // "New" = first ingest, which a relay-backfill replay of a month-old event
                    // also satisfies: freshness comes from the inner send time, so stale replays
                    // persist and surface without ringing anything.
                    if let Some(outcome) = outcome {
                        inbound::notify_chat_outcome(&*handler, &channel_id, &event, outcome, true).await;
                    }
                    return;
                }
                inbound::DispatchedV2::Held { channel_id, author, at_ms, marked } => {
                    // Not held, it stays on the relay for a later read.
                    let held = crate::community::id32_from_hex(&channel_id).is_some_and(|ch| super::service::writing_hold(&c.id().0, &crate::community::ChannelId(ch), &event, &author, at_ms));
                    if !held {
                        return;
                    }
                    remember();
                    // A manager sees what was held, marked, and is never rung for it.
                    if let Some(marked) = marked {
                        if let Some(inbound::ChatPersist::New(message)) = inbound::persist_routed_chat_event(&marked, &channel_id, &c.id().0, &my_pk).await {
                            // News to a listener, as the same post judged later is; never a ring.
                            let news = crate::news::listening_since().is_some() && crate::news::is_news(message.at) && crate::news::first_telling_hex(&message.id);
                            handler.on_community_message(&channel_id, &message, news);
                        }
                    }
                    return;
                }
                inbound::DispatchedV2::Presence { event: ev, .. } => {
                    // Live membership motion: fold it into the persisted Guestbook so
                    // the memberlist stays a local read (the presence callback already
                    // fired inline), and refresh the overview when it lands.
                    let joined = match &ev.entry {
                        super::guestbook::GuestbookEntry::Join { member, .. } => Some(*member),
                        _ => None,
                    };
                    let changed = ingest_live(c, *ev, &event);
                    remember();
                    // Membership isn't a change the feed reports: joins and leaves have their own hook.
                    if changed {
                        handler.on_community_refreshed(&crate::simd::hex::bytes_to_hex_32(&c.id().0));
                        // Someone back whose Roles still open private Channels is owed their keys
                        // now, not at the next Roster change or the duty's period.
                        if joined.is_some_and(|m| super::service::holds_grant(c, &m)) {
                            super::service::access_duty_now(c.id());
                            enqueue_follow(c.id());
                        }
                    }
                    return;
                }
                inbound::DispatchedV2::Nickname(ev) | inbound::DispatchedV2::Timeout(ev) => {
                    let changed = if matches!(ev.entry, super::guestbook::GuestbookEntry::Nickname { .. }) { "community_nicknames" } else { "community_timeouts" };
                    remember();
                    if ingest_live(c, *ev, &event) {
                        let community_id = crate::simd::hex::bytes_to_hex_32(&c.id().0);
                        crate::traits::emit_event_json(changed, serde_json::json!({ "community_id": community_id }));
                        super::changes::notify_soon(handler.clone(), &community_id);
                    }
                    return;
                }
                inbound::DispatchedV2::Kick { target, event: ev } => {
                    let (actor, kick_rumor, kick_at) = match &ev.entry {
                        super::guestbook::GuestbookEntry::Kick { actor, at_ms, .. } => (Some(*actor), ev.rumor_id, *at_ms),
                        _ => (None, ev.rumor_id, crate::clock::now_ms()),
                    };
                    if !ingest_live(c, *ev, &event) {
                        return;
                    }
                    let community_id = crate::simd::hex::bytes_to_hex_32(&c.id().0);
                    // Self-removal rides the AUTHORIZED fold, never the wrap: the store takes
                    // any Kick rumor, so acting on arrival would let any member evict anyone.
                    // Fail-closed โ€” a kick our roster can't justify leaves us in place.
                    //
                    // The COALESCE verdict, not the memberlist: on a rejoin the store starts
                    // empty while the control fold has already re-derived our old ban mark, so
                    // the memberlist legitimately excludes us for the window before the
                    // Guestbook catches up. A stale Kick landing in that window would read as
                    // an authorized eviction. Coalescing asks only what our latest authorized
                    // entry is, so a fresh Join beats the old Kick and an empty store decides
                    // nothing.
                    let kicked_at = (my_pk == target).then(|| super::service::stored_kick_at(c, &my_pk)).flatten();
                    if let Some(at) = kicked_at {
                        // WARN, not info: `log_info!` is compiled out in release, and a
                        // self-eviction is exactly the destructive, hard-to-diagnose event
                        // that must leave a trace on a shipped build.
                        crate::log_warn!(
                            "[v2:teardown {}] KICK: the authorized guestbook fold rules us kicked",
                            &community_id[..8.min(community_id.len())]
                        );
                        super::service::record_eviction(c, at);
                        self_removed(&*handler, &community_id);
                    } else {
                        // Any member can store a Kick rumor: only the one the authorized fold rules by is a kick.
                        if my_pk != target && handler.wants_community_changes() && super::service::stored_kick_rumor(c, &target) == Some(kick_rumor) {
                            let change = super::changes::CommunityChange::new(
                                actor.and_then(|a| nostr_sdk::prelude::ToBech32::to_bech32(&a).ok()),
                                kick_at,
                                super::changes::ChangeKind::MemberKicked { member: nostr_sdk::prelude::ToBech32::to_bech32(&target).unwrap_or_else(|_| target.to_hex()) },
                            );
                            super::changes::notify_one(&*handler, &community_id, change);
                        }
                        refreshed(&*handler, &community_id);
                    }
                    return;
                }
                // Typing (never stored) and what the dispatcher handled inline or found to be noise.
                _ => {
                    remember();
                    return;
                }
            }
        }
    })
    .await
}

/// Whether a live follow worker is draining the queue (a `listen()` is running).
/// Headless callers use this to run a follow inline instead of enqueueing into
/// the void.
pub fn follow_worker_running() -> bool {
    V2_FOLLOW_TX.lock().unwrap().as_ref().map(|tx| !tx.is_closed()).unwrap_or(false)
}

/// Queue a follow for `id` โ€” NON-BLOCKING + coalesced. A burst (or a junk-wrap
/// flood) collapses to at most one queued + one running follow per community. A
/// no-op if no worker is running (no live `listen()`). Callers: dispatch,
/// boot/reconnect catch-up, manual sync โ€” none of them block or touch a lock for
/// longer than the enqueue.
pub fn enqueue_follow(id: &CommunityId) {
    let mut pending = V2_FOLLOW_PENDING.lock().unwrap();
    if !pending.insert(id.0) {
        return; // already queued or processing โ€” coalesce.
    }
    let closed = {
        let tx = V2_FOLLOW_TX.lock().unwrap_or_else(|e| e.into_inner());
        match tx.as_ref() {
            Some(tx) if tx.send(*id).is_ok() => false,
            // A worker that EXISTED and died leaves a closed sender. Parking
            // against it is a permanent swallow: the id stays in `pending`, so
            // every later enqueue coalesces into it and the unconditional call
            // sites โ€” including the live rotation dispatch โ€” become no-ops for
            // the rest of the session. Un-park instead, so the guarded callers
            // fall back to the inline follow.
            Some(tx) => tx.is_closed(),
            // No worker YET โ€” park. The boot sweep races the worker spawn, and
            // spawn_follow_worker drains parked ids into its fresh queue; a
            // dropped boot refold leaves an offline-rotated community wedged.
            None => false,
        }
    };
    if closed {
        pending.remove(&id.0);
    }
}

/// [`enqueue_follow`], but the worker takes this id ahead of everything already
/// queued. For the LIVE rotation path only: a control/rekey wrap just told us this
/// community moved, and the boot backlog ahead of it is dozens of network walks.
/// Promotes an id that is already queued, so coalescing can't bury the urgency.
pub fn enqueue_follow_urgent(id: &CommunityId) {
    V2_FOLLOW_URGENT.lock().unwrap_or_else(|e| e.into_inner()).insert(id.0);
    enqueue_follow(id);
}

/// Take the next id, preferring one a live rotation marked urgent.
fn pop_next_follow(queue: &mut std::collections::VecDeque<CommunityId>) -> Option<CommunityId> {
    let pos = {
        let urgent = V2_FOLLOW_URGENT.lock().unwrap_or_else(|e| e.into_inner());
        if urgent.is_empty() { None } else { queue.iter().position(|id| urgent.contains(&id.0)) }
    };
    match pos {
        Some(i) => queue.remove(i),
        None => queue.pop_front(),
    }
}

/// Spawn the single follow worker for this session. Installs the queue sender and
/// drains it, running one combined follow per community at a time. Replacing the
/// sender (a re-`listen()`) or [`clear`] (a swap) closes the old channel so the old
/// worker exits; the captured `std::sync::Arc<crate::db::Session>` also stops it. Idempotent per session.
/// Most recently active community first. Ties keep arrival order, so a batch whose
/// members have never been read (all zero) is not shuffled into an arbitrary one.
fn prioritize_by_activity(
    batch: Vec<CommunityId>,
    activity: impl Fn(&CommunityId) -> u64,
) -> Vec<CommunityId> {
    let mut keyed: Vec<(u64, CommunityId)> = batch.into_iter().map(|id| (activity(&id), id)).collect();
    // Stable: equal activity keeps the order the ids arrived in.
    keyed.sort_by_key(|k| std::cmp::Reverse(k.0));
    keyed.into_iter().map(|(_, id)| id).collect()
}

pub fn spawn_follow_worker(handler: Arc<dyn InboundEventHandler>) {
    let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<CommunityId>();
    // Re-send every pending id into the fresh queue: parked pre-worker
    // enqueues AND anything a replaced worker's dropped channel still owed.
    // Entries stay in the set โ€” the worker removes each as it starts
    // processing, preserving the coalescing invariant.
    {
        let pending = V2_FOLLOW_PENDING.lock().unwrap_or_else(|e| e.into_inner());
        for id in pending.iter() {
            let _ = tx.send(CommunityId(*id));
        }
    }
    *V2_FOLLOW_TX.lock().unwrap_or_else(|e| e.into_inner()) = Some(tx);
    let session = crate::db::current_session();
    crate::db::spawn_bound(async move {
        while let Some(first) = rx.recv().await {
            // Drain whatever else is already waiting and take the most recently
            // ACTIVE community first. Arrival order is boot order, which has nothing
            // to do with what the user is reading: a community silent for weeks was
            // ahead of the one on screen, and its walk held the queue while the
            // active one stayed on a dead epoch โ€” unreadable, and indistinguishable
            // from a strand. Coalescing already bounds this batch to one entry per
            // community.
            let mut batch = vec![first];
            while let Ok(next) = rx.try_recv() {
                batch.push(next);
            }
            if batch.len() > 1 {
                let last_msgs = crate::db::events::get_all_chats_last_messages().await.unwrap_or_default();
                // Most recent message across the community's channels.
                let activity = |cid: &CommunityId| -> u64 {
                    crate::db::community::load_community_v2(cid)
                        .ok()
                        .flatten()
                        .map(|c| {
                            c.channels
                                .iter()
                                .filter_map(|ch| {
                                    let ch_hex = crate::simd::hex::bytes_to_hex_32(&ch.id.0);
                                    last_msgs.get(&ch_hex).and_then(|v| v.first().map(|m| m.at))
                                })
                                .max()
                                .unwrap_or(0)
                        })
                        // A row that will not load sorts LAST: unknown is not urgent.
                        .unwrap_or(0)
                };
                batch = prioritize_by_activity(batch, activity);
            }
            let mut queue: std::collections::VecDeque<CommunityId> = batch.into();
            loop {
                // Absorb what arrived while the previous follow ran. Without this the
                // batch is frozen at drain time, and a rotation landing one item in
                // waits out every remaining walk before it is even looked at.
                while let Ok(next) = rx.try_recv() {
                    queue.push_back(next);
                }
                let Some(id) = pop_next_follow(&mut queue) else { break };
                // Remove from pending BEFORE running, so a trigger arriving DURING the
                // follow re-enqueues (and is processed after) rather than being lost.
                V2_FOLLOW_PENDING.lock().unwrap_or_else(|e| e.into_inner()).remove(&id.0);
                V2_FOLLOW_URGENT.lock().unwrap_or_else(|e| e.into_inner()).remove(&id.0);
                // One community's panic must not take the worker down with it: a dead
                // worker leaves a closed sender, and every live rotation dispatch after
                // that is a silent no-op for the rest of the session โ€” the whole client
                // goes deaf to rotations, which reads to everyone else as a fork.
                let one = std::panic::AssertUnwindSafe(follow_community(&session, &id, &*handler));
                if futures_util::FutureExt::catch_unwind(one).await.is_err() {
                    crate::log_warn!(
                        "[v2:follow {}] worker caught a panic; the queue stays alive",
                        &crate::simd::hex::bytes_to_hex_32(&id.0)[..8]
                    );
                }
            }
        }
    });
}

/// One combined rekey-then-control follow for a community, each pass against the
/// FRESHLY-RELOADED persisted state (never a stale clone, so the two planes can't
/// lose each other's writes). Rekey runs first: a base adopt moves the control
/// address, and a self-removal tears the community down (skipping control). No-op
/// without a live client โ€” unit tests drive `service::follow_control` /
/// `follow_rekeys` directly.
async fn follow_community(session: &std::sync::Arc<crate::db::Session>, id: &CommunityId, handler: &dyn InboundEventHandler) {
    crate::db::scoped(async move {
        let Some(client) = crate::state::nostr_client() else {
            return;
        };
        // Serialize against an inline (headless) follow of the same community โ€” the
        // queue only serializes triggers routed THROUGH it.
        let community_id = crate::simd::hex::bytes_to_hex_32(&id.0);
        // A grave has nothing left to follow, and its death was surfaced when it sealed: the
        // refresh that surfacing triggers asks for a follow, so answering it would loop.
        if crate::db::community::get_community_dissolved(&community_id).unwrap_or(false) {
            return;
        }
        // Owed rotations take this lock themselves: queued now, they run after this pass.
        if super::service::has_read_cuts(&community_id) || super::service::has_owed_settle(&community_id) {
            let owed = *id;
            crate::db::spawn_bound(async move { super::service::retry_owed_rotations(&owed).await });
        }
        let lock = follow_lock(id);
        let _guard = lock.lock().await;
        let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
        let mut laps = Laps::start();
        let moved_live = take_live_authority_move(id);
        if moved_live {
            note_roster_move(id);
            keys_first(id, &community_id, &transport, &client, session, handler).await;
            laps.mark("keys-first");
        }

        // Rekey first (fresh DB state).
        let Ok(Some(current)) = crate::db::community::load_community_v2(id) else {
            return; // community gone (left / removed).
        };
        let rekeys = super::service::follow_rekeys(&transport, &current, session).await;
        let rekeys_ok = rekeys.is_ok();
        match rekeys {
            // A tombstone surfaced during catch-up (an offline member learning of a
            // death) โ€” the flag is set; seal + surface, and stop following.
            Ok(follow) if follow.dissolved => {
                // Only the pass that learned of the death surfaces it.
                if !current.dissolved {
                    crate::log_warn!("[v2:teardown {}] DISSOLVED tombstone", &community_id[..8.min(community_id.len())]);
                    stamp_dissolved_chats(id).await;
                    dissolved(&*handler, &community_id);
                }
                return;
            }
            Ok(follow) if follow.self_removed => {
                crate::log_warn!("[v2:teardown {}] REKEY EXCLUSION: an authorized rotation left us out", &community_id[..8.min(community_id.len())]);
                // Retain the epoch keys: they open no future epoch, and dropping them
                // destroys the ability to self-delete our own past messages. Every other
                // self-removal trigger already retains; this one silently did not.
                super::service::record_eviction(&current, follow.removed_at.unwrap_or_else(super::service::now_ms));
                let _ = crate::db::community::delete_community_retain_keys(&community_id);
                refresh_subscription(&client).await;
                self_removed(&*handler, &community_id);
                return;
            }
            Ok(follow) if follow.updated.is_some() => {
                refresh_subscription(&client).await;
                refreshed(&*handler, &community_id);
                reread_moved_channels(&current);
            }
            Ok(_) => {}
            Err(e) => {
                // Surfaced, not swallowed: with EOSE-verified fetches an AUTH-gated
                // or dead rekey plane now reports here instead of masquerading as
                // "no rotation" โ€” the exact signature of an epoch wedge.
                //
                // Fall THROUGH to the control pass rather than returning. Control is
                // the authority fold; it depends on the root (unchanged by this
                // failure), not on the rekey walk. Returning here meant a base-plane
                // blip also skipped the roster refresh, so the next walk re-refused
                // for lack of authority โ€” the strand loop in a different dress.
                crate::log_warn!("[v2:follow {}] rekey follow failed (control pass still runs): {}", &community_id[..8.min(community_id.len())], e);
            }
        }

        laps.mark("rekeys");
        take_owed_keys(id, &community_id, &transport, &client, session, handler).await;
        // Control second, on the (possibly new-root) freshly-reloaded state.
        let Ok(Some(current)) = crate::db::community::load_community_v2(id) else {
            return;
        };
        let followed = super::service::follow_control(&transport, &current).await;
        laps.mark("control");
        if followed.as_ref().is_ok_and(|c| c.authority_changed) {
            note_roster_move(id);
        }
        take_owed_keys(id, &community_id, &transport, &client, session, handler).await;
        let control_ok = followed.is_ok();
        let control = match followed {
            Ok(c) => c,
            Err(e) => {
                // Never swallowed: a control failure stops the roster and the floors
                // advancing, which is exactly what freezes authority and strands this
                // client on a dead epoch. It used to vanish into a `matches!`.
                crate::log_warn!("[v2:follow {}] control follow failed: {}", &community_id[..8.min(community_id.len())], e);
                super::service::ControlFollow::default()
            }
        };
        let control_changed = control.updated.is_some();
        // What a live fold already wrote counts as this pass's own: the first walk ran on it,
        // so only the keys and duties that follow a Roster move are still owed.
        let authority_changed = control.authority_changed || moved_live;
        // The change feed hears of a fold once it is written, not after the key and history
        // reads below: a member is told of a Role before its rooms finish filling.
        if control_ok {
            super::changes::notify(&*handler, &community_id);
        }
        // The authority half is what the rekey walk gates on, and the walk ran BEFORE
        // this fold. Re-walk once, in-process, on the freshly-written state โ€” a queue
        // re-enqueue would be both slower and, on a coalesced queue, droppable.
        if control.moved() {
            if let Ok(Some(latest)) = crate::db::community::load_community_v2(id) {
                match super::service::follow_rekeys(&transport, &latest, session).await {
                    Ok(f) if f.self_removed || f.dissolved => {}
                    Ok(f) if f.updated.is_some() => {
                        refresh_subscription(&client).await;
                        refreshed(&*handler, &community_id);
                    }
                    Ok(_) => {}
                    Err(e) => crate::log_warn!(
                        "[v2:follow {}] post-authority rekey re-walk failed: {}",
                        &community_id[..8.min(community_id.len())], e
                    ),
                }
            }
        }
        laps.mark("re-walk");
        // Keys delivered on an access plane park for the vend judge just below.
        let collect = super::service::access_collect_due(id, authority_changed);
        if let Some(current) = crate::db::community::load_community_v2(id).ok().flatten().filter(|_| collect) {
            match super::service::collect_access(&transport, &current).await {
                Ok(0) => {}
                Ok(n) => crate::log_info!("[v2:follow {}] {n} key(s) waiting on access planes", &community_id[..8.min(community_id.len())]),
                Err(e) => crate::log_warn!("[v2:follow {}] access plane read failed: {e}", &community_id[..8.min(community_id.len())]),
            }
            match super::service::collect_writers(&transport, &current).await {
                Ok(0) => {}
                Ok(n) => {
                    crate::log_info!("[v2:follow {}] took {n} writer key(s)", &community_id[..8.min(community_id.len())]);
                    refresh_subscription(&client).await;
                    refreshed(&*handler, &community_id);
                }
                Err(e) => crate::log_warn!("[v2:follow {}] writer key read failed: {e}", &community_id[..8.min(community_id.len())]),
            }
        }
        laps.mark("access");
        // A holder delivers only off a pass that read both planes: a failed one may hold a key
        // its roster hasn't caught up with.
        if rekeys_ok && control_ok && super::service::access_duty_due(id, authority_changed) {
            let owed = *id;
            crate::db::spawn_bound(async move {
                // Every holder sees the same gap: a random wait lets the first delivery serve them all.
                crate::rt::time::sleep(std::time::Duration::from_millis(3_000 + rand::random::<u64>() % 12_000)).await;
                if !crate::db::current_session().is_live() {
                    return;
                }
                let Ok(Some(c)) = crate::db::community::load_community_v2(&owed) else { return };
                let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
                match super::service::access_duty(&transport, &c).await {
                    Ok(done) if done == Default::default() => {}
                    Ok(done) => crate::log_info!(
                        "[v2:access] delivered {} channel key(s), cut {} holder(s) a channel no longer lets in; writers: {} delivered, {} cut, {} ledger(s) moved",
                        done.delivered, done.cut, done.writers.delivered, done.writers.cut, done.writers.moved
                    ),
                    Err(e) => crate::log_warn!("[v2:access] access duty failed: {e}"),
                }
            });
        }
        if authority_changed {
            // Whoever made the change delivers the keys it owes moments after it, and holders a
            // few seconds after that: look again while one is still owed, and once more whatever
            // this device thinks it is owed.
            let again = *id;
            crate::db::spawn_bound(async move {
                let mut waited = 0;
                for (at, whatever) in OWED_LOOKS_SECS {
                    crate::rt::time::sleep(std::time::Duration::from_secs(at - waited)).await;
                    waited = at;
                    if !crate::db::current_session().is_live() {
                        return;
                    }
                    let owed = crate::db::community::load_community_v2(&again).ok().flatten().is_some_and(|c| super::service::owed_keys(&c));
                    if owed || whatever {
                        super::service::access_collect_now(&again);
                        enqueue_follow(&again);
                    }
                }
            });
        }
        // Re-judge parked key vends on EVERY pass, not only when the fold moved. A
        // vend that lands AFTER its Grant folded has nothing left to change the
        // control plane, so gating this on `changed` strands it until some unrelated
        // edition happens by (CORD-03 "delivered on grant").
        adopt_parked_keys(id, &community_id, &transport, &client, session, handler, authority_changed).await;
        laps.mark("keys");
        if control_changed {
            refresh_subscription(&client).await;
            refreshed(&*handler, &community_id);
            reread_moved_channels(&current);
            // A control change can reveal rekey work that predates it โ€” a just-announced
            // private channel's key crate is already sitting on its rekey plane (the key
            // ships BEFORE the vsk-2), and this pass's rekey walk ran before the channel
            // existed. Queue one more pass; it coalesces and converges (an unchanged
            // control fold doesn't re-queue).
            enqueue_follow(id);
        } else if control_ok {
            // A Roster or banlist fold leaves the document alone: the change feed still looks.
            super::changes::notify(&*handler, &community_id);
        }

        // Banned by the banlist we just folded โ†’ self-remove NOW, not when the Refounding
        // eventually lands. A Ban composes three layers (CORD-04 ยง6) and their guarantees
        // arrive at different speeds: the Banlist edition is instant, the Refounding is
        // "heavy and asynchronous" by design. Waiting on the rotation would leave the target
        // sitting in a community that already dropped them from its member count โ€” silenced,
        // still looking joined. Checked unconditionally: a banlist-only change folds no
        // document, so `follow_control` returns None for it.
        if let Some(me) = crate::my_public_key() {
            if crate::db::community::is_author_banned(&community_id, &me) {
                crate::log_warn!("[v2:teardown {}] SELF-BAN: our npub is in the folded banlist", &community_id[..8.min(community_id.len())]);
                // Dated by the banlist edition that named us, not by when we noticed it.
                let banned_at = crate::db::community::get_community_ban_marks(&community_id)
                    .ok()
                    .and_then(|marks| marks.get(&me.to_hex()).map(|s| s.saturating_mul(1000)))
                    .unwrap_or_else(super::service::now_ms);
                super::service::record_eviction(&current, banned_at.min(super::service::now_ms()));
                self_removed(&*handler, &community_id);
                return;
            }
        }

        laps.mark("notify");
        // Guestbook third: catch the membership store up from its cursor. Boot and
        // reconnect land here through this same queue, so the memberlist is a local
        // read by the time any panel asks โ€” and every join/leave the catch-up folds
        // surfaces as a presence line (real-rumor-id keyed, so a line each path also
        // saw live inserts exactly once).
        let Ok(Some(current)) = crate::db::community::load_community_v2(id) else {
            return;
        };
        if let Ok(fresh) = super::service::sync_guestbook(&transport, &current).await {
            // A Kick read on catch-up evicts as one heard live does: offline when kicked is still kicked.
            if let Some(at) = crate::state::my_public_key().and_then(|me| super::service::stored_kick_at(&current, &me)) {
                crate::log_warn!("[v2:teardown {}] KICK read on catch-up: the authorized guestbook fold rules us kicked", &community_id[..8.min(community_id.len())]);
                super::service::record_eviction(&current, at);
                self_removed(&*handler, &community_id);
                return;
            }
            // Someone back whose Roles still open private Channels is owed their keys now.
            if fresh.iter().any(|ev| matches!(&ev.entry, super::guestbook::GuestbookEntry::Join { member, .. } if super::service::holds_grant(&current, member))) {
                super::service::access_duty_now(id);
                enqueue_follow(id);
            }
            if !fresh.is_empty() {
                surface_presence(&current, &fresh, handler);
                surface_kicks(&current, &fresh, handler);
                refreshed(&*handler, &community_id);
            }
            match super::service::heal_my_join(&transport, &current).await {
                Ok(true) => refreshed(&*handler, &community_id),
                Ok(false) => {}
                Err(e) => crate::log_debug!("[v2:join {}] restore deferred: {e}", &community_id[..8.min(community_id.len())]),
            }
            match super::service::heal_ban_departures(&transport, &current).await {
                Ok(0) => {}
                Ok(n) => {
                    crate::log_info!("[v2:ban {}] wrote {n} lifted ban(s) to the Guestbook", &community_id[..8.min(community_id.len())]);
                    refreshed(&*handler, &community_id);
                }
                Err(e) => crate::log_debug!("[v2:ban {}] departures deferred: {e}", &community_id[..8.min(community_id.len())]),
            }
            if let Err(e) = super::service::carry_my_nickname(&transport, &current).await {
                crate::log_debug!("[v2:nickname {}] carry deferred: {e}", &community_id[..8.min(community_id.len())]);
            }
            // A walk longer than one pass goes on soon, not on whatever next moves the community;
            // one that failed waits for the next trigger.
            if super::service::guestbook_walk_pending(&current) {
                let id = *id;
                crate::db::spawn_bound(async move {
                    crate::rt::time::sleep(std::time::Duration::from_secs(10)).await;
                    enqueue_follow(&id);
                });
            }
        }
        // Whichever fold stored a new writer or stop entry, or found someone gone, what it undoes is taken back.
        if let Ok(Some(folded)) = crate::db::community::load_community_v2(id) {
            super::service::owe_new_departures(&folded);
        }
        settle_owed_retractions(id, &transport, handler).await;
        // What waited on a Roster, ledger or memberlist this pass may have moved is judged again.
        if let Ok(Some(folded)) = crate::db::community::load_community_v2(id) {
            let released = super::service::rejudge_held(&folded, handler).await;
            if released > 0 {
                crate::log_info!("[v2:follow {}] {released} held post(s) stand now", &community_id[..8.min(community_id.len())]);
            }
        }
        laps.mark("guestbook");
        crate::log_debug!("[v2:follow {}] pass: {laps}", &community_id[..8.min(community_id.len())]);
    })
    .await
}

/// How many newly keyed Channels read their history at once.
const KEYED_BACKFILL_CONCURRENCY: usize = 4;

/// Adopt the Private Channel keys parked for `id` that its fold now lets in, read what each
/// room held before, and tell the handler. `moved` is whether the Roster moved, which makes the
/// past epochs delivered read-only due as well. Returns how many Channels were keyed.
async fn adopt_parked_keys(
    id: &CommunityId,
    community_id: &str,
    transport: &crate::community::transport::LiveTransport,
    client: &Client,
    session: &Arc<crate::db::Session>,
    handler: &dyn InboundEventHandler,
    moved: bool,
) -> usize {
    let Ok(Some(folded)) = crate::db::community::load_community_v2(id) else { return 0 };
    let keyed = super::service::absorb_parked_channel_keys(&folded, session);
    if !keyed.is_empty() {
        crate::log_info!("[v2:follow {}] adopted {} vended private-channel key(s)", &community_id[..8.min(community_id.len())], keyed.len());
        // A newly-keyed channel adds its chat plane to the readable set, and
        // the live subscription is addressed BY that set โ€” without a rebuild
        // we hold the key and still never hear the channel. Independent of
        // `control_changed`: adopting a parked vend changes no control state.
        refresh_subscription(client).await;
    }
    // After adopting: a channel keyed just now is one whose history may be waiting.
    let reread = crate::db::community::load_community_v2(id).ok().flatten();
    let mut rooms: Vec<crate::community::ChannelId> = keyed.clone();
    if let Some(now) = reread.filter(|_| super::service::history_collect_due(id, moved || !keyed.is_empty() || owed_history(id))) {
        match super::service::collect_history_rooms(transport, &now).await {
            Ok(took) if took.is_empty() => {}
            // A past epoch taken after its room was read leaves that room to read again.
            Ok(took) => {
                crate::log_info!("[v2:follow {}] {} past epoch(s) delivered read-only", &community_id[..8.min(community_id.len())], took.iter().map(|(_, n)| n).sum::<usize>());
                rooms.extend(took.into_iter().map(|(ch, _)| ch).filter(|ch| !keyed.contains(ch)));
            }
            Err(e) => crate::log_warn!("[v2:follow {}] history read failed: {e}", &community_id[..8.min(community_id.len())]),
        }
    }
    // Read what was said while we were locked out. The live subscription
    // only carries what arrives NEXT, so without this a member granted
    // access walks into a room that looks empty. The count rides the hook:
    // backfilled history is NOT dispatched as live messages, and without
    // the number a handler cannot even tell there is history to go read.
    // A few rooms at a time: a Role that opens several fills them together.
    let rooms: Vec<String> = rooms.iter().map(|ch| crate::simd::hex::bytes_to_hex_32(&ch.0)).collect();
    for rooms in rooms.chunks(KEYED_BACKFILL_CONCURRENCY) {
        let fills = futures_util::future::join_all(rooms.iter().map(|hex| {
            crate::VectorCore::v2_backfill_channel(id, hex, 50, 2, None, None, crate::community::transport::Evidence::Fast, 12)
        }))
        .await;
        for (hex, backfilled) in rooms.iter().zip(fills) {
            handler.on_channel_keyed(community_id, hex, backfilled);
        }
    }
    keyed.len()
}

struct OwedLooks;

/// Until when (unix ms) each community's passes look for owed keys between their stages.
fn owed_looks() -> Arc<StdMutex<HashMap<[u8; 32], u64>>> {
    crate::db::current_session().scoped::<OwedLooks, _>()
}

/// How long after a Roster move a pass keeps looking between its stages.
const OWED_LOOKS_FOR_MS: u64 = 60_000;

/// Whether a Roster move is fresh enough that its past epochs may still be on their way: whoever
/// delivers a room's key sends its history just after, so one look can land between the two.
fn owed_history(id: &CommunityId) -> bool {
    owed_looks().lock().unwrap_or_else(|e| e.into_inner()).get(&id.0).is_some_and(|until| crate::clock::now_ms() < *until)
}

/// The Roster just moved: whoever it let in is delivered to over the next moments.
fn note_roster_move(id: &CommunityId) {
    owed_looks().lock().unwrap_or_else(|e| e.into_inner()).insert(id.0, crate::clock::now_ms() + OWED_LOOKS_FOR_MS);
}

/// Take whatever key the stored Roster still owes this member and someone has delivered since
/// the last look. Asked between the stages of a pass, so a key that lands while one runs does
/// not wait out the walks left in it. A member owed nothing reads no plane here.
async fn take_owed_keys(
    id: &CommunityId,
    community_id: &str,
    transport: &crate::community::transport::LiveTransport,
    client: &Client,
    session: &Arc<crate::db::Session>,
    handler: &dyn InboundEventHandler,
) {
    // Only while a Roster move is fresh: a key nobody can deliver yet is left to the clocks.
    if owed_looks().lock().unwrap_or_else(|e| e.into_inner()).get(&id.0).is_none_or(|until| crate::clock::now_ms() >= *until) {
        return;
    }
    let Ok(Some(current)) = crate::db::community::load_community_v2(id) else { return };
    let (rooms, writers) = (super::service::owed_channel_keys(&current), super::service::owed_writer_keys(&current));
    if rooms {
        if let Err(e) = super::service::collect_access(transport, &current).await {
            crate::log_warn!("[v2:follow {}] access plane read failed: {e}", &community_id[..8.min(community_id.len())]);
        }
        adopt_parked_keys(id, community_id, transport, client, session, handler, false).await;
    }
    if writers {
        match super::service::collect_writers(transport, &current).await {
            Ok(0) => {}
            Ok(n) => {
                crate::log_info!("[v2:follow {}] took {n} writer key(s)", &community_id[..8.min(community_id.len())]);
                refresh_subscription(client).await;
                refreshed(handler, community_id);
            }
            Err(e) => crate::log_warn!("[v2:follow {}] writer key read failed: {e}", &community_id[..8.min(community_id.len())]),
        }
    }
}

/// When, after a Roster move, a pass looks for keys again: `(seconds after it, whether it looks
/// even when this device counts nothing owed)`.
const OWED_LOOKS_SECS: [(u64, bool); 3] = [(3, false), (8, false), (20, true)];

/// When each look for a key is taken after the one before found none. Whoever let this member
/// in publishes the key a moment after the change that owes it.
const KEY_LOOKS_MS: [u64; 3] = [0, 400, 800];

/// A live fold just moved the Roster: before the walks, which need nothing of it and can take
/// seconds, take the keys of every Private Channel it let this member into. A member it let
/// into nothing reads no plane here.
async fn keys_first(
    id: &CommunityId,
    community_id: &str,
    transport: &crate::community::transport::LiveTransport,
    client: &Client,
    session: &Arc<crate::db::Session>,
    handler: &dyn InboundEventHandler,
) {
    for wait in KEY_LOOKS_MS {
        let Ok(Some(current)) = crate::db::community::load_community_v2(id) else { return };
        if !super::service::owed_channel_keys(&current) {
            return;
        }
        crate::rt::time::sleep(std::time::Duration::from_millis(wait)).await;
        if let Err(e) = super::service::collect_access(transport, &current).await {
            crate::log_warn!("[v2:follow {}] access plane read failed: {e}", &community_id[..8.min(community_id.len())]);
        }
        // Past epochs are read for a room keyed here; the pass reads the rest at its usual place.
        adopt_parked_keys(id, community_id, transport, client, session, handler, false).await;
    }
}

/// How long each stage of a follow pass took, for the one line a pass logs.
struct Laps {
    last: web_time::Instant,
    took: Vec<(&'static str, u128)>,
}

impl Laps {
    fn start() -> Self {
        Laps { last: web_time::Instant::now(), took: Vec::new() }
    }

    fn mark(&mut self, stage: &'static str) {
        let now = web_time::Instant::now();
        self.took.push((stage, now.duration_since(self.last).as_millis()));
        self.last = now;
    }
}

impl std::fmt::Display for Laps {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        for (i, (stage, ms)) in self.took.iter().enumerate() {
            write!(f, "{}{stage} {ms}ms", if i == 0 { "" } else { ", " })?;
        }
        Ok(())
    }
}

/// Report the authorized Kicks a catch-up folded, as one heard live is.
fn surface_kicks(community: &CommunityV2, fresh: &[super::guestbook::GuestbookEvent], handler: &dyn InboundEventHandler) {
    use nostr_sdk::prelude::ToBech32;
    if !handler.wants_community_changes() {
        return;
    }
    let me = crate::state::my_public_key();
    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
    for ev in fresh {
        let super::guestbook::GuestbookEntry::Kick { actor, target, at_ms, .. } = &ev.entry else { continue };
        if Some(*target) == me || super::service::stored_kick_rumor(community, target) != Some(ev.rumor_id) {
            continue;
        }
        let member = target.to_bech32().unwrap_or_else(|_| target.to_hex());
        let change = super::changes::CommunityChange::new(actor.to_bech32().ok(), *at_ms, super::changes::ChangeKind::MemberKicked { member });
        super::changes::notify_one(handler, &cid_hex, change);
    }
}

/// Fire the presence-line surface for freshly-folded guestbook events โ€” the
/// catch-up twin of the live dispatch (same handler, same real-id dedup key,
/// same banned-author drop). Kicks/snapshots shape the memberlist, not the feed.
fn surface_presence(
    community: &CommunityV2,
    fresh: &[super::guestbook::GuestbookEvent],
    handler: &dyn InboundEventHandler,
) {
    use super::guestbook::GuestbookEntry;
    use nostr_sdk::prelude::ToBech32;
    let Some(primary) = community.primary_channel() else {
        return;
    };
    let chat_id = crate::simd::hex::bytes_to_hex_32(&primary.id.0);
    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
    let banned = crate::db::community::banned_set(&cid_hex);
    for ev in fresh {
        let (member, joined, at_ms, invited_by) = match &ev.entry {
            GuestbookEntry::Join { member, at_ms, invited_by } => (member, true, *at_ms, invited_by.clone()),
            GuestbookEntry::Leave { member, at_ms } => (member, false, *at_ms, None),
            GuestbookEntry::Kick { .. } | GuestbookEntry::Snapshot { .. } | GuestbookEntry::Timeout { .. } | GuestbookEntry::Nickname { .. } => continue,
        };
        if banned.contains(&member.to_bytes()) {
            continue;
        }
        let Ok(npub) = member.to_bech32();
        let event_id = crate::simd::hex::bytes_to_hex_32(&ev.rumor_id);
        let (by, label) = match &invited_by {
            Some((c, l)) => (Some(c.as_str()), Some(l.as_str())),
            None => (None, None),
        };
        if crate::news::first_telling(&ev.rumor_id) {
            handler.on_community_presence(&chat_id, &npub, joined, &event_id, at_ms / 1000, by, label);
        }
    }
}

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

    fn cid(b: u8) -> CommunityId {
        CommunityId([b; 32])
    }

    #[test]
    fn a_live_authority_move_is_owed_to_exactly_one_pass() {
        let (a, b) = (cid(0xA1), cid(0xB2));
        assert!(!take_live_authority_move(&a), "nothing moved yet");
        note_live_authority_move(&a);
        note_live_authority_move(&a);
        assert!(!take_live_authority_move(&b), "another community's move is not this one's");
        assert!(take_live_authority_move(&a), "the pass a live fold queued hears of the move");
        assert!(!take_live_authority_move(&a), "and the pass after it does not");
    }

    #[test]
    fn the_follow_queue_walks_the_community_you_are_actually_reading_first() {
        // Arrival order is boot order, which says nothing about what the user has
        // open. A community silent for weeks used to sit ahead of the active one and
        // hold the queue while it stayed on a dead epoch โ€” messages unreadable, which
        // looks exactly like a strand.
        let stale = cid(1);
        let active = cid(2);
        let middling = cid(3);
        let batch = vec![stale, active, middling]; // arrival order: stale FIRST
        let out = prioritize_by_activity(batch, |c| match c.0[0] {
            1 => 1_000,          // weeks ago
            2 => 9_000_000,      // on screen right now
            3 => 500_000,
            _ => 0,
        });
        assert_eq!(
            out,
            vec![active, middling, stale],
            "the most recently active community must be followed first regardless of arrival order",
        );
    }

    #[test]
    fn an_all_silent_batch_keeps_its_arrival_order() {
        // Every candidate unread (a fresh install, or communities never opened): with
        // nothing to rank on, the order must stay the one the ids arrived in rather
        // than becoming arbitrary.
        let batch = vec![cid(7), cid(8), cid(9)];
        let out = prioritize_by_activity(batch.clone(), |_| 0);
        assert_eq!(out, batch, "equal activity is a stable sort, not a reshuffle");
    }
    use super::super::control::{genesis, CommunityMetadata};
    use crate::community::Epoch;
    use nostr_sdk::prelude::Keys;

    fn a_community(name: &str) -> CommunityV2 {
        let owner = Keys::generate();
        let g = genesis(&owner, CommunityMetadata { name: name.into(), ..Default::default() }, 1_000).unwrap();
        CommunityV2::from_genesis(&g, name, None, vec!["wss://r".into()], 0)
    }

    #[test]
    fn subscription_readiness_is_scoped_to_the_session_that_marked_it() {
        // Generation-keyed on purpose: a bare bool would survive an account swap
        // and report account A's readiness for account B โ€” the exact class of
        // per-account-global bug the swap-cache sweep exists to prevent.
        //
        // Bumping the GLOBAL generation invalidates every live std::sync::Arc<crate::db::Session>, so
        // serialize with the swap-sensitive tests via the same guard they hold.
        let _guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
        mark_subscription_ready();
        assert!(subscription_ready(), "marked for the current session");
        crate::db::close_database();
        assert!(!subscription_ready(), "an account swap invalidates it");
        mark_subscription_ready();
        assert!(subscription_ready(), "the new session's own pass re-arms it");
    }

    #[test]
    fn plane_authors_covers_the_dispatched_planes_only() {
        let c = a_community("A");
        let authors = plane_authors(std::slice::from_ref(&c));

        // Subscribed: the guestbook, the control plane, and the one public channel
        // (the planes dispatch_wrap handles). Exactly those three.
        let gb = derive::guestbook_group_key(&c.community_root, c.id(), c.root_epoch).pk();
        // The split address (the held control_pk), not the legacy derivation.
        let control = crate::community::v2::control::ControlPlane::of(&c).pk();
        assert_ne!(control, derive::control_group_key(&c.community_root, c.id(), c.root_epoch).pk());
        let general = {
            let (s, e) = c.channel_secret(&c.channels[0]);
            derive::channel_group_key(&s, &c.channels[0].id, e).pk()
        };
        // Plus the next base-rekey address (rekey-follow). A public channel has no
        // independent rotation, so #general contributes no channel-rekey address.
        let next_base = derive::base_rekey_group_key(&c.community_root, c.id(), Epoch(1)).pk();
        // Plus the dissolved plane (CORD-02 ยง9), so a live dissolution is detected.
        let dissolved = derive::dissolved_group_key(c.id()).pk();
        assert!(
            authors.contains(&gb)
                && authors.contains(&control)
                && authors.contains(&general)
                && authors.contains(&next_base)
                && authors.contains(&dissolved)
        );
        assert_eq!(authors.len(), 5, "guestbook + control + dissolved + chat + base-rekey planes are subscribed");
    }

    #[test]
    fn plane_authors_is_deterministic_deduped_and_multi_community() {
        let a = a_community("A");
        let b = a_community("B");
        let one = plane_authors(std::slice::from_ref(&a));
        // Re-running over the same community is byte-identical (deterministic).
        assert_eq!(plane_authors(std::slice::from_ref(&a)), one);
        // Two distinct communities' planes are all present, none dropped.
        let two = plane_authors(&[a.clone(), b.clone()]);
        assert_eq!(two.len(), one.len() * 2);
        // Order-independent: reversing the input yields the identical sorted set.
        assert_eq!(plane_authors(&[b, a]), two);
    }

    #[test]
    fn an_older_load_finishing_last_never_stands_over_a_newer_one() {
        let empty = || Arc::new(HeldV2 { communities: Box::new([]), routes: std::sync::OnceLock::new() });
        let load = |generation: u64, written: &[([u8; 32], u64)], previous: Option<(web_time::Instant, Arc<HeldV2>)>| HeldLoad {
            generation,
            written: written.iter().copied().collect(),
            whole: None,
            previous,
            unread: Vec::new(),
        };
        let y = [7u8; 32];
        let t0 = web_time::Instant::now();
        let mut held = HeldV2Cache { generation: 2, written: [(y, 2)].into_iter().collect(), whole: None, snapshot: Some((t0, 0, empty())) };
        // A captured generation 1 (y written at 1), B generation 2 (y written again at 2); B finishes first.
        let (a, b) = (load(1, &[(y, 1)], Some((t0, empty()))), load(2, &[(y, 2)], Some((t0, empty()))));
        let newer = empty();
        b.settle(&mut held, Arc::clone(&newer), t0);
        a.settle(&mut held, empty(), t0);
        let (at, under, standing) = held.snapshot.as_ref().unwrap();
        assert_eq!(*under, 2, "the later finisher's older snapshot is not installed");
        assert!(Arc::ptr_eq(standing, &newer));
        assert!(held.written.is_empty(), "y's write was read by the newer load");
        // A load of only the written rows keeps the time the set was last read whole.
        assert_eq!(*at, t0);
        let later = t0 + std::time::Duration::from_secs(5);
        load(2, &[], None).settle(&mut held, empty(), later);
        assert_eq!(held.snapshot.as_ref().unwrap().0, later, "a whole read restarts the backstop");
    }

    #[tokio::test]
    async fn a_live_subscription_check_never_waits_on_a_refresh() {
        let live = SubscriptionId::new("live-targeted");
        let other = SubscriptionId::new("a-fetch");
        *V2_SUB_ID.lock().await = Some(live.clone());
        assert!(is_live_subscription(&live));
        assert!(!is_live_subscription(&other), "a fetch's subscription is not the live one");
        // One a refresh replaced still carries what a relay took in before the new one stood.
        let replaced = SubscriptionId::new("replaced-by-a-refresh");
        assert!(!is_live_subscription(&replaced));
        retire_subscription(replaced.clone());
        assert!(is_live_subscription(&replaced) && routes_live(&replaced), "a replaced subscription still routes");
        for i in 0..RETIRED_SUBS_KEPT {
            retire_subscription(SubscriptionId::new(format!("later-{i}")));
        }
        assert!(!routes_live(&replaced), "only the last few are kept");
        // A refresh holding the ids answers at once, and errs toward dispatching.
        let held = V2_POOLWIDE_SUB_ID.lock().await;
        assert!(is_live_subscription(&other));
        drop(held);
        *V2_SUB_ID.lock().await = None;
        assert!(!is_live_subscription(&live));
    }

    #[tokio::test]
    async fn a_committed_key_or_epoch_change_reaches_the_live_routes_at_once() {
        use crate::community::transport::memory::MemoryRelay;
        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 acct = {
            const B: &[u8] = b"qpzry9x8gf2tvdw0s3jn54khce6mua7l";
            let mut s = String::from("npub1");
            for i in 0..58 {
                s.push(B[(i * 23 + 3) % 32] as char);
            }
            s
        };
        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 me = Keys::generate();
        crate::state::MY_SECRET_KEY.store_from_keys(&me, &[]);
        crate::state::set_my_public_key(me.public_key());

        let relay = MemoryRelay::new();
        let c = super::super::service::create_community(&relay, "Routes", vec!["wss://r".into()], None).await.unwrap();
        let cid = crate::simd::hex::bytes_to_hex_32(&c.id().0);
        let general = c.channels[0].id;
        let routed = |root: &[u8; 32], epoch: u64| {
            let pk = derive::channel_group_key(root, &general, Epoch(epoch)).pk();
            load_held_v2_cached().route(&pk).is_some()
        };
        assert!(routed(&c.community_root, 0));

        // A rotation adopted mid-session: the new epoch's plane routes the moment it is stored.
        let next = [0x5au8; 32];
        assert!(crate::db::community::advance_server_root_epoch(&cid, 1, &next).unwrap());
        assert!(routed(&next, 1), "the adopted epoch's plane routes without waiting out a cache");
        assert!(!routed(&c.community_root, 0), "and the retired one no longer does");

        // A same-epoch convergence onto a sibling key moves the routes the same way.
        let sibling = [0x11u8; 32];
        assert!(crate::db::community::converge_server_root_epoch(&cid, 1, &sibling).unwrap());
        assert!(routed(&sibling, 1));

        // A second community: a write to one is read again while the other's routes stand,
        // and a deleted one stops routing.
        let other = super::super::service::create_community(&relay, "Other", vec!["wss://r".into()], None).await.unwrap();
        let other_general = other.channels[0].id;
        let other_routed = || load_held_v2_cached().route(&derive::channel_group_key(&other.community_root, &other_general, Epoch(0)).pk()).is_some();
        assert!(other_routed() && routed(&sibling, 1));
        let third = [0x22u8; 32];
        assert!(crate::db::community::advance_server_root_epoch(&cid, 2, &third).unwrap());
        assert!(routed(&third, 2) && !routed(&sibling, 1), "the written community is read again");
        assert!(other_routed(), "the other one still routes");
        crate::db::community::delete_community(&crate::simd::hex::bytes_to_hex_32(&other.id().0)).unwrap();
        assert!(!other_routed(), "a deleted community stops routing");
        assert!(routed(&third, 2));
        invalidate_held_v2_cache();
        assert!(routed(&third, 2) && !other_routed(), "a whole reload agrees");
    }

    #[tokio::test]
    async fn a_timeout_heard_live_counts_at_once() {
        use crate::community::transport::memory::MemoryRelay;
        use crate::community::transport::{Query, Transport};

        struct Quiet;
        impl InboundEventHandler for Quiet {}

        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 acct = {
            const B: &[u8] = b"qpzry9x8gf2tvdw0s3jn54khce6mua7l";
            let mut s = String::from("npub1");
            for i in 0..58 {
                s.push(B[(i * 19 + 5) % 32] as char);
            }
            s
        };
        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 me = Keys::generate();
        crate::state::MY_SECRET_KEY.store_from_keys(&me, &[]);
        crate::state::set_my_public_key(me.public_key());

        let relay = MemoryRelay::new();
        let community = super::super::service::create_community(&relay, "LiveTimeout", vec!["wss://r".into()], 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 member = Keys::generate().public_key();
        // Another of the owner's devices sets it: only the wrap reaches this one.
        let (before, cursor) = crate::db::community::get_guestbook(&cid_hex).unwrap();
        super::super::service::timeout_member(&relay, &held(), &member, 600).await.unwrap();
        crate::db::community::set_guestbook(&cid_hex, &before, cursor).unwrap();
        assert!(!super::super::service::community_timeouts(&held()).unwrap().contains_key(&member));

        let gb = derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
        let q = Query { kinds: vec![stream::KIND_WRAP], authors: vec![gb.pk_hex()], ..Default::default() };
        let wraps = relay.fetch(&q, &community.relays).await.unwrap();
        crate::community::v2::realtime::clear().await;
        for wrap in wraps {
            dispatch_event(wrap, Arc::new(Quiet)).await;
        }
        let running = super::super::service::community_timeouts(&held()).unwrap();
        assert!(running.get(&member).is_some_and(|(_, until)| *until > crate::clock::now_secs()), "it runs without waiting for a guestbook read");
    }

    #[tokio::test]
    async fn a_message_dated_ahead_waits_for_its_time_then_arrives() {
        use super::super::stream::{self, SealForm};
        use crate::community::transport::memory::MemoryRelay;

        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();
        let acct = {
            const B: &[u8] = b"qpzry9x8gf2tvdw0s3jn54khce6mua7l";
            let mut s = String::from("npub1");
            for i in 0..58 {
                s.push(B[(i * 17 + 11) % 32] as char);
            }
            s
        };
        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 me = Keys::generate();
        crate::state::MY_SECRET_KEY.store_from_keys(&me, &[]);
        crate::state::set_my_public_key(me.public_key());
        crate::early::start(Arc::new(crate::event_handler::NoOpEventHandler));

        let relay = MemoryRelay::new();
        let community = super::super::service::create_community(&relay, "Clock", vec!["wss://r".into()], None).await.unwrap();
        let general = community.channels[0].id;
        let group = derive::channel_group_key(&community.community_root, &general, community.root_epoch);
        let member = Keys::generate();
        let post = |text: &str, at_ms: u64| {
            let rumor = super::super::chat::build_message_rumor(member.public_key(), &general, community.root_epoch, text, None, &[], vec![], at_ms);
            let seal = stream::build_seal(&rumor, SealForm::Encrypted, &group, &member).unwrap();
            let (wrap, _) = stream::wrap_seal(&seal, &group, stream::KIND_WRAP, nostr_sdk::prelude::Timestamp::from_secs(at_ms / 1000)).unwrap();
            (rumor.id.unwrap().to_hex(), wrap)
        };
        let now = crate::clock::now_ms();
        let (late_id, late) = post("from a clock minutes fast", now + 4 * 60 * 1000);
        let (soon_id, soon) = post("from a clock a little fast", now + crate::early::TOLERANCE_MS + 1_500);
        let (fine_id, fine) = post("from a clock a hair fast", now + 2_000);

        crate::community::v2::realtime::clear().await;
        for wrap in [late.clone(), soon, fine] {
            dispatch_event(wrap, Arc::new(crate::event_handler::NoOpEventHandler)).await;
        }
        let stored = |id: &str| crate::db::events::event_exists(id).unwrap();
        assert!(stored(&fine_id), "a few seconds fast shows at once");
        assert!(!stored(&late_id) && !stored(&soon_id), "ahead of the clock, they wait");
        assert!(crate::early::held(&late.id));
        assert!(!crate::db::wrappers::processed_wrapper_exists(&late.id.to_bytes()), "never marked handled, so a restart can't lose it");

        // Due, the one a little fast arrives through the normal path.
        for _ in 0..40 {
            if stored(&soon_id) {
                break;
            }
            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
        }
        assert!(stored(&soon_id), "released once its time came");
        assert!(!stored(&late_id), "the other still waits");
    }

    #[tokio::test]
    async fn a_live_message_from_my_other_device_arrives_fully_deletable() {
        use super::super::stream::{self, SealForm};
        use crate::community::message_delete::own_wrap_owner;
        use crate::community::transport::memory::MemoryRelay;

        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();
        let acct = {
            const B: &[u8] = b"qpzry9x8gf2tvdw0s3jn54khce6mua7l";
            let mut s = String::from("npub1");
            for i in 0..58 {
                s.push(B[(i * 13 + 9) % 32] as char);
            }
            s
        };
        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 me = Keys::generate();
        crate::state::MY_SECRET_KEY.store_from_keys(&me, &[]);
        crate::state::set_my_public_key(me.public_key());

        let relay = MemoryRelay::new();
        let community = super::super::service::create_community(&relay, "Twin", vec!["wss://r".into()], None).await.unwrap();
        let general = community.channels[0].id;
        let group = derive::channel_group_key(&community.community_root, &general, community.root_epoch);
        let mine = |text: &str, at_ms: u64, derived: bool| {
            let rumor = super::super::chat::build_message_rumor(me.public_key(), &general, community.root_epoch, text, None, &[], vec![], at_ms);
            let rumor_id = rumor.id.unwrap();
            let owner = if derived { own_wrap_owner(&me.public_key(), &group.pk(), &rumor_id).public_key() } else { Keys::generate().public_key() };
            let seal = stream::build_seal(&rumor, SealForm::Encrypted, &group, &me).unwrap();
            let wrap = stream::wrap_seal_for(&seal, &group, stream::KIND_WRAP, nostr_sdk::prelude::Timestamp::from_secs(at_ms / 1000), &[], &owner).unwrap();
            (rumor_id.to_hex(), wrap)
        };
        let (twin, twin_wrap) = mine("from my phone", 5_000, true);
        let (older, older_wrap) = mine("from an older build", 6_000, false);

        crate::community::v2::realtime::clear().await;
        dispatch_event(twin_wrap, Arc::new(crate::event_handler::NoOpEventHandler)).await;
        dispatch_event(older_wrap, Arc::new(crate::event_handler::NoOpEventHandler)).await;

        let has = |id: &str| (crate::db::community::has_wrap_owner(id).unwrap(), crate::db::community::has_message_key(id).unwrap());
        assert_eq!(has(&twin), (true, true), "the owner this identity derives, and the plane key");
        assert_eq!(has(&older), (false, true), "a random owner is no one's here");

        // Either key kept settles it for a catch-up: there is nothing left to heal.
        let twin_wrap_hex = crate::db::community::wrap_owners(&twin).unwrap().pop().unwrap().1;
        crate::db::community::delete_message_key(&twin).unwrap();
        assert!(crate::db::events::community_wraps_settled(std::slice::from_ref(&twin_wrap_hex)).contains(&twin_wrap_hex));
    }

    #[tokio::test]
    async fn dispatch_event_routes_a_v2_message_to_the_handler() {
        use crate::community::transport::memory::MemoryRelay;
        use crate::community::transport::{Query, Transport};
        use crate::types::Message;
        use std::sync::Mutex as StdMutex;

        #[derive(Default)]
        struct Recorder {
            got: StdMutex<Vec<(String, String)>>,
        }
        impl InboundEventHandler for Recorder {
            fn on_community_message(&self, chat_id: &str, msg: &Message, _new: bool) {
                self.got.lock().unwrap().push((chat_id.to_string(), msg.content.clone()));
            }
        }

        // Offline DB + identity.
        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();
        let acct = {
            const B: &[u8] = b"qpzry9x8gf2tvdw0s3jn54khce6mua7l";
            let mut s = String::from("npub1");
            for i in 0..58 {
                s.push(B[(i * 5 + 1) % 32] as char);
            }
            s
        };
        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 me = Keys::generate();
        crate::state::MY_SECRET_KEY.store_from_keys(&me, &[]);
        crate::state::set_my_public_key(me.public_key());

        // Create a v2 community (persisted), then ANOTHER member (holds the root)
        // posts โ€” the incoming case a live sub delivers (an OWN send is echoed at
        // send time, so its relay copy correctly dedups instead of firing).
        let relay = MemoryRelay::new();
        let community = super::super::service::create_community(&relay, "Live", vec!["wss://r".into()], None).await.unwrap();
        let general = community.channels[0].id;
        let member = Keys::generate();
        let group = derive::channel_group_key(&community.community_root, &general, community.root_epoch);
        let rumor = super::super::chat::build_message_rumor(member.public_key(), &general, community.root_epoch, "live ping", None, &[], vec![], 5_000);
        let (wrap, _) = super::super::chat::seal_chat_rumor(&rumor, &group, &member, nostr_sdk::prelude::Timestamp::from_secs(5), false).unwrap();
        let _ = relay.publish(&wrap, &community.relays).await;
        let q = Query { kinds: vec![stream::KIND_WRAP], authors: vec![group.pk_hex()], ..Default::default() };
        let wrap = relay.fetch(&q, &community.relays).await.unwrap().into_iter().find(|w| w.pubkey == group.pk()).unwrap();

        // The realtime dispatch (loading held v2 communities from the DB) routes it.
        // Dispatch the SAME wrap TWICE โ€” modelling the pool re-delivering it under
        // the targeted + pool-wide subs (and from multiple relays). The handler
        // must fire EXACTLY ONCE (no duplicate bot replies) โ€” and only AFTER the
        // persist outcome (the callbacks-from-persist model).
        let rec = Arc::new(Recorder::default());
        crate::community::v2::realtime::clear().await; // fresh seen-set for the test
        let first_id = wrap.id;
        dispatch_event(wrap.clone(), rec.clone()).await;
        dispatch_event(wrap, rec.clone()).await;

        {
            let got = rec.got.lock().unwrap();
            assert_eq!(got.len(), 1, "a re-delivered wrap fires the handler exactly once");
            assert_eq!(got[0].1, "live ping");
            assert_eq!(got[0].0, crate::simd::hex::bytes_to_hex_32(&general.0));
        }
        assert!(crate::db::wrappers::processed_wrapper_exists(&first_id.to_bytes()), "a handled wrap joins the ledger");

        // Settled for a catch-up: someone else's stored message, or mine once its delete key is kept.
        let wrap_hex = first_id.to_hex();
        assert!(crate::db::events::community_wraps_settled(std::slice::from_ref(&wrap_hex)).contains(&wrap_hex), "a stored foreign message is settled");
        assert_eq!(crate::db::events::community_wraps_settled(&[wrap_hex.clone(), "cd".repeat(32)]).len(), 1, "an unknown wrap is not");
        let w = crate::db::get_write_connection_guard_static().unwrap();
        w.execute("UPDATE events SET mine = 1 WHERE wrapper_event_id = ?1", [&wrap_hex]).unwrap();
        let rumor_hex: String = w.query_row("SELECT id FROM events WHERE wrapper_event_id = ?1", [&wrap_hex], |r| r.get(0)).unwrap();
        drop(w);
        assert!(!crate::db::events::community_wraps_settled(std::slice::from_ref(&wrap_hex)).contains(&wrap_hex), "my message without its delete key still heals on open");
        crate::db::community::store_message_key(&rumor_hex, &wrap_hex, group.keys(), &community.relays).unwrap();
        assert!(crate::db::events::community_wraps_settled(std::slice::from_ref(&wrap_hex)).contains(&wrap_hex), "with the key kept there is nothing left to heal");
        crate::db::get_write_connection_guard_static().unwrap().execute("UPDATE events SET mine = 0 WHERE wrapper_event_id = ?1", [&wrap_hex]).unwrap();

        // A reaction to a message we don't hold yet stays retryable: no ledger entry.
        let unseen = "ab".repeat(32);
        let reaction = super::super::chat::build_reaction_rumor(
            member.public_key(), &general, community.root_epoch, &unseen, &member.public_key().to_hex(), 14, "+", None, 7_000,
        );
        let (early, _) = super::super::chat::seal_chat_rumor(&reaction, &group, &member, nostr_sdk::prelude::Timestamp::from_secs(7), false).unwrap();
        let early_id = early.id;
        dispatch_event(early, rec.clone()).await;
        assert!(!crate::db::wrappers::processed_wrapper_exists(&early_id.to_bytes()), "an early reaction is not ledgered");

        // A wrap already stored under its outer id is dropped before it's opened. The stored
        // row is made to claim a second message's wrap, so only that skip keeps it silent.
        let rumor2 = super::super::chat::build_message_rumor(member.public_key(), &general, community.root_epoch, "second", None, &[], vec![], 6_000);
        let (wrap2, _) = super::super::chat::seal_chat_rumor(&rumor2, &group, &member, nostr_sdk::prelude::Timestamp::from_secs(6), false).unwrap();
        let moved = crate::db::get_write_connection_guard_static().unwrap().execute(
            "UPDATE events SET wrapper_event_id = ?1 WHERE wrapper_event_id = ?2",
            rusqlite::params![wrap2.id.to_hex(), first_id.to_hex()],
        ).unwrap();
        assert_eq!(moved, 1, "the first message was stored under its outer id");
        dispatch_event(wrap2, rec.clone()).await;
        assert_eq!(rec.got.lock().unwrap().len(), 1, "a stored outer id never reaches the handler");
    }

    #[tokio::test]
    async fn a_post_held_on_arrival_waits_and_a_manager_sees_it_unrung() {
        use crate::community::v2::writers::{writer_address, Ledger, Spell};
        use crate::types::Message;
        use std::sync::Mutex as StdMutex;

        #[derive(Default)]
        struct Recorder {
            got: StdMutex<Vec<(String, bool, bool)>>,
        }
        impl InboundEventHandler for Recorder {
            fn on_community_message(&self, _chat_id: &str, msg: &Message, is_new: bool) {
                self.got.lock().unwrap().push((msg.content.clone(), is_new, msg.unauthorized));
            }
        }

        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();
        let acct = {
            const B: &[u8] = b"qpzry9x8gf2tvdw0s3jn54khce6mua7l";
            let mut s = String::from("npub1");
            for i in 0..58 {
                s.push(B[(i * 11 + 9) % 32] as char);
            }
            s
        };
        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 me = Keys::generate();
        crate::state::MY_SECRET_KEY.store_from_keys(&me, &[]);
        crate::state::set_my_public_key(me.public_key());

        let relay = crate::community::transport::memory::MemoryRelay::new();
        let community = super::super::service::create_community(&relay, "Held live", vec!["wss://r".into()], None).await.unwrap();
        let general = community.channels[0].id;
        let (cid, chan) = (crate::simd::hex::bytes_to_hex_32(&community.id().0), crate::simd::hex::bytes_to_hex_32(&general.0));
        let ledger = Ledger::new(&general)
            .appended(1_000, Spell::Writer { epoch: crate::community::Epoch(1), pk: writer_address(&[0x11; 32], &general, crate::community::Epoch(1)), root: community.root_epoch, by: me.public_key().to_bytes(), certifier: None })
            .unwrap();
        crate::db::community::set_community_writers(&cid, &chan, &ledger.to_json(), 1, true).unwrap();
        invalidate_held_v2_cache();
        let member = Keys::generate();
        let group = derive::channel_group_key(&community.community_root, &general, community.root_epoch);
        let rumor = super::super::chat::build_message_rumor(member.public_key(), &general, community.root_epoch, "not a writer", None, &[], vec![], 5_000);
        let (wrap, _) = super::super::chat::seal_chat_rumor(&rumor, &group, &member, nostr_sdk::prelude::Timestamp::from_secs(5), false).unwrap();

        let rec = Arc::new(Recorder::default());
        clear().await;
        dispatch_event(wrap.clone(), rec.clone()).await;
        dispatch_event(wrap.clone(), rec.clone()).await;
        assert_eq!(rec.got.lock().unwrap().clone(), vec![("not a writer".to_string(), false, true)], "the owner sees it once, marked, and nothing rings");
        let held = crate::db::community::held_wraps(&cid).unwrap();
        assert_eq!(held.iter().map(|(id, ..)| id.clone()).collect::<Vec<_>>(), vec![wrap.id.to_hex()], "its wrap waits for a later judgment");
        assert!(crate::db::wrappers::processed_wrapper_exists(&wrap.id.to_bytes()), "never opened again off a relay");
        let now_ms = || web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).unwrap().as_millis() as u64;
        // One that can't be held, dated past the horizon, stays on the relay for a later read.
        let ahead = super::super::chat::build_message_rumor(member.public_key(), &general, community.root_epoch, "from next week", None, &[], vec![], now_ms() + 7 * 86_400_000);
        let (later, _) = super::super::chat::seal_chat_rumor(&ahead, &group, &member, nostr_sdk::prelude::Timestamp::from_secs(6), false).unwrap();
        dispatch_event(later.clone(), rec.clone()).await;
        assert_eq!(rec.got.lock().unwrap().len(), 1, "no copy of what isn't held");
        assert!(!crate::db::wrappers::processed_wrapper_exists(&later.id.to_bytes()));

        // A ledger that moves takes back what its new stop undoes, before the read that follows.
        #[derive(Default)]
        struct Removed(StdMutex<Vec<(String, bool)>>);
        impl InboundEventHandler for Removed {
            fn on_community_update(&self, _chat_id: &str, target: &str, msg: &Message) {
                self.0.lock().unwrap().push((target.to_string(), msg.unauthorized));
            }
        }
        // A writer at that certifier-less epoch posts after a stop this device hasn't read.
        let writer = Keys::generate();
        let wgroup = derive::channel_writer_group_key(&[0x11; 32], &general, crate::community::Epoch(1));
        let split = derive::GroupKey::from_parts(wgroup.keys().clone(), group.conv_key().clone());
        let rumor = super::super::chat::with_writer_epoch(super::super::chat::build_message_rumor(writer.public_key(), &general, community.root_epoch, "after the stop", None, &[], vec![], now_ms() + 5_000), crate::community::Epoch(1));
        let (posted, _) = super::super::chat::seal_chat_rumor(&rumor, &split, &writer, nostr_sdk::prelude::Timestamp::from_secs(now_ms() / 1000 + 5), false).unwrap();
        crate::community::transport::Transport::publish(&relay, &posted, &community.relays).await.unwrap();
        clear().await;
        dispatch_event(posted.clone(), rec.clone()).await;
        let stopped = ledger.appended(now_ms(), Spell::Stop { writer: writer.public_key().to_bytes() }).unwrap();
        crate::db::community::set_community_writers(&cid, &chan, &stopped.to_json(), 2, true).unwrap();
        let removed = Removed::default();
        settle_owed_retractions(community.id(), &relay, &removed).await;
        assert!(crate::db::community::owed_retractions(&cid).unwrap().is_empty(), "nothing owed once taken back");
        // A read that fails leaves it owed for the next pass.
        struct Down;
        #[async_trait::async_trait]
        impl crate::community::transport::Transport for Down {
            async fn fetch_plane(&self, _p: &Keys, _q: &crate::community::transport::Query, _r: &[String]) -> Result<crate::community::transport::PlaneFetch, String> {
                Err("down".into())
            }
            async fn publish(&self, _e: &nostr_sdk::prelude::Event, _r: &[String]) -> Result<(), String> {
                Err("down".into())
            }
            async fn publish_durable(&self, _e: &nostr_sdk::prelude::Event, _r: &[String]) -> Result<(), String> {
                Err("down".into())
            }
            async fn fetch(&self, _q: &crate::community::transport::Query, _r: &[String]) -> Result<Vec<nostr_sdk::prelude::Event>, String> {
                Err("down".into())
            }
        }
        let stored = Message { id: "c".repeat(64), content: "shown".into(), at: now_ms(), npub: Some(nostr_sdk::prelude::ToBech32::to_bech32(&Keys::generate().public_key()).unwrap()), wrapper_event_id: Some("b".repeat(64)), ..Default::default() };
        crate::db::events::save_message(&chan, &stored).await.unwrap();
        crate::db::community::owe_writer_retraction(&cid, &chan, stored.at - 1).unwrap();
        settle_owed_retractions(community.id(), &Down, &removed).await;
        assert_eq!(crate::db::community::owed_retractions(&cid).unwrap().iter().map(|(c, s, _)| (c.clone(), *s)).collect::<Vec<_>>(), vec![(chan.clone(), stored.at - 1)], "still owed");
        // Nor does a drain cut short: it clears only once done.
        struct Hangs;
        #[async_trait::async_trait]
        impl crate::community::transport::Transport for Hangs {
            async fn fetch_plane(&self, _p: &Keys, _q: &crate::community::transport::Query, _r: &[String]) -> Result<crate::community::transport::PlaneFetch, String> {
                std::future::pending().await
            }
            async fn publish(&self, _e: &nostr_sdk::prelude::Event, _r: &[String]) -> Result<(), String> {
                std::future::pending().await
            }
            async fn publish_durable(&self, _e: &nostr_sdk::prelude::Event, _r: &[String]) -> Result<(), String> {
                std::future::pending().await
            }
            async fn fetch(&self, _q: &crate::community::transport::Query, _r: &[String]) -> Result<Vec<nostr_sdk::prelude::Event>, String> {
                std::future::pending().await
            }
        }
        let _ = tokio::time::timeout(std::time::Duration::from_millis(100), settle_owed_retractions(community.id(), &Hangs, &removed)).await;
        assert_eq!(crate::db::community::owed_retractions(&cid).unwrap().len(), 1, "a drain that never finished leaves it owed");
        let id = super::super::chat::open_writer_chat_event(&posted, &posted.pubkey, crate::community::Epoch(1), group.conv_key(), &general, community.root_epoch).unwrap().opened().rumor_id.to_hex();
        assert_eq!(removed.0.lock().unwrap().clone(), vec![(id, true)], "the owner's device keeps it, marked");
    }

    #[tokio::test]
    async fn a_stale_straggler_folds_like_a_live_event_without_ringing() {
        use crate::community::transport::memory::MemoryRelay;
        use crate::types::Message;
        use std::sync::Mutex as StdMutex;

        #[derive(Default)]
        struct Recorder {
            got: StdMutex<Vec<(String, bool)>>,
        }
        impl InboundEventHandler for Recorder {
            fn on_community_message(&self, _chat_id: &str, msg: &Message, new: bool) {
                self.got.lock().unwrap().push((msg.content.clone(), new));
            }
        }

        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();
        let acct = {
            const B: &[u8] = b"qpzry9x8gf2tvdw0s3jn54khce6mua7l";
            let mut s = String::from("npub1");
            for i in 0..58 {
                s.push(B[(i * 11 + 5) % 32] as char);
            }
            s
        };
        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 me = Keys::generate();
        crate::state::MY_SECRET_KEY.store_from_keys(&me, &[]);
        crate::state::set_my_public_key(me.public_key());

        let relay = MemoryRelay::new();
        let community = super::super::service::create_community(&relay, "Late", vec!["wss://r".into()], None).await.unwrap();
        let general = community.channels[0].id;
        let member = Keys::generate();
        let group = derive::channel_group_key(&community.community_root, &general, community.root_epoch);
        let rumor = super::super::chat::build_message_rumor(member.public_key(), &general, community.root_epoch, "old news", None, &[], vec![], 5_000);
        let (wrap, _) = super::super::chat::seal_chat_rumor(&rumor, &group, &member, nostr_sdk::prelude::Timestamp::from_secs(5), false).unwrap();

        let rec = Arc::new(Recorder::default());
        crate::community::v2::realtime::clear().await;
        crate::community::dispatch_inbound(wrap.clone(), rec.clone()).await;
        crate::community::dispatch_inbound(wrap.clone(), rec.clone()).await;
        assert_eq!(*rec.got.lock().unwrap(), vec![("old news".to_string(), false)], "folded once, never as new");
        assert!(crate::db::wrappers::processed_wrapper_exists(&wrap.id.to_bytes()));
        let channel_hex = crate::simd::hex::bytes_to_hex_32(&general.0);
        let chat_id = crate::db::id_cache::get_chat_id_by_identifier(&channel_hex).unwrap();
        assert_eq!(crate::db::events::get_chat_message_count(chat_id).unwrap(), 1);

        // What a fetch for our own documents returns rides the same sink, and opens nowhere.
        use nostr_sdk::prelude::FinalizeEvent;
        let own = nostr_sdk::prelude::EventBuilder::new(nostr_sdk::prelude::Kind::Custom(super::super::kind::COMMUNITY_LIST_FRAG), "x")
            .finalize(&me)
            .unwrap();
        crate::community::dispatch_inbound(own, rec.clone()).await;
        assert_eq!(rec.got.lock().unwrap().len(), 1);
        assert_eq!(crate::db::events::get_chat_message_count(chat_id).unwrap(), 1);
    }

    #[test]
    fn every_plane_address_routes_to_its_own_community() {
        let (a, b) = (a_community("A"), a_community("B"));
        let held = HeldV2 { communities: vec![a.clone(), b.clone()].into(), routes: Default::default() };
        for c in [&a, &b] {
            for pk in community_addresses(c) {
                assert_eq!(held.route(&pk).map(|r| r.id().0), Some(c.id().0));
            }
        }
        assert!(held.route(&Keys::generate().public_key()).is_none(), "a stranger's wrap routes nowhere");
    }

    fn wrap_id(n: u32) -> [u8; 32] {
        let mut id = [0x5C; 32];
        id[..4].copy_from_slice(&n.to_le_bytes());
        id
    }

    #[test]
    fn a_wrap_is_dispatched_once_across_a_generation_turnover() {
        let gen = SEEN_WRAPS_GEN as u32;
        let mut seen = SeenWraps::default();
        assert!(seen.first_sight(&wrap_id(0)));
        assert!(!seen.first_sight(&wrap_id(0)), "a re-delivery is refused");
        for n in 1..gen {
            assert!(seen.first_sight(&wrap_id(n)));
        }
        // The id past a full generation turns it over, and nothing just seen is forgotten.
        assert!(seen.first_sight(&wrap_id(gen)));
        assert_eq!((seen.cur.len(), seen.prev.len()), (1, SEEN_WRAPS_GEN), "a full generation ages whole");
        for n in 0..=gen {
            assert!(!seen.first_sight(&wrap_id(n)), "wrap {n} fired twice across a turnover");
        }
        // A second full generation retires the first, and memory stays at two.
        for n in gen + 1..=2 * gen {
            assert!(seen.first_sight(&wrap_id(n)));
        }
        assert!(seen.cur.len() + seen.prev.len() <= 2 * SEEN_WRAPS_GEN);
        assert!(!seen.first_sight(&wrap_id(gen)), "the previous generation is still remembered");
        assert!(seen.first_sight(&wrap_id(0)), "two generations back is let go");
    }

    #[tokio::test]
    async fn each_account_keeps_its_own_seen_wraps() {
        let (a, b) = (crate::db::Session::empty(), crate::db::Session::empty());
        let id = wrap_id(77);
        let first = |s| crate::db::with_session(s, async move { seen_wraps().lock().unwrap().first_sight(&id) });
        assert!(first(a.clone()).await);
        assert!(!first(a).await);
        assert!(first(b).await, "a wrap one account dispatched is still new to another");
    }

    fn community_on(name: &str, relays: &[&str]) -> CommunityV2 {
        let mut c = a_community(name);
        c.relays = relays.iter().map(|r| r.to_string()).collect();
        c
    }

    fn key_set(pks: impl IntoIterator<Item = PublicKey>) -> std::collections::BTreeSet<[u8; 32]> {
        pks.into_iter().map(|p| p.to_bytes()).collect()
    }

    #[test]
    fn each_relay_is_asked_for_exactly_the_planes_of_the_communities_that_list_it() {
        // Two spellings of one relay, a relay listed twice, and a community with no usable relay.
        let a = community_on("A", &["wss://one.example", "wss://one.example/", "wss://shared.example"]);
        let b = community_on("B", &["wss://shared.example/", "wss://two.example"]);
        let lost = community_on("C", &["not a relay"]);
        let held = [a.clone(), b.clone(), lost.clone()];
        let plan = subscription_plan(&held);
        let url = |s: &str| RelayUrl::parse(s).unwrap();

        // Every address, from every listed relay.
        let old_authors = plane_authors(&held);
        let old_relays: std::collections::BTreeSet<RelayUrl> =
            held.iter().flat_map(|c| c.relays.iter()).filter_map(|r| RelayUrl::parse(r).ok()).collect();
        assert_eq!(plan.authors, old_authors, "the pool-wide filter is unchanged");
        assert_eq!(plan.per_relay.keys().cloned().collect::<std::collections::BTreeSet<_>>(), old_relays);
        assert_eq!(key_set(plan.per_relay.values().flatten().copied()), key_set(old_authors.iter().copied()), "no address is dropped");

        // Coverage: every community's planes from every relay it lists.
        for c in &held {
            for r in c.relays.iter().filter_map(|r| RelayUrl::parse(r).ok()) {
                let share = key_set(plan.per_relay[&r].iter().copied());
                assert!(key_set(community_addresses(c)).is_subset(&share), "{} lost coverage on {r}", c.name);
            }
        }
        // The saving: a relay carries only its own communities, plus the one with nowhere else.
        let only = |cs: &[&CommunityV2]| key_set(cs.iter().flat_map(|c| community_addresses(c)));
        assert_eq!(key_set(plan.per_relay[&url("wss://one.example")].iter().copied()), only(&[&a, &lost]));
        assert_eq!(key_set(plan.per_relay[&url("wss://two.example")].iter().copied()), only(&[&b, &lost]));
        assert_eq!(key_set(plan.per_relay[&url("wss://shared.example")].iter().copied()), only(&[&a, &b, &lost]));
        for share in plan.per_relay.values() {
            assert!(share.windows(2).all(|w| w[0].to_bytes() < w[1].to_bytes()), "each share is sorted and deduped");
        }
    }

    #[test]
    fn the_plan_fingerprint_moves_with_any_relays_share() {
        let a = community_on("A", &["wss://one.example"]);
        let b = community_on("B", &["wss://two.example"]);
        let base = subscription_plan(&[a.clone(), b.clone()]);
        assert_eq!(plan_fingerprint(&base), plan_fingerprint(&subscription_plan(&[b.clone(), a.clone()])));
        // Same author set overall, split differently: the unchanged-plan fast path must not take it.
        let mut moved_b = b.clone();
        moved_b.relays = vec!["wss://one.example".into()];
        let moved = subscription_plan(&[a.clone(), moved_b]);
        assert_eq!(moved.authors, base.authors);
        assert_ne!(plan_fingerprint(&moved), plan_fingerprint(&base));
        assert_ne!(plan_fingerprint(&subscription_plan(&[a])), plan_fingerprint(&base));
    }

    #[test]
    fn an_idle_follow_lock_is_pruned_and_a_held_one_is_shared() {
        let _serial = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
        let (held_id, idle_id) = (CommunityId([0xA1; 32]), CommunityId([0xB2; 32]));
        let held = follow_lock(&held_id);
        assert!(Arc::ptr_eq(&held, &follow_lock(&held_id)), "every caller gets the one lock");
        drop(follow_lock(&idle_id));
        let _next = follow_lock(&CommunityId([0xC3; 32]));
        let locks = V2_FOLLOW_LOCKS.lock().unwrap();
        assert!(!locks.contains_key(&idle_id.0), "a lock nobody holds goes when a new one is made");
        assert!(locks.contains_key(&held_id.0), "a held lock is never dropped from under its holder");
    }

    #[tokio::test]
    async fn follow_queue_coalesces_a_burst_and_re_enqueues_after_processing() {
        // The queue is process-wide: every test that installs or clears it holds this guard.
        let _serial = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
        // Install a test channel in place of the worker's, so we can observe what the
        // queue delivers without a live client.
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<CommunityId>();
        *V2_FOLLOW_TX.lock().unwrap() = Some(tx);
        V2_FOLLOW_PENDING.lock().unwrap().clear();

        let id = CommunityId([0x11; 32]);
        // A burst for one community collapses to a SINGLE queued follow (coalesced).
        enqueue_follow(&id);
        enqueue_follow(&id);
        enqueue_follow(&id);
        assert_eq!(rx.recv().await, Some(id), "first trigger queues a follow");
        assert!(rx.try_recv().is_err(), "the burst coalesced to exactly one");

        // The worker removes it from pending before running; a trigger AFTER that
        // re-queues (so a change during a follow isn't lost).
        V2_FOLLOW_PENDING.lock().unwrap().remove(&id.0);
        enqueue_follow(&id);
        assert_eq!(rx.recv().await, Some(id), "a trigger after processing re-queues");

        // A different community is independent (not coalesced against the first).
        let id2 = CommunityId([0x22; 32]);
        enqueue_follow(&id2);
        assert_eq!(rx.recv().await, Some(id2));

        *V2_FOLLOW_TX.lock().unwrap() = None;
        V2_FOLLOW_PENDING.lock().unwrap().clear();
    }

    #[test]
    fn a_live_rotation_is_taken_ahead_of_a_boot_backlog() {
        V2_FOLLOW_URGENT.lock().unwrap().clear();
        let backlog: Vec<CommunityId> = (1u8..=30).map(|n| CommunityId([n; 32])).collect();
        let rotated = CommunityId([0xAA; 32]);

        let mut queue: std::collections::VecDeque<CommunityId> = backlog.clone().into();
        // The rotation lands at the BACK, exactly as a live dispatch mid-batch does.
        queue.push_back(rotated);

        // Without the mark it waits out all 30 walks.
        assert_eq!(pop_next_follow(&mut queue.clone()), Some(backlog[0]));

        V2_FOLLOW_URGENT.lock().unwrap().insert(rotated.0);
        assert_eq!(
            pop_next_follow(&mut queue),
            Some(rotated),
            "a live rotation must not queue behind dozens of unrelated network walks"
        );
        // Everything else keeps its prioritised order behind it.
        assert_eq!(pop_next_follow(&mut queue), Some(backlog[0]));
        V2_FOLLOW_URGENT.lock().unwrap().clear();
    }

    #[test]
    fn urgency_promotes_an_id_already_queued() {
        let _serial = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<CommunityId>();
        *V2_FOLLOW_TX.lock().unwrap() = Some(tx);
        V2_FOLLOW_PENDING.lock().unwrap().clear();
        V2_FOLLOW_URGENT.lock().unwrap().clear();

        let id = CommunityId([0x33; 32]);
        enqueue_follow(&id); // boot catch-up queued it first
        // The live rotation coalesces against that entry โ€” the urgency must still land,
        // or the promotion is silently swallowed by the dedup.
        enqueue_follow_urgent(&id);
        assert!(V2_FOLLOW_URGENT.lock().unwrap().contains(&id.0));
        assert_eq!(rx.try_recv().ok(), Some(id));
        assert!(rx.try_recv().is_err(), "still coalesced to one queue entry");

        *V2_FOLLOW_TX.lock().unwrap() = None;
        V2_FOLLOW_PENDING.lock().unwrap().clear();
        V2_FOLLOW_URGENT.lock().unwrap().clear();
    }

    #[tokio::test]
    async fn a_dissolved_community_honors_no_new_events_and_fires_death_once() {
        use super::super::service;
        use crate::community::transport::memory::MemoryRelay;
        use crate::community::transport::Transport;
        use crate::types::Message;
        use std::sync::Mutex as StdMutex;

        #[derive(Default)]
        struct Recorder {
            messages: StdMutex<Vec<String>>,
            deaths: StdMutex<Vec<String>>,
        }
        impl InboundEventHandler for Recorder {
            fn on_community_message(&self, _chat: &str, msg: &Message, _new: bool) {
                self.messages.lock().unwrap().push(msg.content.clone());
            }
            fn on_community_dissolved(&self, community_id: &str) {
                self.deaths.lock().unwrap().push(community_id.to_string());
            }
        }

        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();
        let acct = {
            const B: &[u8] = b"qpzry9x8gf2tvdw0s3jn54khce6mua7l";
            let mut s = String::from("npub1");
            for i in 0..58 {
                s.push(B[(i * 3 + 2) % 32] as char);
            }
            s
        };
        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 me = Keys::generate();
        crate::state::MY_SECRET_KEY.store_from_keys(&me, &[]);
        crate::state::set_my_public_key(me.public_key());

        let relay = MemoryRelay::new();
        let community = service::create_community(&relay, "Doomed", vec!["wss://r".into()], None).await.unwrap();
        let general = community.channels[0].id;

        // The owner's tombstone arrives as a MEMBER sees it (local flag still 0 โ€”
        // build + publish it directly rather than via dissolve_community, which
        // would seal our own DB first and make it the owner-published case). `me`
        // is the owner, so the seal verifies.
        let rumor = super::super::dissolution::dissolved_tombstone_rumor(me.public_key(), community.id(), 8_000);
        let tombstone = super::super::dissolution::seal_dissolved(&rumor, community.id(), &me, nostr_sdk::prelude::Timestamp::from_secs(8_000)).unwrap();
        let _ = relay.publish(&tombstone, &community.relays).await;
        assert!(!crate::db::community::get_community_dissolved(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap(), "not yet locally sealed");

        let rec = Arc::new(Recorder::default());
        clear().await;
        // Fire the SAME tombstone twice AND a fresh re-wrap of its verified seal
        // (distinct outer id) โ€” death must be announced exactly once.
        dispatch_event(tombstone.clone(), rec.clone()).await;
        dispatch_event(tombstone, rec.clone()).await;
        assert!(crate::db::community::get_community_dissolved(&crate::simd::hex::bytes_to_hex_32(&community.id().0)).unwrap());

        // A member posts a fresh message to #general AFTER the tombstone. It must
        // not be honored (the community is excluded from load_held_v2, so its
        // plane is NotOurs).
        let member = Keys::generate();
        let cgroup = derive::channel_group_key(&community.community_root, &general, community.root_epoch);
        let rumor = super::super::chat::build_message_rumor(member.public_key(), &general, community.root_epoch, "into the grave", None, &[], vec![], 9_000);
        let (mw, _) = super::super::chat::seal_chat_rumor(&rumor, &cgroup, &member, nostr_sdk::prelude::Timestamp::from_secs(9), false).unwrap();
        dispatch_event(mw, rec.clone()).await;

        assert_eq!(rec.deaths.lock().unwrap().len(), 1, "death is announced exactly once");
        assert!(rec.messages.lock().unwrap().is_empty(), "a post-tombstone message is never honored (CORD-02 ยง9)");

        // Surfacing the death refreshes the UI, which asks for a follow; following a known
        // grave must stay quiet, or the two feed each other.
        crate::state::set_nostr_client(crate::nostr_client_builder().build());
        let session = crate::db::current_session();
        for _ in 0..3 {
            follow_community(&session, community.id(), &*rec).await;
        }
        let _ = crate::state::take_nostr_client();
        assert_eq!(rec.deaths.lock().unwrap().len(), 1, "a follow of a known grave announces nothing");
    }

    #[test]
    fn a_private_channel_subscribes_to_its_own_chat_plane() {
        let mut c = a_community("Priv");
        c.channels.push(super::super::community::ChannelV2 {
            id: crate::community::ChannelId([0x33; 32]),
            name: "mods".into(),
            private: true,
            key: Some([0x44; 32]),
            epoch: Epoch(1),
            voice: None,
            meta_custom: None,
            meta_extra: Default::default(),
            writers: None,
            sealed: None,
        });
        let authors = plane_authors(std::slice::from_ref(&c));
        // A private channel is read under its OWN key/epoch (not the root).
        let priv_chat = derive::channel_group_key(&[0x44; 32], &c.channels[1].id, Epoch(1)).pk();
        assert!(authors.contains(&priv_chat), "a private channel subscribes to its own chat plane");
        // Its next-rekey address IS subscribed (rekey-follow), keyed by the current
        // root at the channel's next epoch โ€” so a rotation is delivered.
        let next_rekey = derive::channel_rekey_group_key(&c.community_root, &c.channels[1].id, Epoch(2)).pk();
        assert!(authors.contains(&next_rekey), "a private channel's next rekey plane is subscribed");
    }
}