vector-core 0.12.0

Core library for Vector: the single source of truth for all Vector clients, SDKs and interfaces.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
//! Vector Core: the single source of truth for all Vector clients, SDKs and interfaces.
//!
//! This crate contains ALL of Vector's business logic, fully decoupled from Tauri.
//! It is used by:
//! - **src-tauri**: the desktop and mobile app (a thin command shell)
//! - **Vector Web**: the same frontend in a browser, over this crate compiled to wasm32
//! - **vector_sdk**: bots and clients, with **vector-media** for voice without devices
//! - **vector-cli**, **concord-cli** and the **vector-agent** MCP server
//!
//! # Architecture
//!
//! ```text
//! ┌─────────────────────────────────────────────┐
//! │              vector-core                     │
//! │                                              │
//! │  types ─ compact ─ state ─ db ─ crypto       │
//! │  chat ─ profile ─ net ─ hex                  │
//! │                                              │
//! │  traits::EventEmitter (UI abstraction)       │
//! │  VectorCore (high-level API)                 │
//! └─────────────────────────────────────────────┘
//!        ▲              ▲              ▲
//!   src-tauri       vector-cli     Vector SDK
//! (AppHandle)      (terminal)     (callbacks)
//! ```

// === Logging (must be first — #[macro_export] macros used by all modules) ===
#[macro_use]
mod macros;

// === Foundation ===
pub mod rt;
pub mod files;
#[cfg(target_arch = "wasm32")]
pub mod webfiles;
pub mod logging;
pub mod error;
pub mod traits;

// Nostr SDK trait imports needed for bech32 operations
use crate::event_ext::FinalizeUnsignedWithId;
use nostr_sdk::prelude::{FinalizeEventAsync, ToBech32};

// === Core Types ===
pub mod event_ext;
pub mod event_json;
pub mod tags;
pub mod types;
pub mod profile;
pub mod chat;
pub mod clock;
pub mod boot_payload;
pub mod compact;

// === State ===
pub mod state;

// === Debug Stats ===
#[cfg(any(debug_assertions, feature = "bench"))]
pub mod stats;

// === Crypto ===
pub mod crypto;

// === Signer (polymorphic: local vault vs. NIP-46 remote bunker) ===
pub mod signer;

// === NIP-55 offline signer (on-device Amber over Android IPC) ===
pub mod nip55;

// === NIP-07 browser signer (a `window.nostr` extension, web builds) ===
pub mod nip07;

// === Database ===
pub mod db;
/// The "every task carries its account" check, run by this crate's suite and
/// by every crate that spawns per-account work against vector-core.
pub mod spawn_audit;
#[cfg(test)]
mod vault_audit;

// === Network ===
pub mod net;
pub mod fasthash;
pub mod event_size;
#[cfg(not(target_arch = "wasm32"))]
pub mod tls;
pub mod events_tracker;
pub mod proxy;
pub mod negentropy;
pub mod dm_catchup;
pub mod live_subs;
pub mod news;
pub mod blossom;
pub mod media;
pub mod blossom_servers;
pub mod blossom_capabilities;
pub mod blossom_error;
pub mod blossom_info;
pub mod blossom_stats;
pub mod inbox_relays;
pub mod relay_info;
pub mod emoji_packs;
pub mod text_color;
pub mod text_time;
pub mod text_spans;
pub mod secrets;
pub mod emoji_usage;
pub mod nostr_embed;
pub mod video_poster;
pub mod image_crop;
pub mod image_prep;
pub mod deep_link;
pub mod golink;
pub mod badges;
pub mod history_gaps;
pub mod bot_interface;
pub mod webxdc;
pub mod webxdc_permissions;
#[cfg(feature = "xdc")]
pub mod xdc;
#[cfg(feature = "tor")]
pub mod tor;
#[cfg(all(feature = "i2p", not(target_arch = "wasm32")))]
pub mod i2p;
pub mod transport;
pub mod svg;
#[cfg(not(target_arch = "wasm32"))]
pub mod vcache;

/// NIP-42 authenticator.
///
/// Many Concord/Armada communities live on AUTH-gating relays (Ditto's default
/// gates kind-1059), where an unauthenticated client silently reads back ZERO
/// events — a join's control-plane verify then fails closed and every community
/// fetch comes up empty. Registering this is what unlocks those reads; a relay
/// that doesn't challenge is unaffected.
///
/// The signer is resolved per challenge rather than captured at client
/// construction, so a bunker that connects later (or an account swap) authks
/// under the identity that is live *now*.
#[derive(Debug)]
pub struct VectorAuthenticator;

impl nostr_sdk::prelude::Authenticator for VectorAuthenticator {
    fn make_auth_event<'a>(
        &'a self,
        relay_url: &'a nostr_sdk::prelude::RelayUrl,
        challenge: &'a str,
    ) -> signer::BoxedFuture<'a, std::result::Result<nostr_sdk::prelude::Event, nostr_sdk::prelude::Error>>
    {
        Box::pin(async move {
            let signer =
                signer::active_signer().map_err(nostr_sdk::prelude::Error::other)?;
            Ok(
                nostr_sdk::prelude::ClientAuthentication::new(challenge, relay_url.clone())
                    .finalize_async(&signer)
                    .await?,
            )
        })
    }
}

/// A `ClientBuilder` carrying Vector's client-wide policy: NIP-42 auth plus the transport.
///
/// Callers should start from this rather than `ClientBuilder::new()` so both come along. The
/// transport decides per connection attempt, so relays added later follow the network in use.
pub fn nostr_client_builder() -> nostr_sdk::prelude::ClientBuilder {
    transport::ws::apply_transport(
        nostr_sdk::prelude::ClientBuilder::new().authenticator(VectorAuthenticator),
        transport::Lane::Account,
    )
}

pub use transport::ws::{apply_transport, transport_relay_options};

/// Register a relay with the pool's own auto-reconnect disabled.
///
/// Vector drives every reconnect from its reconcile loop, because it needs the
/// connection lifecycle to be observable and to sequence with health checks and
/// the Tor transport switch. The pool's retry is invisible to all of that, so two
/// schedules end up fighting over one socket.
///
/// This exists as a helper rather than a per-call `.reconnect(false)` because
/// `reconnect` is the one relay option `ClientBuilder` cannot default: it lives
/// only on `RelayOptions`, so every registration site has to opt out by hand, and
/// most of them silently didn't.
pub trait ClientRelayExt {
    /// `Client::add_relay` with `reconnect(false)` already applied.
    fn add_managed_relay<'client, 'url, U>(
        &'client self,
        url: U,
    ) -> nostr_sdk::prelude::AddRelay<'client, 'url>
    where
        U: Into<nostr_sdk::prelude::RelayUrlArg<'url>>;
}

impl ClientRelayExt for nostr_sdk::prelude::Client {
    fn add_managed_relay<'client, 'url, U>(
        &'client self,
        url: U,
    ) -> nostr_sdk::prelude::AddRelay<'client, 'url>
    where
        U: Into<nostr_sdk::prelude::RelayUrlArg<'url>>,
    {
        self.add_relay(url).reconnect(false)
    }
}

/// Re-send every live subscription this relay is supposed to carry, after VECTOR
/// reconnected it.
///
/// Vector owns every reconnect (`add_managed_relay` ⇒ `reconnect(false)`), and the
/// pool re-applies live subs only inside its own retry path — which is exactly the
/// path that was turned off. So a dropped socket comes back carrying NOTHING, and a
/// catch-up fetch is not a subscription: the data lands once and then the stream is
/// silent forever. Only an AUTH-gating relay healed, via its post-challenge re-send.
///
/// Driven off the pool's own subscription table rather than a list of known
/// subscriptions, so a future subscription is covered without touching this. Only
/// ids the pool already associates with `relay` are re-sent, so a relay-targeted
/// subscription is never widened onto a relay it deliberately excluded. Same-id
/// REQs are idempotent. Sent as raw REQs: the pool refuses to subscribe an id it
/// already holds.
pub async fn resubscribe_relay_after_reconnect(
    client: &nostr_sdk::prelude::Client,
    relay: &nostr_sdk::prelude::RelayUrl,
) {
    use std::borrow::Cow;
    crate::community::v2::realtime::note_resubscribe();
    let Ok(Some(handle)) = client.relay(relay).await else { return };
    let (mut sent, mut failed) = (0usize, 0usize);
    for (id, per_relay) in client.subscriptions().await {
        let Some(filters) = per_relay.get(relay) else { continue };
        if filters.is_empty() {
            continue;
        }
        let req = nostr_sdk::prelude::ClientMessage::Req {
            subscription_id: Cow::Borrowed(&id),
            filters: filters.iter().map(Cow::Borrowed).collect(),
        };
        match handle.send_msg(req).await {
            Ok(()) => sent += 1,
            Err(_) => failed += 1,
        }
    }
    println!("[subs] {relay}: re-sent {sent} live sub(s), {failed} refused");
    // What a relay closed was never in the pool to re-send.
    live_subs::heal(client).await;
}

/// A relay connect budget for the transport in use: the caller's clearnet value, raised to the
/// chosen kind's floor.
///
/// Clearnet TCP+TLS settles in well under a second, so the tight per-call budgets are right
/// there. Under an anonymity network those budgets expire mid-circuit, and because the
/// health-check and reconcile loops treat a timeout as "unhealthy" they disconnect and retry,
/// so a relay would churn and never connect.
pub fn relay_connect_timeout(clearnet: std::time::Duration) -> std::time::Duration {
    transport::budget(transport::Op::RelayConnect, clearnet)
}

/// A relay round-trip budget for the transport in use. A relay that answers a probe in 200ms
/// direct can take many seconds through three hops.
pub fn relay_request_timeout(clearnet: std::time::Duration) -> std::time::Duration {
    transport::budget(transport::Op::RelayRequest, clearnet)
}

/// The transport for any `ClientBuilder`, as the user's own lane.
#[deprecated(note = "use vector_core::apply_transport(builder, lane)")]
pub fn apply_tor_proxy(
    builder: nostr_sdk::prelude::ClientBuilder,
) -> nostr_sdk::prelude::ClientBuilder {
    apply_transport(builder, transport::Lane::Account)
}

/// A publish waiting on the transport's budget for its OK and NIP-42 challenge: the SDK's
/// fixed 10 s marks a Tor-slow publish failed while the relay is still answering.
pub fn transport_aware<'c, 'e, 'u>(
    send: nostr_sdk::client::SendEvent<'c, 'e, 'u>,
) -> nostr_sdk::client::SendEvent<'c, 'e, 'u> {
    let wait = relay_request_timeout(std::time::Duration::from_secs(10));
    send.ok_timeout(wait).authentication_timeout(wait)
}

/// Relay options carrying the transport, for clients the SDK builds itself (NIP-46).
#[deprecated(note = "use vector_core::transport_relay_options()")]
pub fn tor_relay_options() -> nostr_sdk::prelude::RelayOptions {
    transport_relay_options()
}

/// Sign an `EventBuilder` with the session signer, refusing an event no relay would store.
///
/// Stands in for 0.44's `Client::sign_event_builder`, which went away when the
/// client stopped owning a signer.
pub async fn sign_builder(
    builder: nostr_sdk::prelude::EventBuilder,
) -> std::result::Result<nostr_sdk::prelude::Event, String> {
    let signer = signer::active_signer()?;
    let event = builder
        .finalize_async(&signer)
        .await
        .map_err(|e| e.to_string())?;
    event_size::check(&event)?;
    Ok(event)
}

/// Sign an `EventBuilder` with the session signer and publish it.
///
/// Stands in for 0.44's `Client::send_event_builder`.
pub async fn sign_and_send(
    client: &nostr_sdk::prelude::Client,
    builder: nostr_sdk::prelude::EventBuilder,
) -> std::result::Result<nostr_sdk::prelude::SendEventOutput, String> {
    let event = sign_builder(builder).await?;
    transport_aware(client.send_event(&event))
        .await
        .map_err(|e| e.to_string())
}

/// Read `filter` from the user's read relays, or `Err` unless at least one relay reached EOSE.
///
/// The SDK's fetch reports a timeout, a disconnect and a refusal as an empty success, so it
/// cannot tell "you hold none" from "nobody answered". A read-modify-write needs the difference.
pub async fn fetch_answered(
    client: &nostr_sdk::prelude::Client,
    filter: nostr_sdk::prelude::Filter,
    timeout: std::time::Duration,
) -> std::result::Result<Vec<nostr_sdk::prelude::Event>, String> {
    use community::transport::{fetch_relay_eose_filters, EoseFail};
    use nostr_sdk::prelude::RelayStatus;
    let relays = client.relays().with_capabilities(nostr_sdk::prelude::RelayCapabilities::READ).await;
    // Reconnects are ours, so a terminated relay would only burn the whole timeout.
    let live: Vec<_> = relays
        .iter()
        .filter(|(_, r)| !matches!(r.status(), RelayStatus::Terminated | RelayStatus::Shutdown | RelayStatus::Banned))
        .map(|(url, _)| url)
        .collect();
    if live.is_empty() {
        return Err("no relays to read from".to_string());
    }
    let reads = live.into_iter().map(|url| {
        let url = url.to_string();
        let filter = filter.clone();
        async move {
            match fetch_relay_eose_filters(client, &url, vec![filter.clone()], timeout).await {
                // A CLOSED is usually auth-required; the authenticator answers it, so ask once more.
                Err(EoseFail::Closed) => {
                    crate::rt::time::sleep(std::time::Duration::from_millis(800)).await;
                    fetch_relay_eose_filters(client, &url, vec![filter], timeout).await
                }
                other => other,
            }
        }
    });
    let mut answered = false;
    let mut seen = std::collections::HashSet::new();
    let mut events = Vec::new();
    for read in futures_util::future::join_all(reads).await.into_iter().flatten() {
        answered = true;
        events.extend(read.into_iter().filter(|e| seen.insert(e.id)));
    }
    if !answered {
        return Err("none of your relays answered".to_string());
    }
    Ok(events)
}

/// The newest of a replaceable event's copies: highest `created_at`, then lowest id, as relays keep.
pub fn newest_replaceable(events: Vec<nostr_sdk::prelude::Event>) -> Option<nostr_sdk::prelude::Event> {
    events.into_iter().min_by(|a, b| b.created_at.cmp(&a.created_at).then_with(|| a.id.cmp(&b.id)))
}

/// Seal, wrap and publish a rumor to `receiver`.
///
/// Stands in for 0.44's `Client::gift_wrap` / `gift_wrap_to`, which went away
/// with the client's signer. An empty `relays` publishes pool-wide, matching
/// `gift_wrap`; a non-empty one targets those relays, matching `gift_wrap_to`.
pub async fn send_gift_wrap<'u, I, U, T>(
    client: &nostr_sdk::prelude::Client,
    relays: I,
    receiver: &nostr_sdk::prelude::PublicKey,
    rumor: nostr_sdk::prelude::UnsignedEvent,
    extra_tags: T,
) -> std::result::Result<nostr_sdk::prelude::SendEventOutput, String>
where
    I: IntoIterator<Item = U>,
    U: Into<nostr_sdk::prelude::RelayUrlArg<'u>>,
    T: IntoIterator<Item = nostr_sdk::prelude::Tag>,
{
    let wrap = signer::gift_wrap(receiver, rumor, extra_tags).await?;
    let targets: Vec<nostr_sdk::prelude::RelayUrlArg<'u>> =
        relays.into_iter().map(Into::into).collect();
    if targets.is_empty() {
        crate::transport_aware(client.send_event(&wrap)).await.map_err(|e| e.to_string())
    } else {
        transport_aware(client.send_event(&wrap))
            .to(targets)
            .await
            .map_err(|e| e.to_string())
    }
}

/// Capabilities for a Community / "external" relay: GOSSIP only.
///
/// GOSSIP is read/write-capable when TARGETED — `can_read()` is
/// `READ|GOSSIP|DISCOVERY` and `can_write()` is `WRITE|GOSSIP`, so per-relay
/// targeted ops pass. But pool-wide ops select READ-only / WRITE-only relays, so
/// the DM/giftwrap subscription and the user's outbox skip GOSSIP relays — the
/// user's own traffic never touches relays they don't own.
///
/// No PING counterpart any more: 0.45 demoted PING from a capability flag to a
/// per-relay option (`AddRelay::ping`) that already defaults to true, with
/// `sleep_when_idle` defaulting to false. The 24/7 keepalive this used to buy is
/// now the default, so it doesn't belong in the capability set.
pub fn community_relay_capabilities() -> nostr_sdk::prelude::RelayCapabilities {
    nostr_sdk::prelude::RelayCapabilities::GOSSIP
}

/// Relay options for a Discovery Relay (see `state::DISCOVERY_RELAYS`): the same
/// GOSSIP|PING targeted-only isolation as Community relays — reachable via
/// `fetch_events_from` / `send_event_to`, invisible to pool-wide DM/profile ops.
/// An overlap with a user relay keeps the user's READ+WRITE flags (`add_relay`
/// no-ops on an already-pooled url).
pub fn discovery_relay_capabilities() -> nostr_sdk::prelude::RelayCapabilities {
    community_relay_capabilities()
}

// === Event Storage ===
pub mod stored_event;

// === Rumor Processing ===
pub mod rumor;

// === Messaging ===
pub mod sending;

// === Per-DM Wallpapers ===
pub mod pinned_chats;
pub mod rail_layout;
pub mod start_menu;
pub mod synced_prefs;
pub mod notify;
pub mod push;
pub mod wallpaper;
pub mod requests;

// === Message Deletion (NIP-09 against retained gift-wraps) ===
pub mod deletion;
pub mod early;
pub mod self_destruct;
pub mod transfer;

// === SIMD Operations ===
pub mod simd;

/// Calls: the platform-free half from `vector-calls`, and with `calls` the session itself.
pub mod calls;

// === Community protocol (GROUP_PROTOCOL.md) ===
pub mod community;

// === Event Handler ===
pub mod event_handler;

// === Re-exports for convenience ===
pub use types::{Message, Attachment, Reaction, EditEntry, ImageMetadata, SiteMetadata, LoginResult, AttachmentFile, mention, extract_mentions};
pub use profile::{Profile, ProfileFlags, SlimProfile, Status};
pub use chat::{Chat, ChatType, ChatMetadata, SerializableChat};
pub use compact::{CompactMessage, CompactMessageVec, NpubInterner};
pub use state::{
    ChatState, MY_SECRET_KEY, STATE, ENCRYPTION_KEY,
    nostr_client, my_public_key, has_active_session,
    set_nostr_client, set_my_public_key,
    take_nostr_client, clear_my_public_key,
    set_pending_bunker_setup, pending_bunker_setup, clear_pending_bunker_setup,
    set_pending_nip55_setup, pending_nip55_setup, clear_pending_nip55_setup,
};
pub use crypto::{GuardedKey, GuardedSigner};
pub use signer::{
    SignerKind, signer_kind, set_signer_kind, is_bunker, is_keyless,
    BUNKER_SIGNER, bunker_signer, set_bunker_signer, take_bunker_signer,
    build_bunker_signer, prewarm_bunker, drain_bunker_state,
    parse_bunker_remote_pubkey, parse_bunker_relays,
    BunkerConnectionState, bunker_state, set_bunker_state,
    VectorAuthUrlHandler, attempt_bunker_login, WatchedBunkerSigner,
    vector_metadata, build_nostrconnect_uri, build_nostrconnect_session,
    VECTOR_APP_NAME, VECTOR_APP_URL, VECTOR_APP_ICON,
};
pub use nip55::{
    Nip55Backend, Nip55Error, Nip55ResolverOutcome, Nip55Signer, Nip55State,
    set_nip55_backend, nip55_backend, nip55_state, set_nip55_state, drain_nip55_state,
    nip55_is_installed, nip55_pair, nip55_perms_json,
    VECTOR_NIP55_SIGN_KINDS, VECTOR_NIP55_ENCRYPT_TYPES,
};
pub use nip07::{Nip07Backend, Nip07Signer, set_nip07_backend, nip07_backend, nip07_get_public_key};
pub use error::{DownloadError, VectorError, Result};

/// What [`VectorCore::download_attachment_reporting`] is doing, as it happens.
#[derive(Debug, Clone, Copy)]
pub enum DownloadStep {
    /// Ciphertext received so far from the current source, and the length it declared.
    /// A source that fails over starts the count again.
    Received { bytes: u64, total: Option<u64> },
    /// Every byte is in; it is being decrypted, or checked against its hash.
    Opening,
}
pub use traits::{EventEmitter, NoOpEmitter, set_event_emitter, emit_event};
pub use db::{set_app_data_dir, get_app_data_dir};
pub use sending::{SendCallback, NoOpSendCallback, SendConfig, SendResult};
pub use deletion::{delete_own_dm, delete_received_dm, DeleteOutcome};
pub use stored_event::{StoredEvent, StoredEventBuilder, SystemEventType};
pub use rumor::{RumorEvent, RumorContext, ConversationType, RumorProcessingResult, process_rumor};
pub use profile::{SyncPriority, ProfileSyncHandler, NoOpProfileSyncHandler};
pub use event_handler::{InboundEventHandler, LiveOnly, NoOpEventHandler, PreparedEvent, process_event};

use std::path::PathBuf;
use std::sync::Arc;

// ============================================================================
// VectorCore — High-level API
// ============================================================================

/// Configuration for initializing VectorCore.
pub struct CoreConfig {
    /// Path to the app data directory (e.g., ~/.local/share/io.vectorapp/data/)
    pub data_dir: PathBuf,
    /// Optional event emitter for UI integration
    pub event_emitter: Option<Box<dyn EventEmitter>>,
}

/// The main entry point for Vector Core.
///
/// Provides a high-level API for all Vector operations. Internally uses
/// global state (same pattern as the Tauri backend) for compatibility.
///
/// ```no_run
/// use vector_core::{VectorCore, CoreConfig};
/// use std::path::PathBuf;
///
/// # async fn example() -> vector_core::Result<()> {
/// let core = VectorCore::init(CoreConfig {
///     data_dir: PathBuf::from("/tmp/vector-data"),
///     event_emitter: None,
/// })?;
///
/// // Login with nsec
/// let result = core.login("nsec1...", None).await?;
/// println!("Logged in as {}", result.npub);
/// # Ok(())
/// # }
/// ```
#[derive(Clone, Copy)]
pub struct VectorCore;

/// How a post goes out. The default is a plain post, with pictures compressed.
///
/// ```
/// let opts = vector_core::PostOptions::default().reply_to("ab12…").expires_in(600);
/// let original = vector_core::PostOptions::default().compress(false);
/// ```
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct PostOptions {
    /// The message this one replies to.
    pub reply_to: Option<String>,
    /// Seconds until it deletes itself for everyone (NIP-40).
    pub expires_in_secs: Option<u64>,
    /// The one bot (npub or hex) a command is meant for, when several answer the same name.
    pub bot: Option<String>,
    /// The text under a file. Ignored for a text post, whose content is the text.
    pub caption: Option<String>,
    /// A picture sent as a file is fitted to 2560px and re-encoded first, which also strips its
    /// metadata (camera, GPS). Off sends the file's bytes as they are.
    pub compress: bool,
}

impl Default for PostOptions {
    fn default() -> Self {
        PostOptions { reply_to: None, expires_in_secs: None, bot: None, caption: None, compress: true }
    }
}

impl PostOptions {
    pub fn compress(mut self, on: bool) -> Self {
        self.compress = on;
        self
    }

    pub fn reply_to(mut self, message_id: impl Into<String>) -> Self {
        self.reply_to = Some(message_id.into());
        self
    }

    pub fn expires_in(mut self, secs: u64) -> Self {
        self.expires_in_secs = Some(secs);
        self
    }

    pub fn to_bot(mut self, bot: impl Into<String>) -> Self {
        self.bot = Some(bot.into());
        self
    }

    pub fn caption(mut self, text: impl Into<String>) -> Self {
        self.caption = Some(text.into());
        self
    }
}

/// A file as it goes out: a picture compressed when `compress` says so, its name following
/// the format it became. One too large to compress goes with its metadata cut out instead, and
/// one that can't be stripped either is refused: compressing promises no metadata leaves.
/// Anything that isn't a picture goes as it is.
pub(crate) async fn ready_to_send(bytes: Vec<u8>, filename: &str, compress: bool) -> Result<(Vec<u8>, String)> {
    if !compress || image::guess_format(&bytes).is_err() || crate::svg::looks_like_svg(&bytes) {
        return Ok((bytes, filename.to_string()));
    }
    let prepared = crate::rt::spawn_blocking(move || {
        crate::image_prep::prepare(&bytes, crate::image_prep::ImageUse::Photo).or_else(|e| crate::image_prep::strip(&bytes).ok_or(e))
    })
    .await
    .map_err(|e| VectorError::Other(format!("image: {e}")))?
    .map_err(|e| VectorError::Other(format!("{e}; send it uncompressed to share it as it is")))?;
    let path = std::path::Path::new(filename);
    let same = path.extension().and_then(|e| e.to_str()).is_some_and(|e| {
        let e = e.to_ascii_lowercase();
        e == prepared.extension || (prepared.extension == "jpg" && e == "jpeg")
    });
    let name = if same { filename.to_string() } else { path.with_extension(prepared.extension).to_string_lossy().into_owned() };
    Ok((prepared.bytes, name))
}

/// How a new Community starts. The default is one `#general` Channel on the active relays.
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct NewCommunity {
    pub description: Option<String>,
    /// The first Channel's name, `general` when unset.
    pub first_channel: Option<String>,
    /// Where it lives; empty means the account's active relays.
    pub relays: Vec<String>,
}

impl NewCommunity {
    pub fn description(mut self, text: impl Into<String>) -> Self {
        self.description = Some(text.into());
        self
    }

    pub fn first_channel(mut self, name: impl Into<String>) -> Self {
        self.first_channel = Some(name.into());
        self
    }

    pub fn relays(mut self, relays: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.relays = relays.into_iter().map(Into::into).collect();
        self
    }
}

/// How a new Channel starts. The default is a public chat Channel at the top level.
#[derive(Debug, Clone, Default)]
#[non_exhaustive]
pub struct NewChannel {
    /// A key of its own: only those let in can read it.
    pub private: bool,
    pub category_id: Option<String>,
    /// `chat` (the default), `forum` or `voice`.
    pub view: Option<String>,
    pub topic: Option<String>,
}

impl NewChannel {
    pub fn private(mut self) -> Self {
        self.private = true;
        self
    }

    pub fn in_category(mut self, category_id: impl Into<String>) -> Self {
        self.category_id = Some(category_id.into());
        self
    }

    pub fn view(mut self, view: impl Into<String>) -> Self {
        self.view = Some(view.into());
        self
    }

    pub fn topic(mut self, topic: impl Into<String>) -> Self {
        self.topic = Some(topic.into());
        self
    }
}

/// What a public invite link shows before joining.
#[derive(Debug, Clone, serde::Serialize)]
#[non_exhaustive]
pub struct LinkPreview {
    pub community_id: String,
    pub name: String,
    pub description: Option<String>,
    /// The icon's encrypted blob reference.
    pub icon: Option<crate::community::CommunityImage>,
    /// Already a member: the preview is what this device holds.
    pub joined: bool,
    /// Read from the Community itself. When false, the name, description and icon are what the
    /// link's creator wrote, unproven: show them as a claim, if at all.
    pub verified: bool,
}

/// Which live subscription an event came in on.
enum LiveRoute {
    Dm,
    CommunityV2,
}

/// Stands for every relay in what a listener's catch-up owes.
const EVERY_RELAY: &str = "*";

/// What a listener's catch-up runner owes, by session: see [`VectorCore::owe_catch_up`].
#[derive(Default)]
struct Owed {
    session: u64,
    communities: bool,
    dms: bool,
    relays: std::collections::HashMap<String, u64>,
    running: bool,
}

// Keyed by session id, as `news` is: the runner and its callers may hold different Session objects.
static CATCH_UPS: std::sync::LazyLock<std::sync::Mutex<Owed>> = std::sync::LazyLock::new(Default::default);

/// Who fetches what was published while a `listen` client was offline.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CatchUp {
    /// `listen` folds state, back-fills every channel and syncs DMs before its
    /// Community subscriptions go live (DMs go live first, so nothing sent during
    /// the sync is missed), and again on each reconnect: a bot starts from a
    /// complete picture.
    Inline,
    /// `listen` goes live at once and leaves the gap to the caller, which pages
    /// it behind the live subscriptions (a UI that paints as history lands).
    External,
}

/// A community image no edition names any more, off its media server. Only its uploader's delete
/// is honoured there, so another admin's upload stays, encrypted, under a key only members held.
fn drop_community_image(url: Option<String>, kept: Option<&str>) {
    let Some(url) = url.filter(|u| Some(u.as_str()) != kept) else { return };
    if let Ok(signer) = crate::signer::active_signer() {
        crate::blossom::delete_blobs_best_effort(signer, vec![url]);
    }
}

/// How many times a count-only backfill pages on from where the relay walk stopped.
const BACKFILL_CONTINUATIONS: usize = 3;

/// Epochs below the live one a catch-up with no proof reads.
const UNPROVEN_EPOCHS: u64 = 2;

/// What one catch-up page cost and what it yielded.
///
/// `fetched` is the relay's answer — zero means there is genuinely nothing
/// further back, which is the only sound "reached the start" signal.
/// `new_messages` counts what this client had never seen, which is what a UI
/// reports; a page of entirely-known history is 0 new with a non-empty fetch.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct BackfillCount {
    pub fetched: usize,
    pub new_messages: usize,
    /// Where an older page goes on from (Unix seconds) when this one stopped with relay history
    /// still unread; `None` when it reached what it was after.
    pub next_before: Option<u64>,
    /// No relay answered: nothing is known about what lies past the cursor.
    pub unreachable: bool,
}

impl VectorCore {
    /// Initialize Vector Core with the given configuration.
    pub fn init(config: CoreConfig) -> Result<Self> {
        // Set data directory
        db::set_app_data_dir(config.data_dir);

        // Set event emitter (or no-op)
        if let Some(emitter) = config.event_emitter {
            traits::set_event_emitter(emitter);
        }

        // Install rustls ring provider
        #[cfg(not(target_arch = "wasm32"))]
        let _ = rustls::crypto::ring::default_provider().install_default();

        net::raise_fd_limit();

        Ok(VectorCore)
    }

    /// Get all available accounts.
    pub fn accounts(&self) -> Result<Vec<String>> {
        db::get_accounts().map_err(VectorError::from)
    }

    /// Login with an nsec key or mnemonic seed phrase.
    pub async fn login(&self, key: &str, password: Option<&str>) -> Result<LoginResult> {
        use nostr_sdk::prelude::*;

        // Parse the key
        let keys = if key.starts_with("nsec1") {
            let secret = SecretKey::from_bech32(key)
                .map_err(|e| VectorError::Nostr(format!("Invalid nsec: {}", e)))?;
            Keys::new(secret)
        } else {
            // Treat as mnemonic (NIP-06: derive from BIP-39 seed)
            Keys::from_mnemonic(key, None)
                .map_err(|e| VectorError::Nostr(format!("Key derivation failed: {}", e)))?
        };

        let public_key = keys.public_key();
        let npub = public_key.to_bech32()
            .map_err(|e| VectorError::Nostr(format!("Failed to encode npub: {}", e)))?;

        // Store in GuardedKey vault (pass other vaults to protect during decoy writes)
        let secret_bytes = keys.secret_key().to_secret_bytes();
        state::MY_SECRET_KEY.set(secret_bytes, &[&state::ENCRYPTION_KEY]);
        state::set_my_public_key(public_key);

        // Initialize database for this account
        db::set_current_account(npub.clone())?;
        db::init_database(&npub)?;

        // Store nsec for encryption setup
        {
            let nsec = keys.secret_key().to_bech32()
                .map_err(|e| VectorError::Nostr(format!("Failed to encode nsec: {}", e)))?;
            *state::PENDING_NSEC.lock().unwrap() = Some(nsec.clone());

            // NEVER clobber an existing encrypted key with the plaintext nsec. An account with encryption
            // enabled keeps its key encrypted-at-rest (PIN-derived); overwriting it with the raw nsec — e.g.
            // a no-password headless/diagnostic login (the concord CLI) — would leave the GUI deriving the
            // right key from the correct PIN but trying to decrypt a value that's no longer ciphertext, i.e.
            // "incorrect pin" with the real key effectively lost. MY_SECRET_KEY is already set in-memory above,
            // so login works regardless; only persist the raw key when there's no encrypted key to protect.
            let existing_encrypted = db::get_pkey().ok().flatten().is_some_and(|v| !v.starts_with("nsec1"));
            if !(state::resolve_encryption_enabled_from_db() && existing_encrypted) {
                db::set_pkey(&nsec)?;
            }
        }

        // Use the canonical resolver so this high-level API agrees with
        // crypto::is_encryption_enabled and the Android bg-sync probe.
        let has_encryption = state::resolve_encryption_enabled_from_db();

        if has_encryption {
            if let Some(pwd) = password {
                // The vault takes the key only once it proves against this account's material:
                // a wrong password here would seal everything this session writes under it.
                // No salt upgrade here: a tool can share a data dir with a running app, which
                // upgrades at its own unlock.
                let kdf = crate::crypto::Kdf::of_account().map_err(VectorError::Crypto)?;
                let key = zeroize::Zeroizing::new(crate::crypto::derive_key(pwd, &kdf).await);
                crate::crypto::install_unlocked_key(&key, &kdf).map_err(VectorError::Crypto)?;
            }
        }
        // Seed the atomic unconditionally — `is_encryption_enabled_fast()`
        // must agree with the DB regardless of branch.
        state::init_encryption_enabled();

        // Build Nostr client — tor-aware options so a headless consumer with
        // the Tor pref ON proxies (or blackholes) instead of dialing direct.
        let client = crate::nostr_client_builder()
            // Relay health monitor — powers the reconnect-driven catch-up in `listen()`.
            .monitor(Monitor::new(1024))
            .build();

        // Add trusted relays
        for relay in state::TRUSTED_RELAYS {
            client.add_managed_relay(*relay).await.ok();
        }

        // Connect
        client.connect().await;

        let _ = { state::set_nostr_client(client); Ok::<(), ()>(()) };

        Ok(LoginResult { npub, has_encryption })
    }

    /// Generate a fresh random account secret key (bech32 nsec). Lets a headless client spin up a
    /// brand-new identity (`add_account` with no key) without depending on nostr-sdk directly.
    pub fn generate_nsec(&self) -> Result<String> {
        use nostr_sdk::prelude::*;
        Keys::generate().secret_key().to_bech32()
            .map_err(|e| VectorError::Nostr(format!("Failed to encode nsec: {}", e)))
    }

    /// Send a NIP-17 gift-wrapped text DM using the full pipeline. Retries a
    /// transient publish miss (headless preset, 3 attempts) so an SDK/CLI bot rides
    /// out a relay blip instead of silently dropping the message on the first miss;
    /// `self_send: false` keeps it a plain send (no inbox self-copy).
    pub async fn send_dm(&self, to_npub: &str, content: &str) -> Result<sending::SendResult> {
        let config = SendConfig { self_send: false, ..SendConfig::headless() };
        sending::send_dm(to_npub, content, None, &config, Arc::new(NoOpSendCallback)).await
            .map_err(VectorError::Other)
    }

    /// Send a DM as a threaded reply to `replied_to` (an existing message's event id).
    pub async fn send_dm_reply(&self, to_npub: &str, replied_to: &str, content: &str) -> Result<sending::SendResult> {
        let config = SendConfig { self_send: false, ..SendConfig::headless() };
        sending::send_dm(to_npub, content, Some(replied_to), &config, Arc::new(NoOpSendCallback)).await
            .map_err(VectorError::Other)
    }

    /// Download a received attachment and decrypt it to plaintext bytes. Fetches the encrypted blob
    /// from its Blossom URL (SSRF/Tor-aware client, size-capped) and AES-decrypts with the
    /// attachment's embedded key + nonce. Walks the primary URL then any BUD-04 `fallback`
    /// mirrors (same ciphertext on other hosts) until one serves. Prefer
    /// [`download_attachment_from`](Self::download_attachment_from) when the message author is
    /// known — it adds the BUD-03 hash-swap over the author's advertised servers.
    pub async fn download_attachment(&self, attachment: &Attachment) -> Result<Vec<u8>> {
        self.download_attachment_from(attachment, None).await
    }

    /// [`download_attachment`](Self::download_attachment) with the full source walk: primary URL →
    /// embedded `fallback` mirrors → BUD-03 hash-swap (the same content-address on each of the
    /// author's kind-10063 servers). `author_npub` is the message author (your own npub for your
    /// own messages); `None` skips the hash-swap stage.
    pub async fn download_attachment_from(
        &self,
        attachment: &Attachment,
        author_npub: Option<&str>,
    ) -> Result<Vec<u8>> {
        self.download_attachment_within(attachment, author_npub, 256 * 1024 * 1024)
            .await
            .map_err(|e| VectorError::Other(e.to_string()))
    }

    /// [`download_attachment_from`](Self::download_attachment_from), refusing more
    /// than `max_bytes` of ciphertext: the size an attachment declares is the
    /// sender's word, so the cap holds on the bytes actually received.
    pub async fn download_attachment_within(
        &self,
        attachment: &Attachment,
        author_npub: Option<&str>,
        max_bytes: usize,
    ) -> std::result::Result<Vec<u8>, DownloadError> {
        self.download_attachment_reporting(attachment, author_npub, max_bytes, |_| true).await
    }

    /// [`download_attachment_within`](Self::download_attachment_within), telling `step` what the
    /// walk is doing as it happens. `step` returning false stops it with
    /// [`DownloadError::Cancelled`] at the next chunk.
    pub async fn download_attachment_reporting<F: FnMut(DownloadStep) -> bool>(
        &self,
        attachment: &Attachment,
        author_npub: Option<&str>,
        max_bytes: usize,
        mut step: F,
    ) -> std::result::Result<Vec<u8>, DownloadError> {
        use futures_util::StreamExt;
        let max_download = max_bytes;
        if attachment.url.is_empty() {
            return Err(DownloadError::Unusable("attachment has no URL".into()));
        }
        // Bounded by progress, not by a deadline: any rate finishes, a stall fails over.
        let client = crate::net::build_http_client_with_options(
            None,
            Some(crate::net::transfer_stall()),
            true,
        )
        .map_err(DownloadError::Unreachable)?;
        let mut last_err = String::from("download failed");
        // Waits for the network to come back after a switch; bounded so a flapping network can't
        // hold the download forever.
        let mut network_waits = 0u8;
        // Whether every source answered: only then is a failure the message's own.
        let mut all_answered = true;
        let mut candidates: Vec<String> = vec![attachment.url.clone()];
        candidates.extend(attachment.fallback_urls.iter().cloned());
        let mut hash_swap_tried = false;
        let mut i = 0;
        'sources: while i < candidates.len() {
            let url = candidates[i].clone();
            i += 1;
            // One-time last resort once every embedded source has failed: the author's advertised
            // servers may hold the blob under the same content-address.
            let extend_with_swap = |candidates: &mut Vec<String>, servers: &[String]| {
                let extra = crate::blossom::hash_swap_candidates(&attachment.url, servers);
                for c in extra {
                    if !candidates.contains(&c) {
                        candidates.push(c);
                    }
                }
            };
            macro_rules! next_source {
                () => {{
                    log_net_fail!("[Download] source failed ({}): {}", url, last_err);
                    if i == candidates.len() && !hash_swap_tried {
                        hash_swap_tried = true;
                        let servers = crate::blossom_servers::author_swap_servers(author_npub, false).await;
                        extend_with_swap(&mut candidates, &servers);
                    }
                    continue 'sources;
                }};
            }
            // SSRF guard: URLs are attacker-controlled (off an inbound message). build_http_client
            // only validates redirect HOPS, not the initial request — so validate each source here
            // (matches the native download path). With Tor off this is the only egress guard.
            if let Err(e) = crate::net::validate_url_not_private(&url) {
                last_err = e.to_string();
                next_source!();
            }
            macro_rules! network_changed {
                ($e:expr) => {{
                    if $e.is_transient() && network_waits < 8 {
                        network_waits += 1;
                        match crate::net::wait_after(&$e).await {
                            Ok(()) => {
                                i -= 1;
                                continue 'sources;
                            }
                            // Every other source sits behind the same network: none would fare better.
                            Err(text) => return Err(DownloadError::Unreachable(text)),
                        }
                    }
                }};
            }
            let resp = match crate::net::proxied_request(&client, reqwest::Method::GET, &url).await.send().await {
                Ok(r) => r,
                Err(e) => {
                    network_changed!(e);
                    last_err = format!("download: {e}");
                    all_answered = false;
                    next_source!();
                }
            };
            if !resp.status().is_success() {
                last_err = format!("download failed: HTTP {}", resp.status());
                all_answered = false;
                next_source!();
            }
            // Stream with a cap so a hostile/oversized blob can't OOM the process. The cap is
            // permanent — every mirror serves the same blob, so don't bother trying the next.
            let mut encrypted: Vec<u8> = Vec::with_capacity(
                // The declared length is the server's word: reserve no more than a few MiB on it.
                resp.content_length().map(|l| usize::try_from(l).unwrap_or(usize::MAX).min(max_download).min(4 * 1024 * 1024)).unwrap_or(64 * 1024),
            );
            let total = resp.content_length();
            if !step(DownloadStep::Received { bytes: 0, total }) {
                return Err(DownloadError::Cancelled);
            }
            let mut stream = resp.bytes_stream();
            loop {
                // Every declared byte is here: done, without waiting on an end of body WebKit can hold back.
                if total.is_some_and(|t| encrypted.len() as u64 >= t) {
                    break;
                }
                // A browser's fetch has no read timeout: a body that goes silent fails over here instead.
                #[cfg(target_arch = "wasm32")]
                let next = match crate::rt::time::timeout(crate::transport::budget(crate::transport::Op::HttpRead, crate::net::transfer_stall()), stream.next()).await {
                    Ok(next) => next,
                    Err(_) => {
                        last_err = "read body: stalled".to_string();
                        all_answered = false;
                        next_source!();
                    }
                };
                #[cfg(not(target_arch = "wasm32"))]
                let next = stream.next().await;
                let Some(chunk) = next else { break };
                let chunk = match chunk {
                    Ok(c) => c,
                    Err(e) => {
                        network_changed!(e);
                        last_err = format!("read body: {e}");
                        all_answered = false;
                        next_source!();
                    }
                };
                if encrypted.len() + chunk.len() > max_download {
                    return Err(DownloadError::TooLarge(max_download));
                }
                encrypted.extend_from_slice(&chunk);
                if !step(DownloadStep::Received { bytes: encrypted.len() as u64, total }) {
                    return Err(DownloadError::Cancelled);
                }
            }
            if !step(DownloadStep::Opening) {
                return Err(DownloadError::Cancelled);
            }
            // Plaintext public blob (no decryption tags): its content address and the sender's
            // claim are the only integrity checks there are.
            if attachment.key.is_empty() || attachment.nonce.is_empty() {
                let hash = crate::crypto::sha256_hex(&encrypted);
                if crate::blossom::plaintext_matches(&url, attachment.original_hash.as_deref(), &hash) {
                    return Ok(encrypted);
                }
                last_err = "plaintext blob fails its hash claim".to_string();
                next_source!();
            }
            match crate::crypto::decrypt_data_owned(encrypted, &attachment.key, &attachment.nonce) {
                Ok(plain) => {
                    if i > 1 {
                        log_net_info!("[Download] fallback source {}/{} served {}", i, candidates.len(), url);
                    }
                    return Ok(plain);
                }
                Err(e) => {
                    // A host serving wrong bytes under the right URL must not
                    // veto sources still holding the real ciphertext.
                    last_err = format!("decrypt: {e}");
                    next_source!();
                }
            }
        }
        log_net_fail!("[Download] all {} source(s) failed for {}: {}", candidates.len(), attachment.url, last_err);
        Err(if all_answered { DownloadError::Unusable(last_err) } else { DownloadError::Unreachable(last_err) })
    }

    /// The size of an attachment that arrived without one, asked of its server as a download
    /// would ask it, and recorded on the message so auto-download can weigh it. `None` when the
    /// server won't say, or the message is a request not yet answered.
    pub async fn probe_attachment_size(&self, message_id: &str, attachment_id: &str) -> Option<u64> {
        crate::db::scoped(async move {
            let (chat_id, message) = self.get_message(message_id).await?;
            let att = message.attachments.iter().find(|a| a.id == attachment_id)?;
            if att.size > 0 {
                return Some(att.size);
            }
            if !(att.url.starts_with("https://") || att.url.starts_with("http://")) {
                return None;
            }
            if !message.mine && crate::requests::shielded() && state::STATE.lock().await.dm_unanswered(&chat_id) {
                return None;
            }
            let probe = crate::net::get_remote_file_size(&att.url);
            let size = crate::rt::time::timeout(crate::net::tor_http_timeout(std::time::Duration::from_secs(5)), probe).await.ok().flatten()?;
            if let Err(e) = db::attachments::set_attachment_size(message_id, attachment_id, size) {
                crate::log_warn!("[Attachments] could not record a probed size: {e}");
            }
            state::STATE.lock().await.update_attachment(&chat_id, message_id, attachment_id, |a| a.size = size);
            Some(size)
        })
        .await
    }

    /// Send a NIP-17 gift-wrapped file attachment DM.
    pub async fn send_file(&self, to_npub: &str, file_path: &str) -> Result<sending::SendResult> {
        let path = std::path::Path::new(file_path);
        let bytes = std::fs::read(path)
            .map_err(VectorError::Io)?;
        let filename = path.file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("file");
        let extension = path.extension()
            .and_then(|e| e.to_str())
            .unwrap_or("bin");

        sending::send_file_dm(
            to_npub,
            std::sync::Arc::new(bytes),
            filename,
            extension,
            None,
            None,
            &SendConfig::default(),
            Arc::new(NoOpSendCallback),
        ).await.map_err(VectorError::Other)
    }

    /// Send bytes held in memory as a DM file named `filename`, whose extension sets its type.
    /// `opts` carries the caption, the reply, and whether a picture is compressed; a DM has no
    /// per-message expiry, so one set there is refused.
    pub async fn send_file_bytes(&self, to_npub: &str, bytes: Vec<u8>, filename: &str, opts: &PostOptions) -> Result<sending::SendResult> {
        if opts.expires_in_secs.is_some() {
            return Err(VectorError::Other("DMs have no per-message expiry".into()));
        }
        let (bytes, filename) = ready_to_send(bytes, filename, opts.compress).await?;
        let extension = std::path::Path::new(&filename).extension().and_then(|e| e.to_str()).unwrap_or("bin").to_lowercase();
        let config = SendConfig { self_send: false, ..SendConfig::headless() };
        let sent = sending::send_file_dm(to_npub, std::sync::Arc::new(bytes), &filename, &extension, None, opts.reply_to.as_deref(), &config, Arc::new(NoOpSendCallback))
            .await
            .map_err(VectorError::Other)?;
        // A DM file carries no text: the caption follows as a reply to it.
        if let Some(caption) = opts.caption.as_deref().filter(|c| !c.trim().is_empty()) {
            let file_id = sent.event_id.clone().unwrap_or_else(|| sent.pending_id.clone());
            self.send_dm_reply(to_npub, &file_id, caption).await?;
        }
        Ok(sent)
    }

    /// Withdraw one of our own reactions, in a DM or a Community, by the reaction's id.
    pub async fn remove_reaction(&self, reaction_id: &str) -> Result<()> {
        crate::db::scoped(async move {
            use nostr_sdk::prelude::{EventId, PublicKey, ToBech32};
            let session = crate::db::current_session();
            let (chat_id, message_id, author_npub, is_community) =
                Self::locate_reaction(reaction_id).await.ok_or_else(|| VectorError::NotFound(format!("reaction {reaction_id}")))?;
            let me = state::my_public_key().ok_or_else(|| VectorError::NotInitialized("not logged in".into()))?;
            if me.to_bech32().ok().as_deref() != Some(author_npub.as_str()) {
                return Err(VectorError::Other("only its own author can withdraw a reaction".into()));
            }
            // Off this device first, as the app does, so the relay's echo of the delete changes nothing.
            // The kind-7 row goes explicitly: a message save adds reactions, never drops them.
            let updated = state::STATE.lock().await.remove_reaction_from_message(&message_id, reaction_id);
            let _ = crate::db::events::delete_event(reaction_id).await;
            if let Some((_, mut message)) = updated {
                traits::emit_message_update(&chat_id, &message_id, &mut message).await;
            }
            // The delete signs as whoever is live: never as the account that took over.
            if !session.is_live() {
                return Err(VectorError::Other("account changed while withdrawing the reaction".into()));
            }
            if is_community {
                use crate::community::transport::LiveTransport;
                let id = self.v2_community_for_channel(&chat_id)?.ok_or_else(|| VectorError::NotFound("community channel".into()))?;
                let community = crate::db::community::load_community_v2(&id)
                    .map_err(VectorError::Db)?
                    .ok_or_else(|| VectorError::NotFound("community".into()))?;
                let ch = crate::community::ChannelId(Self::id32(&chat_id, "channel_id")?);
                let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
                crate::community::v2::service::delete_own(&transport, &community, &ch, reaction_id, crate::community::v2::kind::REACTION)
                    .await
                    .map_err(VectorError::Other)?;
            } else {
                let rid = EventId::from_hex(reaction_id).map_err(|e| VectorError::Nostr(e.to_string()))?;
                let recipient = PublicKey::parse(&chat_id).map_err(|e| VectorError::Nostr(e.to_string()))?;
                crate::deletion::delete_own_reaction(&rid, recipient).await.map_err(VectorError::Other)?;
            }
            Ok(())
        })
        .await
    }

    /// Where a reaction sits: `(chat id, message id, reactor npub, in a Community)`. Memory first,
    /// then the database, since memory holds only a window of each chat.
    async fn locate_reaction(reaction_id: &str) -> Option<(String, String, String, bool)> {
        if let Some(found) = state::STATE.lock().await.find_reaction(reaction_id) {
            return Some(found);
        }
        let parent = crate::db::events::reaction_target(reaction_id).ok().flatten()?;
        let (chat_id, message) = crate::db::events::get_message_by_id(&parent).await.ok().flatten()?;
        let author = message.reactions.iter().find(|r| r.id == reaction_id)?.author_id.clone();
        let community = crate::db::community::community_id_for_channel(&chat_id).ok().flatten().is_some();
        Some((chat_id, parent, author, community))
    }

    /// Withdraw our own `emoji` reaction to `message_id`, if we hold one. `Ok(false)` when there is none.
    pub async fn remove_my_reaction(&self, message_id: &str, emoji: &str) -> Result<bool> {
        match Self::own_reaction_id(message_id, emoji).await {
            Some(id) => self.remove_reaction(&id).await.map(|_| true),
            None => Ok(false),
        }
    }

    /// The id of our own reaction to `message_id` with `emoji`, if we already have
    /// one. A reaction set is keyed by (author, emoji), so a repeat is something
    /// every receiver collapses anyway: refusing it here spends no publish, no
    /// gift-wrap and no relay round-trip on an event that changes nothing.
    async fn own_reaction_id(message_id: &str, emoji: &str) -> Option<String> {
        use nostr_sdk::prelude::ToBech32;
        let me = state::my_public_key()?.to_bech32().ok()?;
        let resident = state::STATE.lock().await.find_message(message_id).map(|(_, m)| m);
        let message = match resident {
            Some(m) => m,
            None => crate::db::events::get_message_by_id(message_id).await.ok().flatten()?.1,
        };
        message.reactions.iter().find(|r| r.author_id == me && r.emoji == emoji).map(|r| r.id.clone())
    }

    /// Send a NIP-25 reaction to a DM message. `emoji_url` carries the NIP-30
    /// image URL when reacting with a custom-pack emoji (content stays
    /// `:shortcode:`). Returns the reaction's rumor id. Local echo + persistence
    /// are best-effort — the gift-wrap send is the source of truth.
    pub async fn send_reaction(
        &self,
        to_npub: &str,
        reference_id: &str,
        emoji: &str,
        emoji_url: Option<&str>,
    ) -> Result<String> {
        use nostr_sdk::prelude::*;

        let client = state::nostr_client().ok_or(VectorError::Other("Not connected".into()))?;
        let my_public_key = state::my_public_key().ok_or(VectorError::Other("Not logged in".into()))?;

        // Already ours: hand back the reaction we hold rather than minting a second.
        if let Some(existing) = Self::own_reaction_id(reference_id, emoji).await {
            return Ok(existing);
        }

        // Group ceiling + per-tier fresh-reaction allowance (joins always pass)
        badges::check_new_reaction_allowance(reference_id, emoji)
            .await
            .map_err(VectorError::Other)?;

        let reference_event = EventId::from_hex(reference_id)
            .map_err(|e| VectorError::Nostr(e.to_string()))?;
        let receiver_pubkey = PublicKey::from_bech32(to_npub)
            .map_err(|e| VectorError::Nostr(e.to_string()))?;

        // NIP-30 custom-emoji tag — only when content is `:shortcode:` and a URL is present.
        let custom_emoji_tag = emoji_url.and_then(|url| {
            if !emoji.starts_with(':') || !emoji.ends_with(':') || emoji.len() < 3 || url.is_empty() {
                return None;
            }
            let shortcode = &emoji[1..emoji.len() - 1];
            if shortcode.is_empty() { return None; }
            Some(Tag::custom("emoji", [shortcode.to_string(), url.to_string()]))
        });

        let reaction_target = nostr_sdk::prelude::nip25::ReactionTarget {
            event_id: reference_event,
            public_key: receiver_pubkey,
            coordinate: None,
            kind: Some(Kind::PrivateDirectMessage),
            relay_hint: None,
        };
        let mut builder =
            nostr_sdk::prelude::nip25::ReactionBuilder::new(reaction_target, emoji)
                .into_event_builder();
        if let Some(tag) = custom_emoji_tag {
            builder = builder.tag(tag);
        }
        let rumor = builder.finalize_unsigned_with_id(my_public_key);
        let inner_rumor_id = rumor.id;
        let rumor_id = inner_rumor_id.ok_or(VectorError::Other("Failed to get rumor ID".into()))?.to_hex();

        // Retain the recipient wrap's ephemeral key + targeted relays so the
        // reaction can later be revoked with a NIP-09 relay nuke (mirrors the
        // DM message send path). Without retention the reaction is undeletable.
        let outcome = inbox_relays::send_gift_wrap_retained(&client, &receiver_pubkey, rumor.clone(), [])
            .await.map_err(VectorError::Other)?;
        if !outcome.output.success.is_empty() {
            if let Some(rid) = inner_rumor_id {
                if let Err(e) = db::nip17_keys::store_wrap_key(
                    &outcome.wrap_event_id, &rid, &receiver_pubkey,
                    db::nip17_keys::WrapRole::Recipient,
                    &outcome.wrap_secret, &outcome.targeted_relays,
                ) {
                    crate::log_warn!("[Reaction] failed to persist wrap key: {}", e);
                }
            }
        }

        // Self-wrap for multi-device recovery + retain its key too, so another
        // device (or this one) can later revoke. Bail on account swap.
        let self_wrap_client = client.clone();
        db::spawn_bound(async move {
            if let Ok(self_outcome) = inbox_relays::send_gift_wrap_retained(
                &self_wrap_client, &my_public_key, rumor, [],
            ).await {
                if !self_outcome.output.success.is_empty() {
                    if let Some(rid) = inner_rumor_id {
                        let _ = db::nip17_keys::store_wrap_key(
                            &self_outcome.wrap_event_id, &rid, &my_public_key,
                            db::nip17_keys::WrapRole::SelfSend,
                            &self_outcome.wrap_secret, &self_outcome.targeted_relays,
                        );
                    }
                }
            }
        });

        // Best-effort optimistic local echo + persistence.
        let reaction = Reaction {
            id: rumor_id.clone(),
            reference_id: reference_id.to_string(),
            author_id: my_public_key.to_bech32().unwrap_or_else(|_| my_public_key.to_hex()),
            emoji: emoji.to_string(),
            emoji_url: emoji_url.map(|s| s.to_string()),
        };
        let msg_for_save = {
            let mut st = state::STATE.lock().await;
            match st.add_reaction_to_message(reference_id, reaction) {
                Some((cid, true)) => st.find_message(reference_id).map(|(_, m)| (cid, m)),
                _ => None,
            }
        };
        if let Some((cid, mut msg)) = msg_for_save {
            let _ = db::events::save_message(&cid, &msg).await;
            traits::emit_message_update(&cid, reference_id, &mut msg).await;
        }

        Ok(rumor_id)
    }

    /// Send an ephemeral typing indicator to a DM recipient. Fire-and-forget
    /// with a 30-second NIP-40 expiry so relays purge it quickly.
    pub async fn send_typing(&self, to_npub: &str) -> Result<()> {
        use nostr_sdk::prelude::*;

        let client = state::nostr_client().ok_or(VectorError::Other("Not connected".into()))?;
        let my_public_key = state::my_public_key().ok_or(VectorError::Other("Not logged in".into()))?;
        let pubkey = PublicKey::from_bech32(to_npub).map_err(|e| VectorError::Nostr(e.to_string()))?;
        // Notes: nobody to tell.
        if pubkey == my_public_key {
            return Ok(());
        }

        let expiry = Timestamp::from_secs(crate::clock::timestamp().as_secs() + 30);
        let rumor = EventBuilder::new(Kind::ApplicationSpecificData, "typing")
            .tag(Tag::public_key(pubkey))
            .tag(Tag::custom("d", vec!["vector"]))
            .tag(Tag::expiration(expiry))
            .finalize_unsigned_with_id(my_public_key);

        // No usable signer stays VectorError::Other, as SDK callers match it; resolving a local
        // key reads a cached owner, not the vault.
        signer::active_signer().map_err(VectorError::Other)?;
        // Client no longer wraps: build the wrap, then publish it to the target relays.
        let wrap = signer::gift_wrap(&pubkey, rumor, [Tag::expiration(expiry)])
            .await
            .map_err(VectorError::Nostr)?;
        transport_aware(client.send_event(&wrap))
            .to(state::active_trusted_relays().await)
            .await
            .map_err(|e| VectorError::Nostr(e.to_string()))?;
        Ok(())
    }

    /// Edit a DM you previously sent (kind-16 edit) with an optimistic local
    /// echo. Returns the edit event id. Persistence is best-effort and only
    /// happens when the chat already exists locally.
    pub async fn edit_dm(&self, to_npub: &str, message_id: &str, new_content: &str) -> Result<String> {
        crate::db::scoped(async move {
            use nostr_sdk::prelude::*;

            let client = state::nostr_client().ok_or(VectorError::Other("Not connected".into()))?;
            let my_public_key = state::my_public_key().ok_or(VectorError::Other("Not logged in".into()))?;
            let my_npub = my_public_key.to_bech32().map_err(|e| VectorError::Nostr(e.to_string()))?;
            let receiver_pubkey = PublicKey::from_bech32(to_npub).map_err(|e| VectorError::Nostr(e.to_string()))?;
            let reference_event = EventId::from_hex(message_id).map_err(|e| VectorError::Nostr(e.to_string()))?;

            let (plain, text_spans) = crate::text_spans::extract_own(new_content);
            let new_content = plain.as_str();
            // NIP-30: resolve `:shortcode:` so the edit carries emoji image tags.
            let emoji_tags = emoji_packs::resolve_outbound_emoji_tags(new_content);
            // On the rumor and the wrap alike, so relays drop the edit with its message.
            let expiry_tags: Vec<Tag> = crate::self_destruct::edit_expiry(message_id)
                .await
                .map_err(VectorError::Other)?
                .map(|exp| Tag::expiration(Timestamp::from_secs(exp)))
                .into_iter()
                .collect();

            let mut builder = EventBuilder::new(
                Kind::from_u16(stored_event::event_kind::MESSAGE_EDIT),
                new_content,
            ).tag(Tag::event(reference_event));
            for et in &emoji_tags {
                builder = builder.tag(Tag::custom(
                    "emoji",
                    [et.shortcode.clone(), et.url.clone()],
                ));
            }
            builder = builder.tags(crate::text_spans::to_nostr_tags(&text_spans));
            let rumor = builder.tags(expiry_tags.clone()).finalize_unsigned_with_id(my_public_key);
            let edit_id = rumor.id.ok_or(VectorError::Other("Failed to get edit rumor ID".into()))?.to_hex();
            let edit_ts_ms = rumor.created_at.as_secs() * 1000;

            // Optimistic local echo + best-effort persistence.
            let msg_for_emit = {
                let mut st = state::STATE.lock().await;
                st.update_message_in_chat_with(to_npub, message_id, |msg, i| {
                    msg.apply_edit(new_content.to_string(), edit_ts_ms, emoji_tags.clone(), text_spans.clone(), i);
                    msg.set_preview_metadata(None);
                })
            };
            if let Some(mut msg) = msg_for_emit {
                traits::emit_message_update(to_npub, message_id, &mut msg).await;
                if let Ok(db_chat_id) = db::id_cache::get_chat_id_by_identifier(to_npub) {
                    let _ = db::events::save_edit_event(
                        &edit_id, message_id, new_content, &emoji_tags, &text_spans, db_chat_id, None, &my_npub,
                    ).await;
                }
            }

            inbox_relays::send_gift_wrap(&client, &receiver_pubkey, rumor.clone(), expiry_tags.clone())
                .await.map_err(VectorError::Other)?;

            let self_wrap_client = client.clone();
            let self_wrap_session = crate::db::current_session();
            db::spawn_bound(async move {
                if !self_wrap_session.is_live() { return; }
                if let Ok(wrap) = signer::gift_wrap(&my_public_key, rumor, expiry_tags).await {
                    let _ = crate::transport_aware(self_wrap_client.send_event(&wrap)).await;
                }
            });

            Ok(edit_id)
        })
        .await
    }

    /// Delete a DM from the network: one you sent ([`deletion::delete_own_dm`]), or your copy of
    /// one you received ([`deletion::delete_received_dm`]). Drops it here too.
    pub async fn delete_dm(&self, message_id: &str) -> Result<deletion::DeleteOutcome> {
        use nostr_sdk::prelude::*;
        let rumor_id = EventId::from_hex(message_id).map_err(|e| VectorError::Nostr(e.to_string()))?;
        let (chat_id, msg) = self.get_message(message_id).await.ok_or_else(|| VectorError::Other("message not found".into()))?;
        if !chat_id.starts_with("npub1") {
            return Err(VectorError::Other("not a DM".into()));
        }
        let outcome = if msg.mine { deletion::delete_own_dm(&rumor_id).await } else { deletion::delete_received_dm(&rumor_id).await }
            .map_err(VectorError::Other)?;
        state::STATE.lock().await.remove_message(message_id);
        let _ = crate::db::events::delete_event(message_id).await;
        traits::emit_event_json("message_removed", serde_json::json!({ "id": message_id, "chat_id": chat_id, "reason": "deleted" }));
        Ok(outcome)
    }

    /// Get chats from the in-memory state.
    pub async fn get_chats(&self) -> Vec<SerializableChat> {
        let state = state::STATE.lock().await;
        state.chats.iter()
            .map(|c| c.to_serializable_with_last_n(1, &state.interner))
            .collect()
    }

    /// Get messages for a chat (paginated).
    pub async fn get_messages(&self, chat_id: &str, limit: usize, offset: usize) -> Vec<Message> {
        let state = state::STATE.lock().await;
        let Some(chat) = state.get_chat(chat_id) else { return Vec::new() };
        let msgs = chat.messages.messages();
        let start = offset.min(msgs.len());
        let end = offset.saturating_add(limit).min(msgs.len());
        msgs[start..end].iter().map(|m| m.to_message(&state.interner)).collect()
    }

    /// One message by id, with the chat it was said in. Reads STATE first, then
    /// the store for a row that has paged out of the loaded window.
    ///
    /// This is what a moderation citation needs: it names a message id and
    /// nothing else, so the room has to come back with it. `None` is an
    /// ordinary answer — a citation outlives its message (a delete, a hide, an
    /// expiry, history never synced), and callers must read absence as absence
    /// rather than as a fault.
    pub async fn get_message(&self, message_id: &str) -> Option<(String, Message)> {
        {
            let state = state::STATE.lock().await;
            if let Some((chat, msg)) = state.find_message(message_id) {
                return Some((chat.id.clone(), msg));
            }
        }
        db::events::get_message_by_id(message_id).await.ok().flatten()
    }

    /// Every message carrying an attachment with this content hash, newest
    /// first. `Attachment.id` IS that hash, and so is a citation's
    /// `content_hash`, so a classifier verdict about a blob resolves straight
    /// back to what carried it.
    ///
    /// A list, not one answer: one blob rides many messages — a forward, a
    /// re-post, or forty accounts posting the same image, which is exactly the
    /// case worth being able to see whole.
    pub async fn get_messages_with_attachment(&self, content_hash: &str) -> Vec<(String, Message)> {
        let Ok(ids) = db::attachments::events_with_attachment_hash(content_hash) else { return Vec::new() };
        let mut out = Vec::with_capacity(ids.len());
        for id in ids {
            if let Some(found) = self.get_message(&id).await {
                out.push(found);
            }
        }
        out
    }

    /// Cursor-paged local read: up to `limit` messages strictly before the
    /// `(at_ms, id)` cursor, chronological. `None` returns the newest `limit`.
    ///
    /// The cursor is compared BY VALUE, never resolved to a stored row, so it
    /// keeps working after its message is gone (NIP-09 delete, moderation hide,
    /// a self-destruct timer) — a persisted cursor must not wedge the walk. The
    /// id tiebreaks inside a same-millisecond burst, giving a total order that
    /// can't skip or re-serve across pages. Local only: sync older history in
    /// from relays first.
    pub async fn get_messages_before(
        &self,
        chat_id: &str,
        before: Option<(u64, &str)>,
        limit: usize,
    ) -> Vec<Message> {
        let state = state::STATE.lock().await;
        let Some(chat) = state.get_chat(chat_id) else {
            return Vec::new();
        };
        page_before(chat.messages.messages(), &state.interner, before, limit)
    }

    /// Get a profile by npub.
    pub async fn get_profile(&self, npub: &str) -> Option<SlimProfile> {
        let state = state::STATE.lock().await;
        state.get_profile(npub)
            .map(|p| SlimProfile::from_profile(p, &state.interner))
    }

    /// Fetch a profile's metadata and status from relays.
    pub async fn load_profile(&self, npub: &str) -> bool {
        profile::sync::load_profile(npub.to_string(), &NoOpProfileSyncHandler).await
    }

    /// Update the current user's profile metadata and broadcast to relays.
    pub async fn update_profile(&self, name: &str, avatar: &str, banner: &str, about: &str) -> bool {
        profile::sync::update_profile(
            name.to_string(), avatar.to_string(), banner.to_string(), about.to_string(),
            &NoOpProfileSyncHandler,
        ).await
    }

    /// Like [`update_profile`](Self::update_profile) but marks the profile as a bot (`bot: true` in
    /// the metadata). The SDK uses this for every bot; build human clients on `update_profile`.
    pub async fn update_bot_profile(&self, name: &str, avatar: &str, banner: &str, about: &str) -> bool {
        profile::sync::update_bot_profile(
            name.to_string(), avatar.to_string(), banner.to_string(), about.to_string(),
            &NoOpProfileSyncHandler,
        ).await
    }

    /// Publish whether the current user consents to being shown on other people's streams.
    /// Returns the value now in effect.
    pub async fn set_stream_consent(&self, on: bool) -> Result<bool> {
        db::scoped_result(profile::sync::set_stream_consent(on, &NoOpProfileSyncHandler))
            .await
            .map_err(VectorError::Other)
    }

    /// Update the current user's status and broadcast to relays.
    pub async fn update_status(&self, status: &str) -> bool {
        profile::sync::update_status(status.to_string()).await
    }

    /// Upload an image file to Blossom **unencrypted** and return its public URL — for avatars,
    /// banners, and other images other clients must fetch directly. (The opposite of
    /// [`send_file`](Self::send_file)'s encrypted attachments.) Pass the URL to [`update_profile`].
    ///
    /// [`update_profile`]: Self::update_profile
    pub async fn upload_public_image(&self, file_path: &str) -> Result<String> {
        let path = std::path::Path::new(file_path);
        let bytes = std::fs::read(path).map_err(VectorError::Io)?;
        if bytes.is_empty() {
            return Err(VectorError::Other("Empty image file".into()));
        }
        let extension = path.extension().and_then(|e| e.to_str()).unwrap_or("bin").to_lowercase();
        let mime = crate::crypto::mime_from_extension(&extension);
        let _client = state::nostr_client().ok_or_else(|| VectorError::Other("Not logged in".into()))?;
        let signer = crate::signer::active_signer()
            .map_err(|e| VectorError::Other(format!("Signer unavailable: {e}")))?;
        let servers = crate::blossom_servers::compute_enabled_servers();
        if servers.is_empty() {
            return Err(VectorError::Other("No Blossom servers configured".into()));
        }
        // Avatars/banners run larger than emojis (up to ~1MB): a server may accept
        // nothing for 20s before it is treated as dead and failover moves on.
        crate::blossom::upload_blob_with_failover(
            signer,
            servers,
            std::sync::Arc::new(bytes),
            Some(mime),
            Some(crate::net::tor_http_timeout(std::time::Duration::from_secs(20))),
        )
        .await
        .map_err(VectorError::Other)
    }

    /// Block a user by npub.
    pub async fn block_user(&self, npub: &str) -> bool {
        profile::sync::block_user(npub.to_string(), &NoOpProfileSyncHandler).await
    }

    /// Unblock a user by npub.
    pub async fn unblock_user(&self, npub: &str) -> bool {
        profile::sync::unblock_user(npub.to_string(), &NoOpProfileSyncHandler).await
    }

    /// Set a nickname for a profile.
    pub async fn set_nickname(&self, npub: &str, nickname: &str) -> bool {
        profile::sync::set_nickname(npub.to_string(), nickname.to_string(), &NoOpProfileSyncHandler).await
    }

    /// Get all blocked profiles.
    pub async fn get_blocked_users(&self) -> Vec<SlimProfile> {
        profile::sync::get_blocked_users().await
    }

    /// Queue a profile for background sync.
    pub fn queue_profile_sync(&self, npub: &str, priority: SyncPriority) {
        profile::sync::queue_profile_sync(npub.to_string(), priority, false);
    }

    /// Get the current user's npub.
    pub fn my_npub(&self) -> Option<String> {
        state::my_public_key()
            .and_then(|pk| ToBech32::to_bech32(&pk).ok())
    }

    // === Communities (headless) ===
    // The GUI's Tauri commands carry optimistic-echo + emit machinery a headless client
    // doesn't need; these are the lean equivalents over the same `community::service` layer,
    // so a CLI / agent can join, read, post, and sync a Community.

    /// List every Community held locally (owned or joined), each with its channels.
    pub async fn list_communities(&self) -> Vec<serde_json::Value> {
        let ids = crate::db::community::list_community_ids().unwrap_or_default();
        let me = state::my_public_key();
        let mut out = Vec::new();
        for id in ids {
            let Ok(Some(c)) = crate::db::community::load_community_v2(&id) else { continue };
            let is_owner = me.is_some_and(|m| c.owner().is_ok_and(|o| o == m));
            out.push(serde_json::json!({
                "community_id": crate::simd::hex::bytes_to_hex_32(&c.identity.community_id.0),
                "version": 2,
                "name": c.name,
                "description": c.description,
                "is_owner": is_owner,
                // A dissolved community is SEALED: the row survives (history
                // is never auto-deleted) but no write is ever accepted again.
                // Without this a bot cannot tell it from a live one and
                // retries sends into a tombstone forever.
                "dissolved": c.dissolved,
                // `readable` is the field a bot needs and could never
                // compute: a private channel we've been told about but
                // hold no key for is enumerable-but-unreadable, which
                // is what distinguishes "not a member" from "member
                // awaiting the key vend".
                "channels": c.layout().1.into_iter()
                    .map(|(ch, cat)| serde_json::json!({
                        "channel_id": crate::simd::hex::bytes_to_hex_32(&ch.id.0),
                        "name": ch.name,
                        "private": ch.private,
                        "readable": !(ch.private && ch.key.is_none()),
                        "epoch": ch.epoch.0,
                        "category_id": cat.map(|k| crate::simd::hex::bytes_to_hex_32(&k.id)),
                        "topic": ch.topic(),
                        "view": ch.view().as_str(),
                    }))
                    .collect::<Vec<_>>(),
                "categories": Self::categories_json(&c),
            }));
        }
        out
    }

    /// Create a fresh **Concord v2** community owned by the local identity. Mints the
    /// self-certifying id + genesis, persists, publishes, and registers each channel
    /// as a chat. Returns a `version: 2` JSON summary.
    pub async fn create_community_v2(&self, name: &str) -> Result<serde_json::Value> {
        self.create_community_with(name, &NewCommunity::default()).await
    }

    /// Create a Community as [`NewCommunity`] shapes it. Returns the same summary as
    /// [`create_community_v2`](Self::create_community_v2).
    pub async fn create_community_with(&self, name: &str, opts: &NewCommunity) -> Result<serde_json::Value> {
        use crate::community::{v2::service as v2, transport::LiveTransport};
        let relays: Vec<String> = if opts.relays.is_empty() {
            crate::state::active_trusted_relays().await.iter().map(|s| s.to_string()).collect()
        } else {
            crate::community::v2::service::clean_relays(&[], &opts.relays).map_err(VectorError::Other)?
        };
        if relays.is_empty() {
            return Err(VectorError::Other("no relays available to host the Community".into()));
        }
        let session = crate::db::current_session();
        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
        let mut community = v2::create_community_on_roles_v2(&transport, name, relays, opts.description.clone())
            .await
            .map_err(VectorError::Other)?;
        if !session.is_live() {
            return Err(VectorError::Other("account changed while creating the community".into()));
        }
        self.register_v2_chats(&community, &session).await;
        // Genesis names the first Channel `general`. The Community stands either way, so a
        // failed rename is logged rather than returned: a retry would found a second one.
        if let Some(first) = opts.first_channel.as_deref().map(str::trim).filter(|n| !n.is_empty() && *n != "general") {
            if let Some(ch) = community.channels.first().cloned() {
                // From the held document: a rename keeps every vsk-2 field it doesn't touch.
                let mut meta = ch.metadata();
                meta.name = first.to_string();
                match v2::edit_channel_metadata(&transport, &community, &ch.id, &meta).await {
                    Ok(()) => {
                        if let Ok(Some(fresh)) = crate::db::community::load_community_v2(community.id()) {
                            community = fresh;
                            if session.is_live() {
                                self.register_v2_chats(&community, &session).await;
                            }
                        }
                    }
                    Err(e) => crate::log_warn!("[v2:create] the first channel keeps the name general: {e}"),
                }
            }
        }
        // Start streaming this community's planes right away.
        if let Some(client) = state::nostr_client() {
            crate::community::v2::realtime::refresh_subscription(&client).await;
        }
        Ok(Self::v2_summary(&community))
    }

    /// If `channel_id` belongs to a locally-held **v2** community, its
    /// `CommunityId`; `Ok(None)` for an unknown channel. A DB read error PROPAGATES
    /// (fail-closed) rather than reading as "unknown" on a transient failure.
    fn v2_community_for_channel(&self, channel_id: &str) -> Result<Option<crate::community::CommunityId>> {
        let Some(cid_hex) = crate::db::community::community_id_for_channel(channel_id).map_err(VectorError::Other)? else {
            return Ok(None);
        };
        let cid = crate::community::CommunityId(crate::simd::hex::hex_to_bytes_32(&cid_hex));
        Ok(crate::db::community::community_held(&cid).map_err(VectorError::Other)?.then_some(cid))
    }

    /// The `version: 2` JSON summary the SDK/facade hands back for a v2 community.
    fn v2_summary(community: &crate::community::v2::community::CommunityV2) -> serde_json::Value {
        let me = state::my_public_key();
        let is_owner = me.is_some_and(|m| community.owner().is_ok_and(|o| o == m));
        serde_json::json!({
            "community_id": crate::simd::hex::bytes_to_hex_32(&community.identity.community_id.0),
            "version": 2,
            "name": community.name,
            "description": community.description,
            "is_owner": is_owner,
            // The primary channel id, so the frontend can stamp every grafted chat row
            // the way `register_v2_chats` stamps the persisted ones. Without it each
            // channel claimed primary via the render fallback and a multi-channel
            // community drew one list row per channel until the next full reload.
            "primary_channel": community.primary_channel().map(|c| crate::simd::hex::bytes_to_hex_32(&c.id.0)),
            "channels": community.layout().1.into_iter()
                .map(|(c, cat)| serde_json::json!({
                    "channel_id": crate::simd::hex::bytes_to_hex_32(&c.id.0),
                    "name": c.name,
                    "private": c.private,
                    "category_id": cat.map(|k| crate::simd::hex::bytes_to_hex_32(&k.id)),
                    "topic": c.topic(),
                    "view": c.view().as_str(),
                }))
                .collect::<Vec<_>>(),
            "categories": Self::categories_json(community),
        })
    }

    /// What the local user may do in each channel, on Roles v2 (CORD-04 §8): `None` on the
    /// legacy roster, where channels carry no permissions of their own.
    pub fn my_channel_permissions(community: &crate::community::v2::community::CommunityV2) -> std::collections::HashMap<[u8; 32], u64> {
        let Some(me) = state::my_public_key() else { return Default::default() };
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let roster = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
        if roster.everyone.is_none() {
            return Default::default();
        }
        let owner = community.owner().ok().map(|o| o.to_hex());
        community
            .channels
            .iter()
            .map(|c| (c.id.0, roster.channel_permissions(owner.as_deref(), &me.to_hex(), &crate::simd::hex::bytes_to_hex_32(&c.id.0), c.private).0))
            .collect()
    }

    /// A community's Categories in sidebar order, as the summaries carry them.
    pub fn categories_json(community: &crate::community::v2::community::CommunityV2) -> serde_json::Value {
        community
            .layout()
            .0
            .into_iter()
            .map(|k| serde_json::json!({ "category_id": crate::simd::hex::bytes_to_hex_32(&k.id), "name": k.name }))
            .collect()
    }

    /// Register each of a v2 community's channels as a chat row (so it surfaces in
    /// the chat list / `communities()`). `session`
    /// is captured by the caller BEFORE its network I/O, so this STATE write is
    /// skipped if the account swapped mid-flight (else we'd write A's community
    /// into B's in-memory chats).
    pub async fn register_v2_chats(&self, community: &crate::community::v2::community::CommunityV2, __session: &std::sync::Arc<crate::db::Session>) {
        register_v2_chats_inner(community).await
    }
}

/// Free-function body of [`VectorCore::register_v2_chats`] — also the migration finalize's
/// chat stamp (it runs from a spawned task with no facade handle; only globals are touched).
pub(crate) async fn register_v2_chats_inner(community: &crate::community::v2::community::CommunityV2) {
    // A Community joined or founded while listening: what stands now is its baseline, so its
    // first changes are news rather than the baseline itself.
    crate::community::v2::changes::prime(community);
    crate::db::scoped(async move {
        let owner_npub = community.owner().ok().and_then(|p| ToBech32::to_bech32(&p).ok());
            let me = state::my_public_key();
            let is_owner = me.is_some_and(|m| community.owner().is_ok_and(|o| o == m));
            let id_hex = crate::simd::hex::bytes_to_hex_32(&community.identity.community_id.0);
            // The chat list shows ONE row per community — the primary channel under the
            // community's metadata.
            let Some(primary) = community.primary_channel() else { return };
            let primary_hex = crate::simd::hex::bytes_to_hex_32(&primary.id.0);
            // Every channel gets a real chat row carrying its own name plus the community's
            // primary id. The chat list still shows ONE row per community (it renders only the
            // primary), but the sibling rows are now addressable, which is what lets the UI
            // reach a multi-channel community's other channels.
            let slims = {
                let mut st = state::STATE.lock().await;
                let mut slims = Vec::new();
                for ch in &community.channels {
                    let ch_hex = crate::simd::hex::bytes_to_hex_32(&ch.id.0);
                    st.upsert_community_chat(
                        &ch_hex,
                        &community.name,
                        community.description.as_deref().unwrap_or(""),
                        &id_hex,
                        is_owner,
                        community.icon.is_some(),
                        owner_npub.as_deref(),
                        Some(community.created_at_ms),
                        community.dissolved,
                        &ch.name,
                        &primary_hex,
                    );
                    if let Some(chat) = st.chats.iter().find(|c| c.id == ch_hex) {
                        slims.push(crate::db::chats::SlimChatDB::from_chat(chat, &st.interner));
                    }
                }
                slims
            };
            // Persist the rows so a fresh boot reloads each channel's name/metadata
            for slim in &slims {
                let _ = crate::db::chats::save_slim_chat(slim);
            }
    })
    .await
}

/// How long a community's raid verdict stays warm. Long enough that opening the panel
/// right after seeing its badge is instant, short enough that a wave arriving now shows
/// up without the moderator reloading anything.
const RAID_REPORT_TTL_SECS: u64 = 90;

/// Per-account: the verdict is derived from this account's database and its roster.
struct RaidReportCache;

struct PolicyReportCache;
struct PolicyReportGate;

type ReportCache<T> = std::sync::Arc<std::sync::Mutex<std::collections::HashMap<String, (u64, std::sync::Arc<T>)>>>;

/// The engine's console report, memoised like the assessor's was: evaluating
/// decrypts a four-thousand-message window and clusters every author, so a
/// header badge asking on every render would be a real cost.
fn policy_report_cache() -> ReportCache<serde_json::Value> {
    crate::db::current_session().scoped::<PolicyReportCache, _>()
}

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

fn raid_report_cache() -> ReportCache<crate::community::raid::RaidReport> {
    crate::db::current_session().scoped::<RaidReportCache, _>()
}

/// A fresh memoised report. Expired entries go on every touch, so a community looked at
/// once is not held for the rest of the session.
fn report_get<T>(cache: &ReportCache<T>, cid_hex: &str, now_secs: u64) -> Option<std::sync::Arc<T>> {
    let mut map = cache.lock().unwrap_or_else(|e| e.into_inner());
    map.retain(|_, (at, _)| now_secs.saturating_sub(*at) < RAID_REPORT_TTL_SECS);
    map.get(cid_hex).map(|(_, report)| report.clone())
}

fn report_put<T>(cache: &ReportCache<T>, cid_hex: &str, now_secs: u64, report: std::sync::Arc<T>) {
    let mut map = cache.lock().unwrap_or_else(|e| e.into_inner());
    map.retain(|_, (at, _)| now_secs.saturating_sub(*at) < RAID_REPORT_TTL_SECS);
    map.insert(cid_hex.to_string(), (now_secs, report));
}

/// A memoised report, evaluated at most once per expiry: callers that miss together (a
/// badge, a menu and a panel asking on one render) wait for the first and take its report.
fn report_once<T>(
    cache: &ReportCache<T>,
    gate: &std::sync::Mutex<()>,
    cid_hex: &str,
    now_secs: u64,
    compute: impl FnOnce() -> Result<std::sync::Arc<T>>,
) -> Result<std::sync::Arc<T>> {
    if let Some(hit) = report_get(cache, cid_hex, now_secs) {
        return Ok(hit);
    }
    let _turn = gate.lock().unwrap_or_else(|e| e.into_inner());
    if let Some(hit) = report_get(cache, cid_hex, now_secs) {
        return Ok(hit);
    }
    let report = compute()?;
    report_put(cache, cid_hex, now_secs, report.clone());
    Ok(report)
}

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

    #[test]
    fn an_expired_report_goes_on_the_next_touch() {
        let cache: ReportCache<u32> = Default::default();
        report_put(&cache, "a", 1_000, std::sync::Arc::new(1));
        report_put(&cache, "b", 1_050, std::sync::Arc::new(2));
        assert_eq!(report_get(&cache, "a", 1_000 + RAID_REPORT_TTL_SECS - 1).as_deref(), Some(&1));
        assert_eq!(report_get(&cache, "a", 1_000 + RAID_REPORT_TTL_SECS), None, "a report is fresh for the TTL, no longer");
        assert_eq!(cache.lock().unwrap().len(), 1, "the lookup dropped it");
        report_put(&cache, "c", 1_050 + RAID_REPORT_TTL_SECS, std::sync::Arc::new(3));
        let map = cache.lock().unwrap();
        assert!(!map.contains_key("b") && map.contains_key("c"), "and so does an insert");
    }

    #[test]
    fn callers_that_miss_together_share_one_evaluation() {
        let cache: ReportCache<u32> = Default::default();
        let gate = std::sync::Mutex::new(());
        let runs = std::sync::atomic::AtomicU32::new(0);
        std::thread::scope(|s| {
            for _ in 0..4 {
                s.spawn(|| {
                    let got = report_once(&cache, &gate, "a", 1_000, || {
                        runs.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                        std::thread::sleep(std::time::Duration::from_millis(50));
                        Ok(std::sync::Arc::new(7))
                    });
                    assert_eq!(got.unwrap().as_ref(), &7);
                });
            }
        });
        assert_eq!(runs.load(std::sync::atomic::Ordering::SeqCst), 1);
        let again = report_once(&cache, &gate, "a", 1_000 + RAID_REPORT_TTL_SECS, || Ok(std::sync::Arc::new(8)));
        assert_eq!(again.unwrap().as_ref(), &8, "an expired report is evaluated afresh");
    }
}

impl VectorCore {
    /// Join a Community from a public invite URL (`vectorapp.io/invite/<naddr>#...`). Fetches the
    /// token-encrypted bundle, persists the member-view Community, and registers its channels
    /// as chats. Returns a JSON summary.
    pub async fn join_community(&self, invite_url: &str) -> Result<serde_json::Value> {
        use crate::community::transport::LiveTransport;
        crate::community::v2::invite::parse_invite_link(invite_url)
            .map_err(|_| VectorError::Other("not a Vector invite link".into()))?;
        let session = crate::db::current_session();
        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
        let community = crate::community::v2::service::accept_public_link(&transport, invite_url)
            .await
            .map_err(VectorError::Other)?;
        self.register_v2_chats(&community, &session).await;
        if let Some(client) = state::nostr_client() {
            crate::community::v2::realtime::refresh_subscription(&client).await;
        }
        // Seed the membership store post-join. With a live listen the follow
        // worker does it (and SURFACES the folded joins as presence lines —
        // the joiner sees the room's history, own join included); headless
        // callers seed directly (membership only, no feed to surface).
        if crate::community::v2::realtime::follow_worker_running() {
            crate::community::v2::realtime::enqueue_follow(community.id());
        } else {
            let seed_community = community.clone();
            db::spawn_bound(async move {
                let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(20));
                if matches!(
                    crate::community::v2::service::sync_guestbook(&transport, &seed_community).await,
                    Ok(fresh) if !fresh.is_empty()
                ) {
                    let cid_hex = crate::simd::hex::bytes_to_hex_32(&seed_community.id().0);
                    emit_event("community_refreshed", &serde_json::json!({ "community_id": cid_hex }));
                }
            });
        }
        Ok(Self::v2_summary(&community))
    }

    /// List the parked private invites (giftwrapped) awaiting acceptance. Each entry is the
    /// community id, its name (from the stored bundle), and the inviter's npub.
    pub fn list_pending_invites(&self) -> Result<Vec<serde_json::Value>> {
        let rows = crate::db::community::list_pending_invites().map_err(VectorError::Other)?;
        Ok(rows
            .iter()
            .filter_map(|p| {
                let v2 = crate::community::v2::invite::CommunityInvite::from_bundle_json(&p.bundle_json).ok()?;
                Some(serde_json::json!({
                    "community_id": p.community_id,
                    "name": v2.name,
                    "inviter_npub": p.inviter_npub,
                    "version": 2,
                }))
            })
            .collect())
    }

    /// Accept a PARKED private invite by community id: rebuild the member-view Community from the stored
    /// bundle, finalize the join exactly like a public link, then drop the pending row. Mirrors the
    /// desktop's consent-then-join for an invite delivered over a gift wrap.
    pub async fn accept_pending_invite(&self, community_id: &str) -> Result<serde_json::Value> {
        crate::db::scoped(async move {
            use crate::community::transport::LiveTransport;
            let bundle_json = crate::db::community::get_pending_invite(community_id)
                .map_err(VectorError::Other)?
                .ok_or_else(|| VectorError::Other(format!("no pending invite for {community_id}")))?;
            let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
            let session = crate::db::current_session();
            // The inviter's hex (parked at receive) attributes the Guestbook Join.
            let inviter = crate::db::community::list_pending_invites()
                .ok()
                .and_then(|rows| rows.into_iter().find(|p| p.community_id == community_id).map(|p| p.inviter_npub));
            // On failure the parked row is LEFT INTACT for retry — we must NOT auto-delete
            // on a verify failure: the multi-relay transport launders an unreachable-relay
            // error into an empty fetch, which yields the same "could not verify" as a
            // forged root (and a control-plane flood does too), so an auto-delete would
            // erase a GENUINE invite on a transient blip or an attacker's flood. A
            // pre-planted forged-root bundle (deferred protocol residual) is instead
            // cleared by the user declining it.
            //
            // ONE exception: a verified dissolution is a verdict, not a maybe — an
            // owner-signed grave has no undo (§9), so that invite can never succeed
            // and is retired everywhere instead of parking a permanent error loop.
            let community = match crate::community::v2::service::accept_parked_invite(&transport, &bundle_json, inviter.as_deref()).await {
                Ok(c) => c,
                Err(e) if e == crate::community::v2::service::ERR_DISSOLVED => {
                    let relays = crate::community::v2::invite::CommunityInvite::from_bundle_json(&bundle_json)
                        .map(|i| i.relays)
                        .unwrap_or_default();
                    crate::community::v2::service::retire_dead_invite(&transport, community_id, &relays).await;
                    return Err(VectorError::Other("this community has been dissolved — the invite was removed".into()));
                }
                Err(e) => return Err(VectorError::Other(e)),
            };
            self.register_v2_chats(&community, &session).await;
            if let Some(client) = state::nostr_client() {
                crate::community::v2::realtime::refresh_subscription(&client).await;
            }
            crate::community::v2::realtime::enqueue_follow(community.id());
            let _ = crate::db::community::delete_pending_invite(community_id);
            Ok(Self::v2_summary(&community))
        })
        .await
    }


    // ── Channels (CORD-03) ───────────────────────────────────────────────────

    /// Resolve a v2 community by id, or explain why it isn't one.
    fn v2_community(community_id: &str) -> Result<crate::community::v2::community::CommunityV2> {
        use crate::community::CommunityId;
        if community_id.len() != 64 {
            return Err(VectorError::Other("malformed community id".into()));
        }
        let cid = CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
        crate::db::community::load_community_v2(&cid)
            .map_err(VectorError::Other)?
            .ok_or_else(|| VectorError::Other("community not found".into()))
    }

    fn channel_id_of(channel_id: &str) -> Result<crate::community::ChannelId> {
        crate::simd::hex::hex_to_bytes_32_checked(channel_id)
            .map(crate::community::ChannelId)
            .ok_or_else(|| VectorError::Other("malformed channel id".into()))
    }

    /// Create a channel. A private one mints its own key plus the channel-scoped
    /// access Role that is its access list (CORD-03/04); grant that role with
    /// [`grant_channel_access`](Self::grant_channel_access) to let someone read it.
    /// Returns the new channel id (32-byte hex).
    pub async fn create_channel(&self, community_id: &str, name: &str, private: bool) -> Result<String> {
        use crate::community::{v2::service, transport::LiveTransport};
        let community = Self::v2_community(community_id)?;
        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
        let id = if private {
            service::create_private_channel(&transport, &community, name).await
        } else {
            service::create_public_channel(&transport, &community, name).await
        }
        .map_err(VectorError::Other)?;
        // Subscribe the new channel's chat plane now — waiting on the round-trip of
        // our own vsk-2 edition would leave the creator deaf to first replies.
        if let Some(client) = state::nostr_client() {
            crate::community::v2::realtime::refresh_subscription(&client).await;
        }
        Ok(crate::simd::hex::bytes_to_hex_32(&id.0))
    }

    /// Create a Channel as [`NewChannel`] shapes it. Returns the channel id.
    pub async fn create_channel_with(&self, community_id: &str, name: &str, opts: &NewChannel) -> Result<String> {
        use crate::community::{v2::service, transport::LiveTransport};
        let name = name.trim();
        if name.is_empty() {
            return Err(VectorError::Other("a channel needs a name".into()));
        }
        let view = opts.view.as_deref().map(Self::view_named).transpose()?;
        let session = crate::db::current_session();
        let community = Self::v2_community(community_id)?;
        let category = opts.category_id.as_deref().map(|c| Self::id32(c, "category_id")).transpose()?;
        // A private Channel rekeys every member it admits, which takes longer.
        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(20));
        let id = service::create_channel_in(&transport, &community, name, opts.private, category).await.map_err(VectorError::Other)?;
        let channel_id = crate::simd::hex::bytes_to_hex_32(&id.0);
        // From the held document: the create wrote the Channel there, not onto our copy.
        if let Ok(Some(fresh)) = crate::db::community::load_community_v2(community.id()) {
            if session.is_live() {
                self.register_v2_chats(&fresh, &session).await;
            }
        }
        // The view and topic are a second edition. The Channel stands either way, so a failure
        // is logged rather than returned: a retry would make a second Channel.
        if view.is_some() || opts.topic.is_some() {
            let view = view.unwrap_or(crate::community::v2::community::ChannelView::Chat).as_str();
            if let Err(e) = self.edit_channel_details(community_id, &channel_id, name, opts.topic.as_deref(), view).await {
                crate::log_warn!("[v2:create] channel {} stands without its view or topic: {e}", &channel_id[..12]);
            }
        }
        if let Some(client) = state::nostr_client() {
            crate::community::v2::realtime::refresh_subscription(&client).await;
        }
        Ok(channel_id)
    }

    /// What a public invite link shows before joining: name, description and icon, read from the
    /// Community's own Control Plane when its owner's root verifies (`verified`). Read-only.
    pub async fn preview_public_link(&self, url: &str) -> Result<LinkPreview> {
        use crate::community::{transport::LiveTransport, CommunityId};
        crate::community::v2::invite::parse_invite_link(url).map_err(|_| VectorError::Other("not a Vector invite link".into()))?;
        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
        let bundle = crate::community::v2::service::fetch_public_bundle(&transport, url).await.map_err(VectorError::Other)?;
        // Self-certifying: verified as the bundle decrypts, so it names the Community unfolded.
        let community_id = bundle.community_id.clone();
        if let Ok(id) = Self::id32(&community_id, "community_id") {
            if let Ok(Some(local)) = crate::db::community::load_community_v2(&CommunityId(id)) {
                return Ok(LinkPreview {
                    community_id,
                    name: local.name.clone(),
                    description: local.description.clone(),
                    icon: local.icon.as_ref().map(|i| i.to_community_image()),
                    joined: true,
                    verified: true,
                });
            }
        }
        let (folded, verified) = crate::community::v2::service::preview_bundle_checked(&transport, &bundle).await.map_err(VectorError::Other)?;
        Ok(LinkPreview {
            community_id,
            name: folded.name.clone(),
            description: folded.description.clone(),
            icon: folded.icon.as_ref().map(|i| i.to_community_image()),
            joined: false,
            verified,
        })
    }

    /// Rename a channel (a versioned edit of the same entity, so its history and
    /// id survive). Other folded fields are carried through untouched.
    pub async fn rename_channel(&self, community_id: &str, channel_id: &str, name: &str) -> Result<()> {
        use crate::community::{v2::service, transport::LiveTransport};
        let community = Self::v2_community(community_id)?;
        let id = Self::channel_id_of(channel_id)?;
        let mut meta = community
            .channel(&id)
            .ok_or_else(|| VectorError::Other("unknown channel".into()))?
            .metadata();
        meta.name = name.to_string();
        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
        service::edit_channel_metadata(&transport, &community, &id, &meta)
            .await
            .map_err(VectorError::Other)
    }

    /// Tombstone a channel. Deletion is terminal and the id is never reused;
    /// history stays readable to anyone who already holds its keys.
    pub async fn delete_channel(&self, community_id: &str, channel_id: &str) -> Result<()> {
        use crate::community::{v2::service, transport::LiveTransport};
        let community = Self::v2_community(community_id)?;
        let id = Self::channel_id_of(channel_id)?;
        let name = community.channel(&id).map(|c| c.name.clone()).unwrap_or_default();
        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
        service::delete_channel(&transport, &community, &id, &name)
            .await
            .map_err(VectorError::Other)
    }

    /// Grant `npub` read access to a private channel: adds the channel's access
    /// role and vends the key to them (CORD-03 "delivered on grant").
    pub async fn grant_channel_access(&self, community_id: &str, channel_id: &str, npub: &str) -> Result<()> {
        use crate::community::{v2::service, transport::LiveTransport};
        let community = Self::v2_community(community_id)?;
        let id = Self::channel_id_of(channel_id)?;
        let member = nostr_sdk::prelude::PublicKey::parse(npub)
            .map_err(|e| VectorError::Other(format!("bad npub: {e}")))?;
        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
        service::grant_channel_access(&transport, &community, &id, &member)
            .await
            .map_err(VectorError::Other)
    }

    /// Revoke `npub`'s read access: drops the access role and rekeys the channel
    /// so the removal actually severs them (CORD-06). They keep whatever history
    /// they already read — a rekey protects the future, never the past.
    pub async fn revoke_channel_access(&self, community_id: &str, channel_id: &str, npub: &str) -> Result<()> {
        use crate::community::{v2::service, transport::LiveTransport};
        let community = Self::v2_community(community_id)?;
        let id = Self::channel_id_of(channel_id)?;
        let member = nostr_sdk::prelude::PublicKey::parse(npub)
            .map_err(|e| VectorError::Other(format!("bad npub: {e}")))?;
        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
        service::revoke_channel_access(&transport, &community, &id, &member)
            .await
            .map_err(VectorError::Other)
    }

    /// Who may read a private channel: the channel-scoped Roles that are its
    /// access list (CORD-04 §2) and the members holding them.
    ///
    /// Sync read off the folded roster. `members` is exactly the access-role
    /// holders; `owner` is reported alongside because the owner is entitled
    /// whether or not they hold one (a channel's creator is granted the role, so
    /// an owner-created channel lists them in both).
    /// Whether `npub` may READ `channel_id` here.
    ///
    /// A PUBLIC channel is readable by the community; a PRIVATE one only by the
    /// holders of one of its channel-scoped access roles (CORD-03), plus the
    /// owner. Community-level power is NOT the question and must not be
    /// substituted for it: BAN says what someone may do to people, never which
    /// rooms they may see, and an access role commonly carries no powers at all.
    ///
    /// The reason this exists: a moderation report quotes what was said. Sending
    /// one built from a private channel to a moderator who holds no key there
    /// would launder the content out of the room, using the bot as the bypass —
    /// so anything that forwards evidence asks this first.
    ///
    /// Fails closed. A banned member reads nothing, and an unknown channel is an
    /// error rather than a permissive default.
    pub fn member_can_read_channel(&self, community_id: &str, channel_id: &str, npub: &str) -> Result<bool> {
        use nostr_sdk::prelude::PublicKey;
        let community = Self::v2_community(community_id)?;
        let id = Self::channel_id_of(channel_id)?;
        let ch = community.channel(&id).ok_or_else(|| VectorError::Other("unknown channel".into()))?;
        let who = PublicKey::parse(npub).map_err(|_| VectorError::Other(format!("invalid npub: {npub}")))?.to_hex();
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        if crate::db::community::get_community_banlist(&cid_hex).unwrap_or_default().contains(&who) {
            return Ok(false);
        }
        if !ch.private {
            return Ok(true);
        }
        if community.owner().map(|o| o.to_hex()) == Ok(who.clone()) {
            return Ok(true);
        }
        let roster = crate::db::community::get_community_roles(&cid_hex).map_err(VectorError::Other)?;
        let access_ids = roster.channel_role_ids(&crate::simd::hex::bytes_to_hex_32(&id.0));
        Ok(roster
            .grants
            .iter()
            .filter(|g| g.member == who)
            .any(|g| g.role_ids.iter().any(|rid| access_ids.contains(rid))))
    }

    pub fn channel_access(&self, community_id: &str, channel_id: &str) -> Result<serde_json::Value> {
        use nostr_sdk::prelude::{PublicKey, ToBech32};
        let community = Self::v2_community(community_id)?;
        let id = Self::channel_id_of(channel_id)?;
        let ch = community
            .channel(&id)
            .ok_or_else(|| VectorError::Other("unknown channel".into()))?;
        // Normalised id, not the caller's string: an uppercase-hex argument loads
        // the community but would miss the roster row and silently report nobody.
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let roster = crate::db::community::get_community_roles(&cid_hex).map_err(VectorError::Other)?;
        let banned = crate::db::community::get_community_banlist(&cid_hex).unwrap_or_default();
        let chan_hex = crate::simd::hex::bytes_to_hex_32(&id.0);
        let owner_hex = community.owner().ok().map(|o| o.to_hex());
        let (roles, members): (Vec<serde_json::Value>, Vec<String>) = if roster.everyone.is_some() {
            // Roles v2: whoever the Channel resolves View for, through Roles or their own overwrite.
            use crate::community::roles::{OverwriteTarget, Permissions};
            let scope = roster.syncs.get(&chan_hex).cloned().unwrap_or_else(|| chan_hex.clone());
            let roles = roster
                .overwrites
                .iter()
                .filter(|o| o.scope == scope && o.allow.contains(Permissions::VIEW_CHANNEL))
                .filter_map(|o| match &o.target {
                    OverwriteTarget::Role(id) => roster.role(id).map(|r| serde_json::json!({ "role_id": r.role_id, "name": r.name })),
                    _ => None,
                })
                .collect();
            let mut named: Vec<String> = roster.grants.iter().map(|g| g.member.clone()).collect();
            named.extend(roster.overwrites.iter().filter_map(|o| match &o.target {
                OverwriteTarget::Member(m) => Some(m.clone()),
                _ => None,
            }));
            named.sort();
            named.dedup();
            let members = named
                .into_iter()
                .filter(|m| !banned.contains(m) && Some(m) != owner_hex.as_ref() && roster.is_entitled(owner_hex.as_deref(), m, &chan_hex, &[], &[]))
                .filter_map(|m| PublicKey::from_hex(&m).ok().and_then(|pk| pk.to_bech32().ok()))
                .collect();
            (roles, members)
        } else {
            let access_ids = roster.channel_role_ids(&chan_hex);
            let roles = roster
                .channel_roles(&chan_hex)
                .into_iter()
                .map(|r| serde_json::json!({ "role_id": r.role_id, "name": r.name }))
                .collect();
            let members = roster
                .grants
                .iter()
                .filter(|g| !banned.contains(&g.member))
                .filter(|g| g.role_ids.iter().any(|rid| access_ids.contains(rid)))
                .filter_map(|g| PublicKey::from_hex(&g.member).ok().and_then(|pk| pk.to_bech32().ok()))
                .collect();
            (roles, members)
        };
        Ok(serde_json::json!({
            "channel_id": chan_hex,
            "private": ch.private,
            "readable": !(ch.private && ch.key.is_none()),
            "owner": community.owner().ok().and_then(|o| o.to_bech32().ok()),
            "roles": roles,
            "members": members,
        }))
    }

    /// Mint a public invite link for a Community this identity owns. Returns the shareable URL.
    /// `expires_at_ms` is an ABSOLUTE unix timestamp in MILLISECONDS (v2's native unit and the
    /// `InviteEntry` wire's). `label` is the attribution bucket shown as `"joined via <label>"`.
    pub async fn create_public_invite(
        &self,
        community_id: &str,
        expires_at_ms: Option<u64>,
        label: Option<String>,
    ) -> Result<String> {
        use crate::community::CommunityId;
        if community_id.len() != 64 {
            return Err(VectorError::Other("malformed community id".into()));
        }
        let cid = CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
        let community = crate::db::community::load_community_v2(&cid)
            .map_err(VectorError::Other)?
            .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
        // `build_invite_url` appends its own `/invite/<naddr>`, so pass the bare domain.
        let base = crate::community::v2::invite::INVITE_URL_BASE.trim_end_matches("/invite");
        let label = Some(crate::community::v2::invite::resolve_invite_label(community_id, label).map_err(VectorError::Other)?);
        let minted = crate::community::v2::service::mint_public_link_sync_later(&community, base, expires_at_ms, label)
            .await
            .map_err(VectorError::Other)?;
        Ok(minted.url)
    }

    /// Send a PRIVATE invite: gift-wrap a Direct Invite bundle (3313) to an npub's inbox relays. The
    /// invitee parks it pending consent (accept_pending_invite). Any member may extend one.
    pub async fn invite_to_community(&self, community_id: &str, invitee_npub: &str) -> Result<serde_json::Value> {
        crate::db::scoped(async move {
            use crate::community::CommunityId;

            let my_pk = crate::state::my_public_key()
                .ok_or_else(|| VectorError::Other("Public key not set".into()))?;

            if community_id.len() != 64 {
                return Err(VectorError::Other("malformed community id".into()));
            }
            let cid = CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
            // A Direct Invite (3313 giftwrap), DELIBERATELY ungated: a Direct Invite is an ungateable key handoff (CORD-05 §6 — "any keyholder
            // can whisper keys"), so any member may extend one; the real access cut is
            // the rekey, not a permission on inviting.
            let recipient = nostr_sdk::prelude::PublicKey::parse(invitee_npub)
                .map_err(|e| VectorError::Other(format!("bad invitee npub: {e}")))?;
            let client = crate::state::nostr_client().ok_or_else(|| VectorError::Other("Not connected".into()))?;
            // Gift-wrap the 3313 Direct-Invite rumor (the bundle JSON) to the RECIPIENT'S
            // inbox relays (kind-10050) — a not-yet-member sees it on their DM sub;
            // the community relays wouldn't reach them. `#k=3313` per CORD-05 §6.
            //
            // Load + snapshot UNDER the rotation lock: a bundle minted while a Ban's
            // refound is mid-rotation carries the root being buried, and its joiner
            // lands on a dead epoch only to self-evict on the rekey exclusion.
            let bundle = {
                let lock = crate::community::v2::realtime::follow_lock(&cid);
                let _rotation = lock.lock().await;
                let community = crate::db::community::load_community_v2(&cid)
                    .map_err(VectorError::Other)?
                    .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
                crate::community::v2::service::bundle_of(
                    &community,
                    crate::community::v2::service::BundleAudience::Member(recipient),
                    Some(my_pk),
                    None,
                    None,
                )
            };
            let bundle_json = serde_json::to_string(&bundle).map_err(|e| VectorError::Other(e.to_string()))?;
            // A 24h NIP-40 expiry (DIRECT_INVITE_EXPIRY_SECS): a bundle is live key material for a community that keeps rotating, so it must not linger.
            let expires_at = crate::clock::timestamp().as_secs()
                + crate::community::v2::invite::DIRECT_INVITE_EXPIRY_SECS;
            let expiry_tag = nostr_sdk::prelude::Tag::expiration(nostr_sdk::prelude::Timestamp::from_secs(expires_at));
            let rumor = nostr_sdk::prelude::EventBuilder::new(
                nostr_sdk::prelude::Kind::Custom(crate::community::v2::kind::DIRECT_INVITE),
                bundle_json,
            )
            .tag(expiry_tag.clone())
            .finalize_unsigned_with_id(my_pk);
            let k_tag = nostr_sdk::prelude::Tag::custom(
                "k",
                [crate::community::v2::kind::DIRECT_INVITE.to_string()],
            );
            crate::inbox_relays::send_gift_wrap(&client, &recipient, rumor, [k_tag, expiry_tag])
                .await
                .map_err(VectorError::Other)?;
            Ok(serde_json::json!({ "invited": invitee_npub, "version": 2 }))
        })
        .await
    }

    /// The public invite links this account minted for a Community (to list + revoke). Each carries
    /// the hex `token` (the link secret) needed by [`Self::revoke_public_invite`]. A local read of
    /// the links minted on this device (a mint also syncs the cross-device 13303 record).
    /// `join_count` comes from the Guestbook.
    pub fn list_public_invites(&self, community_id: &str) -> Result<Vec<crate::db::community::PublicInviteRecord>> {
        crate::db::community::list_public_invites(community_id).map_err(VectorError::Other)
    }

    /// Bring [`list_public_invites`](Self::list_public_invites) up to date with the links this
    /// account minted or retired on its other devices. Returns whether it changed.
    pub async fn sync_public_invites(&self, community_id: &str) -> Result<bool> {
        let held = Self::held_v2(community_id)?;
        let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
        crate::community::v2::service::adopt_invite_list(&transport, &held).await.map_err(VectorError::Other)
    }

    /// Revoke a public invite link by its hex token. Retiring the LAST active link flips the Community to
    /// Private, which re-founds (rotates the base key + every channel key) to cut link-joined lurkers.
    /// Idempotent: a token this account doesn't hold is a no-op. Needs a local key when the revoke triggers
    /// the privatize rekey (a bunker account can't rotate).
    pub async fn revoke_public_invite(&self, community_id: &str, token: &str) -> Result<()> {
        use crate::community::{transport::LiveTransport, CommunityId};
        if community_id.len() != 64 {
            return Err(VectorError::Other("malformed community id".into()));
        }
        let cid = CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(20));
        // A link is retired by its 16-byte token hex (re-post the coordinate as a
        // tombstone + tombstone the 13303 entry + refresh the Registry).
        let community = crate::db::community::load_community_v2(&cid)
            .map_err(VectorError::Other)?
            .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
        crate::community::v2::service::revoke_public_link(&transport, &community, token)
            .await
            .map_err(VectorError::Other)
    }

    /// Post a text message to a Community channel. Returns the message id (the inner id).
    pub async fn send_community_message(
        &self,
        channel_id: &str,
        content: &str,
        replied_to: Option<&str>,
    ) -> Result<String> {
        self.send_community_message_expiring(channel_id, content, replied_to, None).await
    }

    /// Post a message that deletes itself after `expires_in_secs`.
    ///
    /// A NIP-40 `expiration` tag on the rumor, which is what relays drop on and
    /// every member's client purges against — the same mechanism as the
    /// per-channel Self-Destruct Timer, decided per message instead of per
    /// channel. For a bot posting a public moderation notice: the warning is
    /// seen, then it stops being a permanent monument to somebody's worst day.
    ///
    pub async fn send_community_message_expiring(
        &self,
        channel_id: &str,
        content: &str,
        replied_to: Option<&str>,
        expires_in_secs: Option<u64>,
    ) -> Result<String> {
        let opts = PostOptions { reply_to: replied_to.map(str::to_string), expires_in_secs, ..Default::default() };
        self.post_community_message(channel_id, content, &opts).await
    }

    /// Post a text message to a Community channel, as [`PostOptions`] shapes it. Returns the
    /// message id (the inner id).
    pub async fn post_community_message(&self, channel_id: &str, content: &str, opts: &PostOptions) -> Result<String> {
        self.post_community(channel_id, content, Vec::new(), opts, std::time::Duration::from_secs(12)).await
    }

    /// The text half of every Community post: mentions, text spans and custom emoji resolved,
    /// the reply's author found, and the options' tags added.
    async fn post_community(
        &self,
        channel_id: &str,
        content: &str,
        mut extra_tags: Vec<nostr_sdk::prelude::Tag>,
        opts: &PostOptions,
        timeout: std::time::Duration,
    ) -> Result<String> {
        use crate::community::transport::LiveTransport;
        let id = self.v2_community_for_channel(channel_id)?.ok_or_else(|| VectorError::Other("unknown community channel".into()))?;
        let community = crate::db::community::load_community_v2(&id)
            .map_err(VectorError::Other)?
            .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
        let ch = crate::community::ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
        let transport = LiveTransport::with_timeout(timeout);
        // The NIP-C7 q tag's author slot is a SHOULD — best-effort from the
        // held message, empty (= unknown) when the parent isn't in memory.
        let reply = match opts.reply_to.as_deref().filter(|r| !r.is_empty()) {
            Some(parent_id) => {
                let author_hex = {
                    let st = state::STATE.lock().await;
                    st.find_message(parent_id)
                        .and_then(|(_, m)| m.npub.as_deref().and_then(|n| nostr_sdk::prelude::PublicKey::parse(n).ok()))
                        .map(|pk| pk.to_hex())
                        .unwrap_or_default()
                };
                Some((parent_id.to_string(), author_hex))
            }
            None => None,
        };
        let reply_ref = reply.as_ref().map(|(id, author)| (id.as_str(), author.as_str()));
        let (named, role_mentions) = crate::community::mentions::resolve_in(&crate::simd::hex::bytes_to_hex_32(&id.0), content);
        // NIP-30: resolve `:shortcode:` against subscribed packs so the rumor
        // carries `["emoji", ...]` pairs.
        let (plain, text_spans) = crate::text_spans::extract_own(&named);
        let content = plain.as_str();
        let emoji_owned = crate::emoji_packs::resolve_outbound_emoji_tags(content);
        let emoji_pairs: Vec<(&str, &str)> = emoji_owned.iter().map(|t| (t.shortcode.as_str(), t.url.as_str())).collect();
        extra_tags.extend(crate::text_spans::to_nostr_tags(&text_spans).chain(crate::community::mentions::to_tags(&role_mentions)));
        if let Some(bot) = opts.bot.as_deref().filter(|b| !b.is_empty()) {
            let pk = nostr_sdk::prelude::PublicKey::parse(bot).map_err(|_| VectorError::Other(format!("{bot} isn't an npub or hex pubkey")))?;
            extra_tags.push(crate::bot_interface::bot_tag(&pk));
        }
        if let Some(secs) = opts.expires_in_secs.filter(|s| *s > 0) {
            let at = crate::clock::now_secs().saturating_add(secs);
            extra_tags.push(nostr_sdk::prelude::Tag::expiration(nostr_sdk::prelude::Timestamp::from_secs(at)));
        }
        crate::community::v2::service::send_chat_message(&transport, &community, &ch, content, reply_ref, &emoji_pairs, extra_tags)
            .await
            .map_err(VectorError::Other)
    }

    /// Send a file to a Community channel as an encrypted attachment. Returns the message id.
    /// Mirrors the DM file pipeline (encrypt → Blossom upload → NIP-92 `imeta`) but publishes
    /// over the community transport.
    pub async fn send_community_file(&self, channel_id: &str, file_path: &str) -> Result<String> {
        self.post_community_file(channel_id, file_path, &PostOptions::default().compress(false)).await
    }

    /// [`send_community_file`](Self::send_community_file) with a caption, a reply, an expiry or a bot address.
    pub async fn post_community_file(&self, channel_id: &str, file_path: &str, opts: &PostOptions) -> Result<String> {
        let path = std::path::Path::new(file_path);
        let bytes = std::fs::read(path).map_err(VectorError::Io)?;
        let filename = path.file_name().and_then(|n| n.to_str()).unwrap_or("file").to_string();
        self.post_community_bytes(channel_id, bytes, &filename, opts).await
    }

    /// Send bytes held in memory to a Community channel as a file named `filename`, whose
    /// extension sets its type. Returns the message id.
    pub async fn post_community_bytes(&self, channel_id: &str, bytes: Vec<u8>, filename: &str, opts: &PostOptions) -> Result<String> {
        crate::db::scoped(async move {
            use crate::community::attachments;
            if bytes.is_empty() {
                return Err(VectorError::Other("Empty file".into()));
            }
            let (bytes, filename) = ready_to_send(bytes, filename, opts.compress).await?;
            let filename = filename.as_str();
            let extension = std::path::Path::new(filename).extension().and_then(|e| e.to_str()).unwrap_or("bin").to_lowercase();

            // Resolve the destination BEFORE the upload so a bad channel fails fast, and refuse a
            // sealed community (CORD-02 §9) here: the send's own gate is too late to save the upload.
            let id = self
                .v2_community_for_channel(channel_id)?
                .ok_or_else(|| VectorError::Other("unknown community channel".into()))?;
            let community = crate::db::community::load_community_v2(&id)
                .map_err(VectorError::Other)?
                .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
            if community.dissolved {
                return Err(VectorError::Other("this community has been dissolved".into()));
            }
            let author_pk = state::my_public_key().ok_or_else(|| VectorError::Other("Not logged in".into()))?;

            let file_hash = crate::crypto::sha256_hex(&bytes);
            let mime = crate::crypto::mime_from_extension(&extension);
            let img_meta = crate::crypto::generate_image_metadata(&bytes);

            // Encrypt → upload to Blossom.
            let params = crate::crypto::generate_encryption_params();
            let encrypted = crate::crypto::encrypt_data(&bytes, &params)?;
            let encrypted_size = encrypted.len() as u64;

            let _client = state::nostr_client().ok_or_else(|| VectorError::Other("Not logged in".into()))?;
            let signer = crate::signer::active_signer().map_err(|e| VectorError::Other(format!("Signer unavailable: {e}")))?;
            let servers = crate::blossom_servers::compute_enabled_servers();
            if servers.is_empty() {
                return Err(VectorError::Other("No Blossom servers configured".into()));
            }
            let noop_progress: crate::blossom::ProgressCallback = std::sync::Arc::new(|_, _| Ok(()));
            let accepted = crate::blossom::upload_blob_with_progress_and_failover(
                signer.clone(),
                servers,
                std::sync::Arc::new(encrypted),
                Some(mime),
                /* is_encrypted */ true,
                noop_progress,
                Some(3),
                Some(std::time::Duration::from_secs(2)),
                None,
            ).await.map_err(VectorError::Other)?;
            // This flow never mirrors, so only the descriptor matters.
            let url = accepted.url;

            let attachment = crate::types::Attachment {
                id: file_hash.clone(),
                key: params.key.clone(),
                nonce: params.nonce.clone(),
                extension: extension.clone(),
                name: filename.to_string(),
                url,
                // The caller's own file is the only plaintext copy there is.
                path: String::new(),
                size: encrypted_size,
                img_meta,
                downloading: false,
                downloaded: false,
                verified: true,
                // Mini Apps: one topic minted at send, so every member joins the same session.
                webxdc_topic: extension
                    .eq_ignore_ascii_case("xdc")
                    .then(|| crate::webxdc::mint_topic_id(&file_hash, &author_pk.to_hex())),
                ..Default::default()
            };
            // The imeta rides the kind-9 rumor verbatim (NIP-92); the caption is its content.
            let imeta = vec![attachments::attachment_to_imeta(&attachment)];
            let caption = opts.caption.clone().unwrap_or_default();
            self.post_community(channel_id, &caption, imeta, opts, std::time::Duration::from_secs(30)).await
        })
        .await
    }

    /// Send an ephemeral typing indicator to a Community channel.
    pub async fn send_community_typing(&self, channel_id: &str) -> Result<()> {
        use crate::community::transport::LiveTransport;
        let id = self.v2_community_for_channel(channel_id)?.ok_or_else(|| VectorError::Other("unknown community channel".into()))?;
        let community = crate::db::community::load_community_v2(&id)
            .map_err(VectorError::Other)?
            .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
        let ch = crate::community::ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(8));
        crate::community::v2::service::send_typing(&transport, &community, &ch)
            .await
            .map_err(VectorError::Other)
    }

    /// React to a Community message. `emoji_url` carries the NIP-30 image URL for a custom
    /// `:shortcode:` reaction (parity with DMs).
    pub async fn send_community_reaction(
        &self,
        channel_id: &str,
        message_id: &str,
        emoji: &str,
        emoji_url: Option<&str>,
    ) -> Result<()> {
        crate::db::scoped(async move {
            // Already ours — nothing to publish; the set can't hold it twice.
            if Self::own_reaction_id(message_id, emoji).await.is_some() {
                return Ok(());
            }
            let emoji_tags: Vec<crate::types::EmojiTag> = match emoji_url {
                Some(url) if emoji.starts_with(':') && emoji.ends_with(':') && emoji.len() >= 3 && !url.is_empty() => {
                    vec![crate::types::EmojiTag { shortcode: emoji[1..emoji.len() - 1].to_string(), url: url.to_string() }]
                }
                _ => Vec::new(),
            };
            let id = self.v2_community_for_channel(channel_id)?.ok_or_else(|| VectorError::Other("unknown community channel".into()))?;
            let community = crate::db::community::load_community_v2(&id)
                .map_err(VectorError::Other)?
                .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
            let ch = crate::community::ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
            let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
            // NIP-25 names the reacted-to author (a required `p`). STATE first, then
            // the persisted row (v2 history + the send echo live in the shared events
            // store, so this almost always resolves locally); the channel-page fetch
            // is the last resort for a target this device never saw.
            let held = {
                let st = state::STATE.lock().await;
                st.find_message(message_id)
                    .and_then(|(_, m)| m.npub.as_deref().and_then(|n| nostr_sdk::prelude::PublicKey::parse(n).ok()))
            };
            let held = held.or_else(|| {
                crate::db::events::event_author(message_id)
                    .ok()
                    .flatten()
                    .and_then(|n| nostr_sdk::prelude::PublicKey::parse(&n).ok())
            });
            let target_author = match held {
                Some(pk) => pk,
                None => crate::community::v2::service::fetch_channel(&transport, &community, &ch, 500)
                    .await
                    .map_err(VectorError::Other)?
                    .iter()
                    .find(|f| f.event.opened().rumor_id.to_hex() == message_id)
                    .map(|f| f.event.opened().author)
                    .ok_or_else(|| VectorError::Other("reacted-to message not found".into()))?,
            };
            // The author lookup straddled awaits against THIS account's community.
            let pair = emoji_tags.first().map(|t| (t.shortcode.as_str(), t.url.as_str()));
            // The NIP-25 `k` names the target's rumor kind. Stored rows don't keep
            // wire-kind fidelity yet, so a reaction to a received kind-1111 thread
            // reply claims `9` — Armada's fold ignores reaction `k`, and exact
            // threading lands with the thread-aware GUI.
            crate::community::v2::service::send_reaction(
                &transport, &community, &ch, message_id, &target_author.to_hex(), crate::community::v2::kind::MESSAGE, emoji, pair,
            )
            .await
            .map(|_| ())
            .map_err(VectorError::Other)
        })
        .await
    }

    /// Edit one of your own Community messages.
    pub async fn edit_community_message(&self, channel_id: &str, message_id: &str, new_content: &str) -> Result<()> {
        let id = self.v2_community_for_channel(channel_id)?.ok_or_else(|| VectorError::Other("unknown community channel".into()))?;
        // An edit names a Role in text only: it pings nobody anew.
        let (named, _) = crate::community::mentions::resolve_in(&crate::simd::hex::bytes_to_hex_32(&id.0), new_content);
        let (plain, text_spans) = crate::text_spans::extract_own(&named);
        let new_content = plain.as_str();
        let span_tags: Vec<nostr_sdk::prelude::Tag> = crate::text_spans::to_nostr_tags(&text_spans).collect();
        let emoji_tags = emoji_packs::resolve_outbound_emoji_tags(new_content);
        let community = crate::db::community::load_community_v2(&id)
            .map_err(VectorError::Other)?
            .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
        let ch = crate::community::ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
        let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
        let emoji_pairs: Vec<(&str, &str)> = emoji_tags.iter().map(|t| (t.shortcode.as_str(), t.url.as_str())).collect();
        crate::community::v2::service::send_edit_tagged(&transport, &community, &ch, message_id, new_content, &emoji_pairs, span_tags)
            .await
            .map(|_| ())
            .map_err(VectorError::Other)
    }

    /// Delete one of your own Community messages, resolving its channel from local
    /// history (the GUI path). A headless v2 consumer holds no local history — use
    /// [`Self::delete_community_message_in`] with the channel id instead.
    pub async fn delete_community_message(&self, message_id: &str) -> Result<()> {
        let channel_id = self.message_chat(message_id).await?;
        self.delete_community_message_in(&channel_id, message_id).await
    }

    /// The chat a message on this device was said in: memory first, then the store, which
    /// holds the rows a page served without loading them into memory.
    pub async fn message_chat(&self, message_id: &str) -> Result<String> {
        if let Some((_, chat)) = state::STATE.lock().await.find_chat_for_message(message_id) {
            return Ok(chat);
        }
        crate::db::events::locate_message(message_id)
            .map_err(VectorError::Other)?
            .chat
            .ok_or_else(|| VectorError::Other("message not found (already deleted?)".into()))
    }

    /// Delete one of your own Community messages (or reactions) in `channel_id`: its wraps off
    /// the relays by every key kept for them, then the in-plane kind-5 so peers drop it, plus
    /// best-effort attachment cleanup.
    pub async fn delete_community_message_in(&self, channel_id: &str, message_id: &str) -> Result<()> {
        use crate::community::transport::LiveTransport;
        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));

        // Attachment URLs come from local history when held (a headless v2 consumer
        // has none — blob cleanup is then the receiving peers' concern, not ours).
        let attachment_urls: Vec<String> = self
            .get_message(message_id)
            .await
            .map(|(_, msg)| msg.attachments.iter().flat_map(|a| a.all_urls().map(str::to_string)).collect())
            .unwrap_or_default();
        // Smart-forward gate: scrub only urls no OTHER message still references.
        let attachment_urls =
            crate::db::attachments::urls_unreferenced_elsewhere(&attachment_urls, message_id).unwrap_or_default();

        let id = self
            .v2_community_for_channel(channel_id)?
            .ok_or_else(|| VectorError::Other("unknown community channel".into()))?;
        let community = crate::db::community::load_community_v2(&id)
            .map_err(VectorError::Other)?
            .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
        let ch = crate::community::ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
        crate::community::v2::service::delete_own(&transport, &community, &ch, message_id, crate::community::v2::kind::MESSAGE)
            .await
            .map_err(VectorError::Other)?;
        // Best-effort attachment blob delete.
        if !attachment_urls.is_empty() {
            if let Some(_client) = state::nostr_client() {
                if let Ok(signer) = crate::signer::active_signer() {
                    crate::blossom::delete_blobs_best_effort(signer, attachment_urls);
                }
            }
        }
        let removed_chat = {
            let mut st = state::STATE.lock().await;
            st.remove_message(message_id).map(|(cid, _)| cid)
        };
        let _ = crate::db::events::delete_event(message_id).await;
        traits::emit_event_json("message_removed", serde_json::json!({
            "id": message_id, "chat_id": removed_chat.as_deref().unwrap_or(channel_id), "reason": "deleted",
        }));
        Ok(())
    }

    /// Moderation-hide someone ELSE's community message under `MANAGE_MESSAGES`
    /// (CORD-04 §3/§5). Seals the same kind-5 its authors use; peers re-derive the
    /// actor's authority from the signed inner against the folded Roster, so this is
    /// an authority claim peers verify, never a local suppression.
    pub async fn hide_community_message(&self, channel_id: &str, message_id: &str) -> Result<()> {
        use crate::community::transport::LiveTransport;
        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));

        // You can only moderate a message you can see: the author resolves from
        // STATE, then the store for a row that has paged out of the window.
        let author_npub = {
            let st = state::STATE.lock().await;
            st.find_message(message_id).and_then(|(_, m)| m.npub)
        };
        let author_npub = match author_npub {
            Some(n) => n,
            None => crate::db::events::event_author(message_id)
                .ok()
                .flatten()
                .ok_or_else(|| VectorError::Other("can't resolve the target message's author".into()))?,
        };
        let author = nostr_sdk::prelude::PublicKey::parse(&author_npub)
            .map_err(|_| VectorError::Other("target message has an unreadable author".into()))?;

        let id = self
            .v2_community_for_channel(channel_id)?
            .ok_or_else(|| VectorError::Other("unknown community channel".into()))?;
        let community = crate::db::community::load_community_v2(&id)
            .map_err(VectorError::Other)?
            .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
        let ch = crate::community::ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
        crate::community::v2::service::moderation_delete(
            &transport, &community, &ch, message_id, crate::community::v2::kind::MESSAGE, &author,
        )
        .await
        .map_err(VectorError::Other)?;

        let removed_chat = {
            let mut st = state::STATE.lock().await;
            st.remove_message(message_id).map(|(cid, _)| cid)
        };
        let _ = crate::db::events::delete_event(message_id).await;
        traits::emit_event_json("message_removed", serde_json::json!({
            "id": message_id, "chat_id": removed_chat.as_deref().unwrap_or(channel_id), "reason": "hidden",
        }));
        Ok(())
    }

    /// Catch a Community channel up from relays: the consensus catch-up (rekeys + control refold)
    /// plus a chat backfill. Returns `(new_message_count, warnings)`; `warnings` are NON-FATAL
    /// errors hit during the sync — surfaced rather than swallowed so a headless caller is never
    /// blind to "the sync ran but a catch-up failed."
    pub async fn sync_community_channel(&self, channel_id: &str, limit: usize) -> Result<(usize, Vec<String>)> {
        self.sync_community_channel_before(channel_id, limit, None).await
    }

    /// One page of a channel catch-up: what the relay served, and how much of it
    /// this client had never seen.
    pub async fn sync_community_channel_page(
        &self,
        channel_id: &str,
        limit: usize,
        before_secs: Option<u64>,
        since_secs: Option<u64>,
    ) -> Result<(BackfillCount, Vec<String>)> {
        let id = self.v2_community_for_channel(channel_id)?.ok_or_else(|| VectorError::Other("unknown community channel".into()))?;
        let warnings = if community::v2::realtime::follow_worker_running() {
            community::v2::realtime::enqueue_follow(&id);
            Vec::new()
        } else {
            Self::v2_inline_follow(&id).await
        };
        let count = Self::v2_backfill_channel_counted(
            &id, channel_id, limit, 8, since_secs, before_secs,
            crate::community::transport::Evidence::Fast, 12,
        ).await;
        Ok((count, warnings))
    }

    /// Fill the hole in a channel's held history that a scroll up from `before_ms` is about to
    /// cross, with the relay pages from its top down. The count of messages that arrived; 0 when
    /// there is no hole there, or the relays can't be reached (it stays for the next scroll).
    pub async fn fill_community_gap(&self, channel_id: &str, before_ms: u64) -> Result<usize> {
        let Some(gap) = history_gaps::gap_at(channel_id, before_ms / 1000) else {
            return Ok(0);
        };
        // From the hole's top: a reader can step into it lower down, past rows it held.
        let before = gap.hi + 1;
        let id = self.v2_community_for_channel(channel_id)?.ok_or_else(|| VectorError::Other("unknown community channel".into()))?;
        let count = Self::v2_backfill_channel_counted(
            &id, channel_id, 50, 2, None, Some(before),
            crate::community::transport::Evidence::Fast, 12,
        ).await;
        // A walk that can't step below where it began (a second holding more than its pages)
        // would be asked again on every scroll: let the hole go.
        if count.next_before.is_some_and(|n| n >= before) {
            history_gaps::abandon(channel_id, before);
        }
        Ok(count.new_messages)
    }

    /// [`sync_community_channel`](Self::sync_community_channel) with a back-paging
    /// cursor: `before_secs` bounds the fetch to messages at or older than it.
    ///
    /// The cursor is what reaches a v2 channel's PRE-ROTATION history. An
    /// uncursored catch-up reads the live epoch only (rotations move the
    /// conversation, so that is where it is); each epoch keeps its own plane
    /// address, and a bounded fetch spans all of them at once because messages are
    /// selected by time, not by epoch.
    pub async fn sync_community_channel_before(
        &self,
        channel_id: &str,
        limit: usize,
        before_secs: Option<u64>,
    ) -> Result<(usize, Vec<String>)> {
        // Consensus catch-up (rekeys then control refold) + chat backfill. With a
        // running listen() the coalescing worker owns the follow (never run inline beside
        // it — two concurrent follows can whole-row clobber); headless, walk it inline.
        // The chat page is fetched + persisted either way, so get_messages backfills.
        let id = self.v2_community_for_channel(channel_id)?.ok_or_else(|| VectorError::Other("unknown community channel".into()))?;
        let warnings = if community::v2::realtime::follow_worker_running() {
            community::v2::realtime::enqueue_follow(&id);
            Vec::new()
        } else {
            Self::v2_inline_follow(&id).await
        };
        // Deepest catch-up walk: pages × page-size bounds one reconnect's fetch.
        // Chat plane = fetch ASAP. NOTE: fetch_plane does not consult the
        // evidence tier yet (#370) — until it does, the transport-seconds
        // bound is the effective limit; the declared Fast records intent.
        let new = Self::v2_backfill_channel(
            &id, channel_id, limit, 8, None, before_secs,
            crate::community::transport::Evidence::Fast, 12,
        ).await;
        Ok((new, warnings))
    }

    /// Cursor-paged relay sync: fetch ONE page of up to `max_events` events from
    /// the channel's relays (per relay — divergent relays can push the union
    /// higher), ingest it, and return how many MESSAGES were new. A return of 0
    /// means the page held nothing new, not that the channel is empty.
    ///
    /// `until_s` / `since_s` are unix-seconds bounds (the back-paging cursor and
    /// the time floor). Depth comes from looping, not from a bigger page:
    /// `max_events` is clamped to 500 (relays clamp theirs anyway) and values
    /// under 50 behave as 50 on v2 (the shared pager's floor).
    ///
    /// Consensus (root rotations, control folds, ban checks) is the FULL sync's
    /// job — [`sync_community_channel`](Self::sync_community_channel) — so a
    /// hundred-page walk doesn't re-fold control a hundred times. Run one full
    /// sync (or be listening) before deep walks.
    pub async fn sync_channel_events(
        &self,
        channel_id: &str,
        max_events: usize,
        until_s: Option<u64>,
        since_s: Option<u64>,
    ) -> Result<usize> {
        let max = max_events.clamp(1, 500);
        let id = self.v2_community_for_channel(channel_id)?.ok_or_else(|| VectorError::Other("unknown community channel".into()))?;
        let community = crate::db::community::load_community_v2(&id)
            .map_err(VectorError::Other)?
            .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
        if community.dissolved {
            return Err(VectorError::Other("this community has been dissolved".into()));
        }
        let ch_id = crate::community::ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
        let ch = community
            .channel(&ch_id)
            .ok_or_else(|| VectorError::Other("no such channel in this community".into()))?;
        // Err, not a silent 0 — "granted but the key hasn't arrived" must be
        // distinguishable from "nothing new" or the caller diagnoses a mute bot.
        if ch.private && ch.key.is_none() {
            return Err(VectorError::Other(
                "this private channel has no key yet (awaiting rekey delivery)".into(),
            ));
        }
        let new = Self::v2_backfill_channel(
            &id, channel_id, max, 1, since_s, until_s,
            crate::community::transport::Evidence::Fast, 12,
        )
        .await;
        Ok(new)
    }

    /// The composer's `/` picker snapshot for `chat_id`, answered INSTANTLY
    /// from local state: the chat's bot-flagged members (kind-0 `bot: true` —
    /// the SDK sets it on every bot it builds) and their last-known manifests
    /// from the persistent store. When the last refresh is older than a minute
    /// (or the bot set changed), ONE background REQ re-fetches every bot's
    /// manifest together (5s unification window), persists newer editions, and
    /// emits `chat_commands_updated` — the UI swaps the list in when it lands.
    /// Works for BOTH community protocols (an invocation is plain content; only
    /// the optional routing tag is v2-only) and DMs. The manifest REQ always
    /// includes the discovery indexers beside the chat's own relays, so an
    /// unreachable or stranger-dropping community relay can't blind the picker.
    pub async fn get_chat_commands(&self, chat_id: &str) -> crate::bot_interface::ChatCommandsSnapshot {
        use crate::bot_interface::{self, ChatCommandsSnapshot};
        use nostr_sdk::prelude::ToBech32;

        let mut bots: Vec<nostr_sdk::prelude::PublicKey> = Vec::new();
        let mut relays: Vec<String> = Vec::new();
        let community_hex = crate::db::community::community_id_for_channel(chat_id).ok().flatten();
        if let Some(cid_hex) = community_hex {
            let Ok(Some(community)) = Self::load_held(&cid_hex) else {
                return ChatCommandsSnapshot { bots: 0, commands: Vec::new(), fresh: true };
            };
            let members = community::v2::service::stored_memberlist(&community).unwrap_or_default();
            relays = community.relays.clone();
            let state = crate::state::STATE.lock().await;
            for pk in members {
                let Ok(npub) = pk.to_bech32();
                if state.get_profile(&npub).map(|p| p.flags.is_bot()).unwrap_or(false) {
                    bots.push(pk);
                }
            }
        } else if chat_id.starts_with("npub1") {
            if let Ok(pk) = nostr_sdk::prelude::PublicKey::parse(chat_id) {
                let is_bot = {
                    let state = crate::state::STATE.lock().await;
                    state.get_profile(chat_id).map(|p| p.flags.is_bot()).unwrap_or(false)
                };
                if is_bot {
                    bots.push(pk);
                    // The counterpart published its manifest to its own login
                    // relays/indexers — our connected pool is the read set.
                    if let Some(client) = crate::state::nostr_client() {
                        relays = client.relays().await.keys().map(|u| u.to_string()).collect();
                    }
                }
            }
        }

        if bots.is_empty() {
            return ChatCommandsSnapshot { bots: 0, commands: Vec::new(), fresh: true };
        }
        // The chat's own relays PLUS the discovery indexers, one REQ across the
        // union — a room whose relays refuse kind 10304 still resolves.
        relays.extend(bot_interface::DISCOVERY_RELAYS.iter().map(|s| s.to_string()));
        relays.sort();
        relays.dedup();
        // Deterministic order: the freshness check compares the exact bot set,
        // and picker sections stay stable across refreshes.
        bots.sort_by_key(|p| p.to_hex());
        let bot_hexes: Vec<String> = bots.iter().map(|p| p.to_hex()).collect();
        let commands = bot_interface::assemble_from_store(&bot_hexes);
        let fresh = bot_interface::commands_fresh(chat_id, &bot_hexes);
        if !fresh {
            bot_interface::spawn_commands_refresh(chat_id.to_string(), bots.clone(), relays);
        }
        ChatCommandsSnapshot { bots: bots.len(), commands, fresh }
    }

    /// Members of a Community: the Complete Memberlist, each entry `{npub}` (it carries no
    /// activity time). One only seen posting, outside the Guestbook's members, also carries
    /// `unlisted` (`"no_join"` or `"departed"`): listed, but never counted, since what this
    /// client has seen depends on how much history it holds. Best-effort throughout: a
    /// transport failure yields an empty list, never an error.
    pub async fn get_community_members(&self, community_id: &str) -> Vec<serde_json::Value> {
        use nostr_sdk::prelude::ToBech32;
        // The Complete Memberlist from LOCAL state (persisted guestbook +
        // observed authors + roster grantees − banlist). The store is seeded
        // post-join and cursor-caught-up by the follow worker (boot/reconnect) +
        // live ingest; a cold store (a hold predating the store) seeds in the
        // background and refreshes the UI when it lands.
        let Ok(Some(community)) = Self::load_held(community_id) else { return Vec::new() };
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let (events, cursor) = crate::db::community::get_guestbook_shared(&cid_hex).unwrap_or_default();
        if cursor == 0 {
            if crate::community::v2::realtime::follow_worker_running() {
                crate::community::v2::realtime::enqueue_follow(community.id());
            } else {
                let c2 = community.clone();
                db::spawn_bound(async move {
                    let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(20));
                    if matches!(crate::community::v2::service::sync_guestbook(&transport, &c2).await, Ok(fresh) if !fresh.is_empty()) {
                        emit_event("community_refreshed", &serde_json::json!({ "community_id": cid_hex }));
                    }
                });
            }
        }
        let parts = crate::community::v2::service::stored_member_parts(&community, &events).unwrap_or_default();
        let counted = parts.counted.into_iter().filter_map(|pk| pk.to_bech32().ok()).map(|npub| serde_json::json!({ "npub": npub }));
        let unlisted = parts
            .unlisted
            .into_iter()
            .filter_map(|(pk, why)| pk.to_bech32().ok().map(|npub| serde_json::json!({ "npub": npub, "unlisted": why })));
        counted.chain(unlisted).collect()
    }

    /// A Community's banlist, as npubs.
    ///
    /// The counterpart to [`Self::set_member_banned`], which had none: setting a
    /// ban succeeds identically whether or not one was already in place, so a
    /// caller lifting a ban could not tell whether it changed anything, and
    /// anything reporting on it was guessing.
    ///
    /// Read from local state, so it reflects the last banlist edition this
    /// client folded rather than a fresh fetch.
    pub fn get_community_banned(&self, community_id: &str) -> Vec<String> {
        use nostr_sdk::prelude::{PublicKey, ToBech32};
        // Resolve the id the same way the moderation panel does: a caller may
        // hold a logical id that is not the row key.
        let cid_hex = match Self::load_held(community_id) {
            Ok(Some(c)) => crate::simd::hex::bytes_to_hex_32(&c.id().0),
            _ => community_id.to_string(),
        };
        crate::db::community::get_community_banlist(&cid_hex)
            .unwrap_or_default()
            .iter()
            .filter_map(|hex| PublicKey::parse(hex).ok())
            .filter_map(|pk| pk.to_bech32().ok())
            .collect()
    }

    /// Everything the moderation panel needs about one Community, read once so the
    /// parts agree with each other: every member scored against the raid evidence
    /// ([`crate::community::raid`]), the duplicate-text cohorts behind those verdicts,
    /// the live invite links, and what the caller may actually do about it.
    ///
    /// v2 only — the containment this feeds (batch ban, refounding) are v2 verbs.
    pub fn community_moderation_intel(&self, community_id: &str) -> Result<serde_json::Value> {
        let community = Self::load_held(community_id)?
            .ok_or_else(|| VectorError::Other("moderation tools require a Concord v2 community".into()))?;
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let report = Self::policy_console_report(&cid_hex, &community)?;
        let invites = crate::db::community::list_public_invites(&cid_hex).unwrap_or_default();
        let banlist = crate::db::community::get_community_banlist(&cid_hex).unwrap_or_default();
        let caps = self.community_capabilities(community_id).unwrap_or_else(|_| serde_json::json!({}));
        let owner_b32 = community.owner().map_err(VectorError::Other)?.to_bech32().unwrap_or_default();
        // Who the member list marks as only seen posting: assessed like everyone, never counted.
        let unlisted: Vec<String> = crate::db::community::get_guestbook_shared(&cid_hex)
            .ok()
            .and_then(|(events, _)| crate::community::v2::service::stored_member_parts(&community, &events).ok())
            .map(|p| p.unlisted.into_keys().filter_map(|pk| pk.to_bech32().ok()).collect())
            .unwrap_or_default();

        Ok(serde_json::json!({
            "community_id": cid_hex,
            "name": community.name,
            "owner_npub": owner_b32,
            "epoch": community.root_epoch.0,
            "report": &*report,
            "unlisted": unlisted,
            "invites": invites.iter().map(|i| serde_json::json!({
                "token": i.token,
                "label": i.label,
                "created_at": i.created_at,
                "expires_at": i.expires_at,
                "join_count": i.join_count,
            })).collect::<Vec<_>>(),
            "banlist_count": banlist.len(),
            "banlist_max": crate::community::v2::roles::MAX_BANLIST,
            "capabilities": caps,
            // The designer offers per-channel exemptions, and this is the
            // console's own data source — one place to ask, one answer.
            "channels": community.channels.iter().map(|c| serde_json::json!({
                "id": crate::simd::hex::bytes_to_hex_32(&c.id.0),
                "name": c.name,
            })).collect::<Vec<_>>(),
        }))
    }

    /// Screen ONE message immediately, without waiting for a sweep.
    ///
    /// Runs only the stateless rules — words, links, regex, mentions — because
    /// those are the only ones a single message can answer. Rate, repetition
    /// and cohorts describe a window and stay with the periodic evaluation.
    ///
    /// Costs no corpus read and no cache: the whole point is that a word filter
    /// should answer in milliseconds, not on the next 90-second tick.
    pub fn screen_community_message(
        &self,
        channel_id: &str,
        author_npub: &str,
        text: &str,
    ) -> Result<serde_json::Value> {
        use nostr_sdk::prelude::PublicKey;
        let Some(id) = self.v2_community_for_channel(channel_id)? else {
            return Ok(serde_json::json!({ "findings": [] }));
        };
        let community = crate::db::community::load_community_v2(&id)
            .map_err(VectorError::Other)?
            .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let owner = community.owner().map_err(VectorError::Other)?;
        let author = PublicKey::parse(author_npub).map_err(|_| VectorError::Other("unreadable author".into()))?;

        // Same staff definition the console uses: a role carrying a moderation
        // permission bit, never mere role membership.
        use crate::community::roles::Permissions;
        const MOD_MASK: u64 = Permissions::MANAGE_ROLES
            | Permissions::MANAGE_CHANNELS
            | Permissions::MANAGE_METADATA
            | Permissions::KICK
            | Permissions::BAN
            | Permissions::MANAGE_MESSAGES;
        let roster = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
        let hex = author.to_hex();
        let roles: Vec<String> =
            roster.grants.iter().find(|g| g.member == hex).map(|g| g.role_ids.clone()).unwrap_or_default();
        let is_staff = roles
            .iter()
            .any(|rid| roster.roles.iter().any(|r| &r.role_id == rid && (r.permissions.0 & MOD_MASK) != 0));

        let now_ms = crate::clock::now_ms();
        let findings = crate::community::policy::harness::screen_message(
            &cid_hex, &owner, &author, &roles, is_staff, channel_id, text, now_ms,
        );
        Ok(serde_json::json!({ "findings": findings }))
    }

    /// The raid verdict alone, for the badge on a community header. Same assessment as
    /// the panel and served from the same cache, so surfacing the alert costs nothing
    /// once and then nothing at all until it expires.
    pub fn check_community_raid(&self, community_id: &str) -> Result<serde_json::Value> {
        let Some(community) = Self::load_held(community_id)? else {
            return Ok(serde_json::json!({ "detected": false }));
        };
        // A raid alarm is a call to act, and only BAN can answer it (the console's
        // containment verbs all need it). Anyone else would be alarmed with nothing
        // to do, and would pay for a four-thousand-message scan to get there.
        let caps = self.community_capabilities(community_id)?;
        if caps["ban"].as_bool() != Some(true) {
            return Ok(serde_json::json!({ "detected": false }));
        }
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let report = Self::policy_console_report(&cid_hex, &community)?;
        let biggest = report["cohorts"].get(0);
        Ok(serde_json::json!({
            "detected": report["raid_detected"].as_bool().unwrap_or(false),
            "suspects": report["suspects"].as_u64().unwrap_or(0),
            "cohort": biggest.and_then(|c| c["size"].as_u64()).unwrap_or(0),
            "sample": biggest
                .and_then(|c| c["sample"].as_str())
                .map(|s| s.chars().take(60).collect::<String>())
                .unwrap_or_default(),
        }))
    }

    /// Assess a community, memoised for [`RAID_REPORT_TTL_SECS`]. The read decrypts a
    /// four-thousand-message window, so a header badge asking on every render would be a
    /// real cost; the panel opening moments later reuses the same answer.
    fn raid_report(cid_hex: &str) -> Result<std::sync::Arc<crate::community::raid::RaidReport>> {
        use crate::community::raid;
        use crate::community::v2::guestbook::GuestbookEntry;
        use nostr_sdk::prelude::PublicKey;
        use std::collections::{HashMap, HashSet};

        let now_secs = crate::clock::now_secs();
        if let Some(report) = report_get(&raid_report_cache(), cid_hex, now_secs) {
            return Ok(report);
        }
        let community = crate::db::community::load_community_v2(&crate::community::CommunityId(
            crate::simd::hex::hex_to_bytes_32(cid_hex),
        ))
        .map_err(VectorError::Other)?
        .ok_or_else(|| VectorError::Other("moderation tools require a Concord v2 community".into()))?;
        let owner_b32 = community.owner().map_err(VectorError::Other)?.to_bech32().unwrap_or_default();
        let me_b32 = state::my_public_key().and_then(|p| p.to_bech32().ok()).unwrap_or_default();

        // Anyone holding a live grant is staff, whatever the role is called.
        let roster = crate::db::community::get_community_roles(cid_hex).unwrap_or_default();
        let staff: HashSet<String> = roster
            .grants
            .iter()
            .filter(|g| !g.role_ids.is_empty())
            .filter_map(|g| PublicKey::from_hex(&g.member).ok().and_then(|pk| pk.to_bech32().ok()))
            .collect();

        // The same fold the member list paints, so the panel can't disagree with it.
        let members: Vec<String> = crate::community::v2::service::stored_memberlist(&community)
            .unwrap_or_default()
            .into_iter()
            .filter_map(|pk| pk.to_bech32().ok())
            .collect();

        // Guestbook: authoritative joins, with the invite each one came through.
        let (events, _cursor) = crate::db::community::get_guestbook(cid_hex).unwrap_or_default();
        let mut joined_at: HashMap<String, u64> = HashMap::new();
        let mut invite_label: HashMap<String, String> = HashMap::new();
        for e in &events {
            let GuestbookEntry::Join { member, invited_by, at_ms } = &e.entry else { continue };
            let Ok(b32) = member.to_bech32();
            // Earliest join wins: a rejoin must not erase real tenure.
            let slot = joined_at.entry(b32.clone()).or_insert(*at_ms);
            *slot = (*slot).min(*at_ms);
            if let Some((_creator, label)) = invited_by {
                invite_label.entry(b32).or_insert_with(|| label.clone());
            }
        }

        let footprints: HashMap<String, crate::db::community::AuthorFootprint> =
            crate::db::community::community_author_footprints(cid_hex)
                .unwrap_or_default()
                .into_iter()
                .map(|f| (f.npub.clone(), f))
                .collect();

        // Cohort evidence comes from the recent window only — a raid is by definition
        // recent, and the whole history would cost a vault decrypt per row.
        const TEXT_WINDOW: usize = 4_000;
        let mut texts: HashMap<String, (Vec<String>, Vec<u64>)> = HashMap::new();
        for (npub, at, text) in crate::db::community::community_recent_texts(cid_hex, TEXT_WINDOW).unwrap_or_default() {
            let slot = texts.entry(npub).or_default();
            slot.0.push(text);
            slot.1.push(at);
        }

        let signals: Vec<raid::MemberSignals> = members
            .iter()
            .map(|npub| {
                let f = footprints.get(npub);
                raid::MemberSignals {
                    npub: npub.clone(),
                    joined_at_ms: joined_at.get(npub).copied().unwrap_or(0),
                    invite_label: invite_label.get(npub).cloned(),
                    messages: f.map(|f| f.messages).unwrap_or(0),
                    first_secs: f.map(|f| f.first_secs).unwrap_or(0),
                    last_secs: f.map(|f| f.last_secs).unwrap_or(0),
                    texts: texts.get(npub).map(|t| t.0.clone()).unwrap_or_default(),
                    text_secs: texts.get(npub).map(|t| t.1.clone()).unwrap_or_default(),
                    is_owner: *npub == owner_b32,
                    is_admin: staff.contains(npub),
                    is_me: *npub == me_b32,
                }
            })
            .collect();

        let params = raid::RaidParams {
            known_shortcodes: crate::emoji_packs::known_shortcodes(),
            ..Default::default()
        };
        let report = std::sync::Arc::new(raid::assess(&signals, now_secs, &params));
        report_put(&raid_report_cache(), cid_hex, now_secs, report.clone());
        Ok(report)
    }

    /// The preset library: what a designer offers instead of a blank document.
    pub fn policy_presets(&self) -> Result<serde_json::Value> {
        let presets: Vec<serde_json::Value> = crate::community::policy::presets::all()
            .into_iter()
            .map(|p| {
                serde_json::json!({
                    "id": p.id,
                    "name": p.name,
                    "description": p.description,
                    "example": p.example,
                    "caveat": p.caveat,
                    "dials": p.dials,
                    // Every rule in plain language: a template whose behaviour
                    // you can only infer from its name is the same black box
                    // the shipped defaults used to be.
                    "rules": crate::community::policy::presets::describe(&p.policy),
                    "bytes": serde_json::to_string(&p.policy).unwrap_or_default(),
                })
            })
            .collect();
        // The from-scratch builder's catalogue rides along: it is fetched at the
        // same moment, and its numbers must come from the same place the
        // presets' do.
        let rule_kinds: Vec<serde_json::Value> = crate::community::policy::presets::rule_kinds()
            .into_iter()
            .map(|k| {
                serde_json::json!({
                    "id": k.id,
                    "label": k.label,
                    "description": k.description,
                    "input": k.input,
                    "input_label": k.input_label,
                    "input_hint": k.input_hint,
                    "rule": k.rule,
                })
            })
            .collect();
        Ok(serde_json::json!({ "presets": presets, "rule_kinds": rule_kinds }))
    }

    /// What a candidate policy WOULD do, against real history. Stores nothing,
    /// publishes nothing, removes nobody — the designer never enables a policy
    /// from a form alone, only from a preview that named who it would catch.
    pub fn preview_community_policy(&self, community_id: &str, bytes: &str) -> Result<serde_json::Value> {
        use crate::community::v2::guestbook::GuestbookEntry;
        let community = Self::load_held(community_id)?
            .ok_or_else(|| VectorError::Other("policies require a Concord v2 community".into()))?;
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let owner = community.owner().map_err(VectorError::Other)?;
        let me = state::my_public_key();

        use crate::community::roles::Permissions;
        const MOD_MASK: u64 = Permissions::MANAGE_ROLES
            | Permissions::MANAGE_CHANNELS
            | Permissions::MANAGE_METADATA
            | Permissions::KICK
            | Permissions::BAN
            | Permissions::MANAGE_MESSAGES;
        let roster = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
        let staff: std::collections::HashSet<String> = roster
            .grants
            .iter()
            .filter(|g| {
                g.role_ids
                    .iter()
                    .any(|rid| roster.roles.iter().any(|r| &r.role_id == rid && (r.permissions.0 & MOD_MASK) != 0))
            })
            .map(|g| g.member.clone())
            .collect();
        let roles_of: std::collections::HashMap<String, Vec<String>> =
            roster.grants.iter().map(|g| (g.member.clone(), g.role_ids.clone())).collect();

        let (events, _cursor) = crate::db::community::get_guestbook_shared(&cid_hex).unwrap_or_default();
        let mut joined_at: std::collections::HashMap<String, u64> = std::collections::HashMap::new();
        let mut invite_label: std::collections::HashMap<String, String> = std::collections::HashMap::new();
        for e in events.iter() {
            let GuestbookEntry::Join { member, invited_by, at_ms } = &e.entry else { continue };
            let hex = member.to_hex();
            let slot = joined_at.entry(hex.clone()).or_insert(*at_ms);
            *slot = (*slot).min(*at_ms);
            if let Some((_c, label)) = invited_by {
                invite_label.entry(hex).or_insert_with(|| label.clone());
            }
        }
        let members: Vec<crate::community::policy::harness::MemberRow> =
            crate::community::v2::service::stored_memberlist(&community)
                .unwrap_or_default()
                .into_iter()
                .map(|pk| {
                    let hex = pk.to_hex();
                    (
                        pk,
                        joined_at.get(&hex).copied(),
                        staff.contains(&hex),
                        roles_of.get(&hex).cloned().unwrap_or_default(),
                        invite_label.get(&hex).cloned(),
                    )
                })
                .collect();

        let now_ms = crate::clock::now_ms();
        let assembled =
            crate::community::policy::harness::assemble(&cid_hex, &owner, me.as_ref(), &members, now_ms)
                .map_err(VectorError::Other)?;
        let preview = crate::community::policy::harness::preview_policy(&assembled, bytes, now_ms);
        serde_json::to_value(preview).map_err(|e| VectorError::Other(e.to_string()))
    }

    /// A community's policies, as stored. Returns the exact bytes, so an editor
    /// round-trips what was written rather than a re-serialization of it.
    pub fn list_community_policies(&self, community_id: &str) -> Result<serde_json::Value> {
        let community = Self::load_held(community_id)?
            .ok_or_else(|| VectorError::Other("policies require a Concord v2 community".into()))?;
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let stored = crate::db::community::get_community_policies(&cid_hex).map_err(VectorError::Other)?;
        let rows: Vec<serde_json::Value> = stored
            .iter()
            .map(|p| {
                // Report what the validator says NOW: a policy stored under an
                // older engine can stop validating, and a moderator must see
                // that rather than assume their rules are running.
                let verdict = serde_json::from_str::<crate::community::policy::document::Policy>(&p.bytes)
                    .map_err(|e| e.to_string())
                    .and_then(|doc| doc.validate().map_err(|r| format!("{r:?}")));
                serde_json::json!({
                    "policy_id": p.policy_id,
                    "hash": p.hash,
                    "enabled": p.enabled,
                    "updated_at": p.updated_at,
                    "bytes": p.bytes,
                    "valid": verdict.is_ok(),
                    "error": verdict.err(),
                })
            })
            .collect();
        Ok(serde_json::json!({
            "community_id": cid_hex,
            "policies": rows,
            // Must agree with `select_policies`, which is the thing that
            // actually decides: the shipped defaults run unless the community
            // has forked them. A flag derived any other way tells a moderator
            // their cover is on while the engine has stood it down.
            "using_builtin": !stored
                .iter()
                .any(|p| p.policy_id == crate::community::policy::harness::DEFAULTS_POLICY_ID),
        }))
    }

    /// Store a policy, validating FIRST. An invalid policy is a rejected edit,
    /// never a stored one that quietly evaluates to nothing.
    pub fn set_community_policy(&self, community_id: &str, policy_id: &str, bytes: &str, enabled: bool) -> Result<serde_json::Value> {
        let community = Self::load_held(community_id)?
            .ok_or_else(|| VectorError::Other("policies require a Concord v2 community".into()))?;
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        if bytes.len() > crate::community::policy::types::caps::MAX_POLICY_BYTES {
            return Err(VectorError::Other("policy exceeds the maximum document size".into()));
        }
        let doc: crate::community::policy::document::Policy =
            serde_json::from_str(bytes).map_err(|e| VectorError::Other(format!("policy is not valid JSON: {e}")))?;
        doc.validate().map_err(|r| VectorError::Other(format!("policy rejected: {r:?}")))?;

        let hash = crate::community::policy::harness::hash_policy_bytes(bytes.as_bytes());
        let hash_hex = crate::simd::hex::bytes_to_hex_32(&hash.0);
        let now_secs = crate::clock::now_secs();
        crate::db::community::set_community_policy(&cid_hex, policy_id, bytes, &hash_hex, enabled, now_secs)
            .map_err(VectorError::Other)?;
        // The console must not keep serving verdicts from the rules that were
        // in force a minute ago.
        Self::invalidate_raid_report(&cid_hex);
        Ok(serde_json::json!({ "policy_id": policy_id, "hash": hash_hex, "enabled": enabled }))
    }

    pub fn delete_community_policy(&self, community_id: &str, policy_id: &str) -> Result<()> {
        let community = Self::load_held(community_id)?
            .ok_or_else(|| VectorError::Other("policies require a Concord v2 community".into()))?;
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        crate::db::community::delete_community_policy(&cid_hex, policy_id).map_err(VectorError::Other)?;
        Self::invalidate_raid_report(&cid_hex);
        Ok(())
    }

    /// The built-in policy, as editable bytes — the starting point an editor
    /// offers instead of a blank document.
    pub fn builtin_policy_json(&self) -> Result<String> {
        serde_json::to_string_pretty(&crate::community::policy::harness::default_policy())
            .map_err(|e| VectorError::Other(e.to_string()))
    }

    /// The moderation console's report, from the POLICY ENGINE. Memoised for
    /// [`RAID_REPORT_TTL_SECS`], same as the assessor it replaces.
    ///
    /// `raid.rs` still runs — [`Self::policy_side_by_side`] diffs the two — but
    /// the panel reads this. The engine earned it on live data: it clustered a
    /// real raid out of local storage and stayed silent on a healthy community
    /// across six runs.
    fn policy_console_report(cid_hex: &str, community: &crate::community::v2::community::CommunityV2) -> Result<std::sync::Arc<serde_json::Value>> {
        let now_secs = crate::clock::now_secs();
        report_once(&policy_report_cache(), &policy_report_gate(), cid_hex, now_secs, || {
            Self::evaluate_policy_console(cid_hex, community, now_secs)
        })
    }

    fn evaluate_policy_console(
        cid_hex: &str,
        community: &crate::community::v2::community::CommunityV2,
        now_secs: u64,
    ) -> Result<std::sync::Arc<serde_json::Value>> {
        use crate::community::v2::guestbook::GuestbookEntry;
        let owner = community.owner().map_err(VectorError::Other)?;
        let me = state::my_public_key();

        // Staff = a role carrying moderation permissions. NOT mere role
        // membership: a cosmetic or self-serve role must never confer immunity
        // from the rules this engine exists to enforce.
        use crate::community::roles::Permissions;
        const MOD_MASK: u64 = Permissions::MANAGE_ROLES
            | Permissions::MANAGE_CHANNELS
            | Permissions::MANAGE_METADATA
            | Permissions::KICK
            | Permissions::BAN
            | Permissions::MANAGE_MESSAGES;
        let roster = crate::db::community::get_community_roles(cid_hex).unwrap_or_default();
        let staff: std::collections::HashSet<String> = roster
            .grants
            .iter()
            .filter(|g| {
                g.role_ids
                    .iter()
                    .any(|rid| roster.roles.iter().any(|r| &r.role_id == rid && (r.permissions.0 & MOD_MASK) != 0))
            })
            .map(|g| g.member.clone())
            .collect();
        let roles_of: std::collections::HashMap<String, Vec<String>> =
            roster.grants.iter().map(|g| (g.member.clone(), g.role_ids.clone())).collect();

        let (events, _cursor) = crate::db::community::get_guestbook(cid_hex).unwrap_or_default();
        let mut joined_at: std::collections::HashMap<String, u64> = std::collections::HashMap::new();
        let mut invite_label: std::collections::HashMap<String, String> = std::collections::HashMap::new();
        for e in &events {
            let GuestbookEntry::Join { member, invited_by, at_ms } = &e.entry else { continue };
            let hex = member.to_hex();
            // Earliest join wins: a rejoin must not erase real tenure.
            let slot = joined_at.entry(hex.clone()).or_insert(*at_ms);
            *slot = (*slot).min(*at_ms);
            if let Some((_creator, label)) = invited_by {
                invite_label.entry(hex).or_insert_with(|| label.clone());
            }
        }

        let members: Vec<crate::community::policy::harness::MemberRow> =
            crate::community::v2::service::stored_memberlist(community)
                .unwrap_or_default()
                .into_iter()
                .map(|pk| {
                    let hex = pk.to_hex();
                    (
                        pk,
                        joined_at.get(&hex).copied(),
                        staff.contains(&hex),
                        roles_of.get(&hex).cloned().unwrap_or_default(),
                        invite_label.get(&hex).cloned(),
                    )
                })
                .collect();

        let now_ms = now_secs.saturating_mul(1000);
        let assembled =
            crate::community::policy::harness::assemble(cid_hex, &owner, me.as_ref(), &members, now_ms)
                .map_err(VectorError::Other)?;
        Ok(std::sync::Arc::new(
            crate::community::policy::harness::evaluate_for_console(cid_hex, &assembled, now_ms)
                .map_err(VectorError::Other)?,
        ))
    }

    /// Run the policy engine beside the shipped assessor and report where they
    /// disagree. Diagnostic only: the engine convicts nothing in production
    /// until this diff has been read against real data.
    pub fn policy_side_by_side(&self, community_id: &str) -> Result<serde_json::Value> {
        use crate::community::v2::guestbook::GuestbookEntry;
        use nostr_sdk::prelude::PublicKey;
        let community = Self::load_held(community_id)?
            .ok_or_else(|| VectorError::Other("moderation tools require a Concord v2 community".into()))?;
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let owner = community.owner().map_err(VectorError::Other)?;

        // The moderation permission bits: holding one of these is staff. Mere
        // role membership is NOT — a cosmetic role must not confer immunity.
        use crate::community::roles::Permissions;
        const MOD_MASK: u64 = Permissions::MANAGE_ROLES
            | Permissions::MANAGE_CHANNELS
            | Permissions::MANAGE_METADATA
            | Permissions::KICK
            | Permissions::BAN
            | Permissions::MANAGE_MESSAGES;
        let roster = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
        let staff: std::collections::HashSet<String> = roster
            .grants
            .iter()
            .filter(|g| {
                g.role_ids.iter().any(|rid| {
                    roster.roles.iter().any(|r| &r.role_id == rid && (r.permissions.0 & MOD_MASK) != 0)
                })
            })
            .map(|g| g.member.clone())
            .collect();
        let roles_of: std::collections::HashMap<String, Vec<String>> =
            roster.grants.iter().map(|g| (g.member.clone(), g.role_ids.clone())).collect();

        let (events, _cursor) = crate::db::community::get_guestbook_shared(&cid_hex).unwrap_or_default();
        let mut joined_at: std::collections::HashMap<String, u64> = std::collections::HashMap::new();
        for e in events.iter() {
            let GuestbookEntry::Join { member, at_ms, .. } = &e.entry else { continue };
            let hex = member.to_hex();
            let slot = joined_at.entry(hex).or_insert(*at_ms);
            *slot = (*slot).min(*at_ms);
        }

        let members: Vec<(PublicKey, Option<u64>, bool, Vec<String>)> =
            crate::community::v2::service::stored_memberlist(&community)
                .unwrap_or_default()
                .into_iter()
                .map(|pk| {
                    let hex = pk.to_hex();
                    (pk, joined_at.get(&hex).copied(), staff.contains(&hex), roles_of.get(&hex).cloned().unwrap_or_default())
                })
                .collect();

        // The assessor's own verdicts, for the diff.
        let assessments: Vec<(String, String)> = Self::raid_report(&cid_hex)
            .map(|r| {
                r.members
                    .iter()
                    .map(|m| (m.npub.clone(), format!("{:?}", m.verdict).to_lowercase()))
                    .collect()
            })
            .unwrap_or_default();

        let now_ms = crate::clock::now_ms();
        let diff = crate::community::policy::harness::run_side_by_side(
            &cid_hex, &owner, &members, &assessments, now_ms,
        )
        .map_err(VectorError::Other)?;
        serde_json::to_value(diff).map_err(|e| VectorError::Other(e.to_string()))
    }

    /// Drop a community's memoised verdict. Every moderation action changes who is a
    /// member, so serving the pre-action answer would leave the badge accusing people
    /// who are already gone.
    pub fn invalidate_raid_report(community_id: &str) {
        policy_report_cache().lock().unwrap_or_else(|e| e.into_inner()).remove(community_id);
        raid_report_cache().lock().unwrap_or_else(|e| e.into_inner()).remove(community_id);
    }

    /// Rotate the Community's keys with no banlist edit: mint a new root epoch that
    /// only `retain` can follow. This is the containment that scales — a wave of
    /// thousands cannot fit in a 500-entry banlist, but it can be locked out of the
    /// next epoch in one publish. `retain` is a keep-list; everyone else is cut.
    ///
    /// Passing an empty `retain` rotates without removing anyone, which is what you
    /// want when the invite link leaked but the members are all real.
    pub async fn refound_community(&self, community_id: &str, retain: &[&str]) -> Result<()> {
        let community = Self::load_held(community_id)?
            .ok_or_else(|| VectorError::Other("re-founding requires a Concord v2 community".into()))?;
        let removed = Self::members_to_remove(&community, retain)?;
        let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(30));
        crate::community::v2::service::refound_community(&transport, &community, &removed)
            .await
            .map_err(VectorError::Other)?;
        // The cut changed who is a member; the memoised verdict still names them.
        Self::invalidate_raid_report(community_id);
        Ok(())
    }

    /// The members a `retain` keep-list would cut.
    ///
    /// Folded from the LOCAL store, and that is not an oversight. The network memberlist
    /// is epoch-scoped — its Guestbook plane holds only the current epoch's snapshot, and
    /// its channel reads only return what is decryptable now — so members stranded on a
    /// buried epoch are already absent from it. Those are precisely the phantoms this
    /// panel exists to clear: they survive ONLY in the local store, which accumulates
    /// across epochs. Folding the network list here returns an empty removal set and the
    /// sweep does nothing.
    ///
    /// The two lists answer different questions and must not be unified. "Who receives a
    /// new key" is the rotation's own network fold, which it does for itself. "Who is a
    /// phantom to evict" is this one, and being local-only is the definition of it.
    ///
    /// An empty `retain` removes nobody — a rotation for its own sake. You and the owner
    /// are never in the result: a keep-list omitting either is a caller mistake, and
    /// honouring it would lock the community's own staff out of an epoch they just minted.
    fn members_to_remove(
        community: &crate::community::v2::community::CommunityV2,
        retain: &[&str],
    ) -> Result<Vec<nostr_sdk::prelude::PublicKey>> {
        use nostr_sdk::prelude::PublicKey;
        let keep: std::collections::HashSet<PublicKey> =
            retain.iter().filter_map(|n| PublicKey::parse(n).ok()).collect();
        if keep.is_empty() {
            return Ok(Vec::new());
        }
        let me = state::my_public_key();
        let owner = community.owner().ok();
        Ok(crate::community::v2::service::stored_memberlist(community)
            .map_err(VectorError::Other)?
            .into_iter()
            .filter(|pk| !keep.contains(pk))
            .filter(|pk| Some(*pk) != me && Some(*pk) != owner)
            .collect())
    }

    /// Rotate the keys around the survivors, then kick the removed off the roster.
    ///
    /// The order is load-bearing, and it is ROTATE FIRST. A Guestbook plane is derived
    /// per epoch, so kicks published before the rotation land on a plane the rotation
    /// immediately buries: every reader then has to receive them in the window before it
    /// follows the rekey, and whatever is still in flight is never folded by anyone.
    /// Publishing onto the NEW epoch instead puts the departures on the plane every
    /// survivor will read from now on, so a client that catches up an hour later still
    /// folds them. It also closes the re-admission window — the removed hold no key at
    /// the new epoch, so they cannot post their way back into the memberlist between
    /// their own kick and the rotation.
    ///
    /// The rotation alone would not clear the roster: the guestbook store is keyed by
    /// community and appended across epochs, and the memberlist re-admits observed
    /// authors from local history regardless of epoch. The kicks are what evict them.
    pub async fn purge_and_refound(
        &self,
        community_id: &str,
        retain: &[&str],
        on_progress: &(dyn Fn(usize, usize) + Sync),
    ) -> Result<serde_json::Value> {
        let community = Self::load_held(community_id)?
            .ok_or_else(|| VectorError::Other("re-founding requires a Concord v2 community".into()))?;
        let removed = Self::members_to_remove(&community, retain)?;
        // The operator's list IS the recipient set. `removed` is derived from the
        // memberlist at THIS instant and only drives the kick sweep below; the refound
        // fetches its own, later. Passing removal alone let an account that appeared in
        // between be vended a key by default — implicitly retained by the purge.
        let keep: Vec<nostr_sdk::prelude::PublicKey> = retain
            .iter()
            .filter_map(|n| nostr_sdk::prelude::PublicKey::parse(n).ok())
            .collect();
        log_info!("[Moderation] purge: {} to remove, {} retained", removed.len(), keep.len());
        let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(30));
        // An EMPTY retain means "cut nobody", not "keep nobody".
        //
        // The two lines above read the same empty list in opposite directions:
        // `members_to_remove` correctly removes nobody, while `keep` becomes an empty
        // ALLOW-LIST — and an allow-list keeps only this device and the owner, so a
        // plain "Rotate keys" vended to two people and stranded everyone else at the
        // previous epoch, permanently. It presented as members vanishing from the
        // list some time later, nowhere near the button that did it.
        //
        // A purge is the caller NAMING who stays. Nobody named is not a purge.
        if keep.is_empty() {
            crate::community::v2::service::refound_community(&transport, &community, &removed)
                .await
                .map_err(VectorError::Other)?;
        } else {
            crate::community::v2::service::refound_community_retaining(&transport, &community, &removed, &keep)
                .await
                .map_err(VectorError::Other)?;
        }
        // Re-load onto the epoch the rotation just minted: kicking against the stale
        // struct would address the plane we just buried, which is the whole bug this
        // ordering exists to avoid.
        let fresh = Self::load_held(community_id)?
            .ok_or_else(|| VectorError::Other("community gone during the purge".into()))?;
        let sweep = crate::community::v2::service::kick_members(&transport, &fresh, &removed, on_progress)
            .await
            .map_err(VectorError::Other)?;
        // Fold our own directives back. Without this the local roster only shows what
        // the live subscription happened to echo before the sweep finished.
        let _ = crate::community::v2::service::sync_guestbook(&transport, &fresh).await;
        log_info!(
            "[Moderation] purge: rotated to epoch {}, kicked {}/{} ({} refused, {} failed)",
            fresh.root_epoch.0,
            sweep.kicked.len(),
            removed.len(),
            sweep.refused.len(),
            sweep.failed.len()
        );
        Ok(serde_json::json!({
            "kicked": sweep.kicked.len(),
            "refused": sweep.refused.len(),
            "failed": sweep.failed.len(),
            "rotated": true,
        }))
    }

    /// Kick many members without rotating. Exposed for callers that want the roster
    /// cleaned but the keys left alone.
    pub async fn kick_community_members(
        &self,
        community_id: &str,
        npubs: &[&str],
        on_progress: &(dyn Fn(usize, usize) + Sync),
    ) -> Result<serde_json::Value> {
        let community = Self::load_held(community_id)?
            .ok_or_else(|| VectorError::Other("kicking requires a Concord v2 community".into()))?;
        use nostr_sdk::prelude::PublicKey;
        let targets: Vec<PublicKey> = npubs.iter().filter_map(|n| PublicKey::parse(n).ok()).collect();
        let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(30));
        let sweep = crate::community::v2::service::kick_members(&transport, &community, &targets, on_progress)
            .await
            .map_err(VectorError::Other)?;
        let _ = crate::community::v2::service::sync_guestbook(&transport, &community).await;
        log_info!(
            "[Moderation] kick sweep: {}/{} kicked ({} refused, {} failed)",
            sweep.kicked.len(),
            targets.len(),
            sweep.refused.len(),
            sweep.failed.len()
        );
        Self::invalidate_raid_report(community_id);
        Ok(serde_json::json!({
            "kicked": sweep.kicked.len(),
            "refused": sweep.refused.iter().map(|(_, why)| why.clone()).collect::<Vec<_>>(),
            "failed": sweep.failed.len(),
        }))
    }

    /// Retire every public invite link this Community holds. A raid arrives through a
    /// link, and revoking them one at a time loses the race — the whole set has to go
    /// in one pass before the rotation, or the next wave walks in through the survivor.
    /// Returns `(revoked, failed)`.
    pub async fn revoke_all_public_invites(&self, community_id: &str) -> Result<(usize, usize)> {
        let tokens: Vec<String> = crate::db::community::list_public_invites(community_id)
            .map_err(VectorError::Other)?
            .into_iter()
            .map(|i| i.token)
            .collect();
        let mut revoked = 0usize;
        let mut failed = 0usize;
        for token in &tokens {
            match self.revoke_public_invite(community_id, token).await {
                Ok(()) => revoked += 1,
                Err(_) => failed += 1,
            }
        }
        Ok((revoked, failed))
    }

    /// One synchronous v2 follow pass — rekeys first (a base adopt moves the
    /// control address), then a control refold on the FRESH state, the same order
    /// the live follow worker runs. Returns non-fatal warnings.
    /// Walk one community's rekeys + control fold NOW, serialized against the live
    /// follow worker by the per-community lock. Public so boot can converge a community
    /// the probe saw move BEFORE paging its content — content read at a superseded
    /// epoch is wasted work, and may not open at all.
    pub async fn v2_inline_follow(id: &crate::community::CommunityId) -> Vec<String> {
        crate::db::scoped(async move {
            use crate::community::transport::LiveTransport;
            let session = crate::db::current_session();
            // Serialize with the live follow worker: `follow_worker_running` is
            // check-then-act, so a worker can spawn right after a caller saw `false` —
            // this shared per-community lock is what actually prevents two follows of
            // one community interleaving their whole-row saves.
            let lock = crate::community::v2::realtime::follow_lock(id);
            let _guard = lock.lock().await;
            let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
            let mut warnings: Vec<String> = Vec::new();
            let Ok(Some(community)) = crate::db::community::load_community_v2(id) else {
                warnings.push("v2 community not found".to_string());
                return warnings;
            };
            let cid_hex = crate::simd::hex::bytes_to_hex_32(&id.0);
            match crate::community::v2::service::follow_rekeys(&transport, &community, &session).await {
                // A tombstone surfaced during catch-up — sealed read-only; stop here.
                Ok(f) if f.dissolved => return warnings,
                Ok(f) if f.self_removed => {
                    // An authorized rotation that excluded us IS a removal — but keep the
                    // epoch keys, exactly as every other self-removal path does. They grant
                    // no future read (post-removal keys are never delivered); dropping them
                    // only destroys the ability to author a 3305 self-delete of our OWN past
                    // messages, each sealed under the epoch it was sent at. That is the one
                    // thing a removed member should still be able to do — and doubly so if
                    // the removal turns out to have been a false positive.
                    let _ = crate::db::community::delete_community_retain_keys(&cid_hex);
                    return warnings;
                }
                Ok(_) => {}
                Err(e) => warnings.push(format!("v2 rekey follow failed: {e}")),
            }
            if let Ok(Some(fresh)) = crate::db::community::load_community_v2(id) {
                match crate::community::v2::service::follow_control(&transport, &fresh).await {
                    // Walk the rekeys once more whenever the control fold moved ANYTHING.
                    // The document half reveals rekey work that predates it (a just-announced
                    // private channel's key crate already sits on its rekey plane). The
                    // AUTHORITY half is the one that strands: the walk above gates every
                    // rotation on the roster and citation heads this fold just wrote, so a
                    // promote-then-rotate is refused on pass 1 and, without this, never
                    // reconsidered. Re-read from the DB — the authority half moves columns
                    // the returned document does not carry.
                    Ok(control) if control.moved() => {
                        if let Ok(Some(latest)) = crate::db::community::load_community_v2(id) {
                            if let Err(e) = crate::community::v2::service::follow_rekeys(&transport, &latest, &session).await {
                                warnings.push(format!("v2 rekey follow failed: {e}"));
                            }
                        }
                    }
                    Ok(_) => {}
                    Err(e) => warnings.push(format!("v2 control follow failed: {e}")),
                }
            }
            // Banned by the freshly-folded banlist: a removal just like the rotation
            // exclusion above, and it arrives FIRST (CORD-04 §6 orders the Banlist edition
            // before the Refounding), so keying removal solely off the rotation leaves a
            // banned headless client running against a community that already dropped it.
            if let Some(me) = crate::my_public_key() {
                if crate::db::community::is_author_banned(&cid_hex, &me) {
                    let _ = crate::db::community::delete_community_retain_keys(&cid_hex);
                    return warnings;
                }
            }
            // As the live follow does: what a fold here undid is taken back, and what waited is judged again.
            let quiet = crate::event_handler::NoOpEventHandler;
            if let Ok(Some(folded)) = crate::db::community::load_community_v2(id) {
                crate::community::v2::service::owe_new_departures(&folded);
            }
            crate::community::v2::realtime::settle_owed_retractions(id, &transport, &quiet).await;
            if let Ok(Some(folded)) = crate::db::community::load_community_v2(id) {
                crate::community::v2::service::rejudge_held(&folded, &quiet).await;
            }
            warnings
        })
        .await
    }

    /// Fetch a channel's recent chat history and PERSIST it into the shared events
    /// tables, so `get_messages`/`get_new_messages` backfill. PAGES backwards until it reaches messages it already holds
    /// (bounded), so a reconnecting bot that slept through more than one page of traffic
    /// still catches the whole gap instead of only the newest `limit`. Reuses the v2
    /// inbound bridge (dedup + STATE aggregate) + the shared save path. Returns the count of
    /// brand-new messages applied. Best-effort: a fetch failure is 0.
    /// Reconnect/boot catch-up for one v2 channel: fetches the newest pages
    /// and PAGES backwards until it reaches messages it already holds, then
    /// ingests through the shared pipeline. The boot volley fetches its own
    /// batches and shares only [`Self::v2_ingest_chat_page`].
    #[allow(clippy::too_many_arguments)]
    pub(crate) async fn v2_backfill_channel(
        id: &crate::community::CommunityId,
        channel_id: &str,
        limit: usize,
        max_pages: usize,
        since: Option<u64>,
        until: Option<u64>,
        evidence: crate::community::transport::Evidence,
        transport_secs: u64,
    ) -> usize {
        // A caller that takes only a count can't page on from where the relay walk stopped: go on
        // from there a few times, or what a quieter address held below it would wait for a scroll.
        let (mut new, mut until) = (0, until);
        let mut waiting = Vec::new();
        for _ in 0..BACKFILL_CONTINUATIONS {
            let (count, still) = Self::v2_backfill_window(id, channel_id, limit, max_pages, since, until, evidence, transport_secs).await;
            new += count.new_messages;
            waiting.extend(still);
            match count.next_before {
                Some(next) if until.is_none_or(|u| next < u) => until = Some(next),
                _ => break,
            }
        }
        // Newest first, so a reaction, edit or delete can arrive a window before its target: once
        // every window has landed, it lands too.
        if !waiting.is_empty() {
            if let Some(me) = state::my_public_key() {
                Self::v2_ingest_chat_page_waiting(channel_id, me, crate::db::current_session(), waiting).await;
            }
        }
        new
    }

    /// [`v2_backfill_channel`](Self::v2_backfill_channel) reporting what the RELAY
    /// served as well as what was new. A back-page over history we already hold is
    /// new-count 0 with a non-empty fetch, so only `fetched` can answer "is there
    /// anything older" — new-count alone stops a scroll at the first known page.
    #[allow(clippy::too_many_arguments)]
    pub(crate) async fn v2_backfill_channel_counted(
        id: &crate::community::CommunityId,
        channel_id: &str,
        limit: usize,
        max_pages: usize,
        since: Option<u64>,
        until: Option<u64>,
        evidence: crate::community::transport::Evidence,
        transport_secs: u64,
    ) -> BackfillCount {
        Self::v2_backfill_window(id, channel_id, limit, max_pages, since, until, evidence, transport_secs).await.0
    }

    /// [`v2_backfill_channel_counted`](Self::v2_backfill_channel_counted), with the reactions,
    /// edits and deletes whose target the window didn't hold.
    #[allow(clippy::too_many_arguments)]
    async fn v2_backfill_window(
        id: &crate::community::CommunityId,
        channel_id: &str,
        limit: usize,
        max_pages: usize,
        since: Option<u64>,
        until: Option<u64>,
        evidence: crate::community::transport::Evidence,
        transport_secs: u64,
    ) -> (BackfillCount, Vec<crate::community::v2::service::FetchedEvent>) {
        // Guard straddles the fetch: a swap mid-fetch must not persist account A's chat
        // into account B's STATE/DB (the message ids are global).
        let session = crate::db::current_session();
        let Some(my_pk) = state::my_public_key() else { return (BackfillCount::default(), Vec::new()) };
        // CORD-02 §9: a dissolved community honors no NEW events — old history reads
        // through the explicit paths, but a catch-up sweep must not ingest anything
        // authored into the grave.
        if crate::db::community::get_community_dissolved(&crate::simd::hex::bytes_to_hex_32(&id.0)).unwrap_or(false) {
            return (BackfillCount::default(), Vec::new());
        }
        let Ok(Some(community)) = crate::db::community::load_community_v2(id) else { return (BackfillCount::default(), Vec::new()) };
        let ch = crate::community::ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
        let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(transport_secs));
        let held = std::sync::atomic::AtomicUsize::new(0);
        let began = crate::clock::now_secs();
        let floor = crate::history_gaps::floor(channel_id, until, began);
        let reach = crate::history_gaps::reach(since, floor);
        let live = community.channel(&ch).map_or(community.root_epoch, |c| community.channel_secret(c).1);
        // Epochs adopted since the proof are read whole. Unproven, the last few from the floor:
        // a week rarely holds more rotations.
        let past = until.is_none().then(|| match crate::history_gaps::proven_epoch(channel_id) {
            Some(e) => (crate::community::Epoch(e), since),
            None => (crate::community::Epoch(live.0.saturating_sub(UNPROVEN_EPOCHS)), reach),
        });
        // Published planes, and past epochs delivered read-only, that nothing here read: what they
        // hold predates everything this device has, so they are read whole.
        let unread: Vec<nostr_sdk::prelude::PublicKey> = match community.channel(&ch).filter(|_| until.is_none()) {
            Some(c) => {
                let read = crate::history_gaps::history_read(channel_id);
                let cid_hex = crate::simd::hex::bytes_to_hex_32(&id.0);
                let views = crate::db::community::history_views(&cid_hex, channel_id).unwrap_or_default().into_iter().filter_map(|(_, v)| nostr_sdk::prelude::PublicKey::from_slice(&v.address).ok());
                c.published_history().into_iter().map(|(_, g)| g.pk()).chain(views).filter(|pk| !read.contains(&pk.to_hex())).collect()
            }
            None => Vec::new(),
        };
        let Ok((page, next_before, complete)) = crate::community::v2::service::fetch_channel_history_since_epoch(
            &transport,
            &community,
            &ch,
            limit.max(50),
            max_pages,
            reach,
            until,
            evidence,
            // A settled wrap is a held row, which decides the page like a held message.
            |page, settled, next| {
                crate::community::v2::service::catch_up_pages_on(page, settled, next, floor, |id| crate::db::events::event_exists(id).unwrap_or(false))
            },
            // Only a catch-up skips what it holds: a back-page feeds the reader what it scrolled to.
            |wraps| {
                if until.is_some() {
                    return Default::default();
                }
                let hex: Vec<String> = wraps.iter().map(|w| w.to_hex()).collect();
                let settled = crate::db::events::community_wraps_settled(&hex);
                let skip: std::collections::HashSet<_> = wraps.iter().zip(&hex).filter(|(_, h)| settled.contains(*h)).map(|(w, _)| *w).collect();
                held.fetch_add(skip.len(), std::sync::atomic::Ordering::Relaxed);
                skip
            },
            past,
            &unread,
        )
        .await
        else {
            return (BackfillCount { unreachable: true, ..Default::default() }, Vec::new());
        };
        let fetched = page.len() + held.into_inner();
        let (new_messages, waiting) = Self::v2_ingest_chat_page_keeping(channel_id, my_pk, session, page).await;
        // A walk that stops while still finding new messages leaves a hole above what it held.
        crate::history_gaps::note_walk(channel_id, until, next_before, floor, |t| crate::db::events::newest_message_before(channel_id, t));
        // From the top, everything down to the floor is now read or in the ledger: proven once every
        // relay answered, so one that didn't is read from the old floor next time.
        if until.is_none() && since.is_none() && complete {
            crate::history_gaps::prove(channel_id, began, live.0);
        }
        // Read to their end or to where an older page goes on from: either way, read.
        if complete && !unread.is_empty() {
            crate::history_gaps::mark_history_read(channel_id, unread.iter().map(|pk| pk.to_hex()));
        }
        (BackfillCount { fetched, new_messages, next_before, unreachable: false }, waiting)
    }

    /// Ingest a fetched chat page: STATE apply, batched persist with delete
    /// barriers, then UI surfacing — shared by the reconnect backfill and the
    /// boot volley's batched paint path.
    pub(crate) async fn v2_ingest_chat_page(
        channel_id: &str,
        my_pk: nostr_sdk::prelude::PublicKey,
        session: std::sync::Arc<crate::db::Session>,
        page: Vec<crate::community::v2::service::FetchedEvent>,
    ) -> usize {
        Self::v2_ingest_chat_page_keeping(channel_id, my_pk, session, page).await.0
    }

    /// Ingest reactions, edits and deletes kept back by [`v2_ingest_chat_page_keeping`] once more.
    async fn v2_ingest_chat_page_waiting(
        channel_id: &str,
        my_pk: nostr_sdk::prelude::PublicKey,
        session: std::sync::Arc<crate::db::Session>,
        page: Vec<crate::community::v2::service::FetchedEvent>,
    ) {
        Self::v2_ingest_chat_page_keeping(channel_id, my_pk, session, page).await;
    }

    /// [`v2_ingest_chat_page`](Self::v2_ingest_chat_page), returning as well the reactions, edits
    /// and deletes that wait on a target nothing holds yet.
    async fn v2_ingest_chat_page_keeping(
        channel_id: &str,
        my_pk: nostr_sdk::prelude::PublicKey,
        session: std::sync::Arc<crate::db::Session>,
        page: Vec<crate::community::v2::service::FetchedEvent>,
    ) -> (usize, Vec<crate::community::v2::service::FetchedEvent>) {
        crate::db::scoped(async move {
            use crate::community::v2::inbound::ChatPersist;
            let judged_on = crate::community::v2::service::writers_head(channel_id);
            let page = crate::community::v2::service::rejudge_page(channel_id, page);
            let since = page.iter().map(|f| f.event.opened().at_ms).min();
            let posted: Vec<(nostr_sdk::prelude::PublicKey, u64)> = page.iter().filter(|f| matches!(f.event, crate::community::v2::chat::ChatEvent::Message { .. } | crate::community::v2::chat::ChatEvent::Edit { .. })).map(|f| (f.event.opened().author, f.event.opened().at_ms)).collect();
            let mut new = 0usize;
            let mut unapplied: Vec<usize> = Vec::new();
            // Pass 1 — apply to STATE (per-item lock) and COLLECT outcomes in wire order.
            let mut outcomes: Vec<ChatPersist> = Vec::with_capacity(page.len());
            // The page index each outcome came from.
            let mut sources: Vec<usize> = Vec::with_capacity(page.len());
            let stored = crate::db::events::existing_event_ids(&crate::community::v2::inbound::page_event_ids(page.iter().map(|f| &f.event))).unwrap_or_default();
            for (i, f) in page.iter().enumerate() {
                // A backfilled WebXDC peer ad persists through the shared 30078 row
                // (recency-gated at read) so a reopening lobby lists peers who
                // advertised while this device was closed. Own
                // echoes drop; the ad is not a chat row.
                if let crate::community::v2::chat::ChatEvent::Webxdc { opened } = &f.event {
                    if opened.author != my_pk {
                        if let Some((topic, addr)) = crate::webxdc::parse_peer_signal(&opened.rumor.content) {
                            let Ok(npub) = ToBech32::to_bech32(&opened.author);
                            crate::community::v2::inbound::persist_webxdc_signal(
                                channel_id,
                                &npub,
                                &topic,
                                addr.as_deref(),
                                &opened.rumor_id.to_hex(),
                                opened.at_ms / 1000,
                            )
                            .await;
                        }
                    }
                    continue;
                }
                crate::community::v2::inbound::hydrate_target(&f.event, channel_id).await;
                let outcome = {
                    let mut st = state::STATE.lock().await;
                    crate::community::v2::inbound::apply_page_event_to_state(&mut st, &f.event, channel_id, &my_pk, &stored)
                };
                match outcome {
                    Some(outcome) => {
                        if matches!(outcome, ChatPersist::New(_)) {
                            new += 1;
                        }
                        outcomes.push(outcome);
                        sources.push(i);
                    }
                    None if matches!(f.event, crate::community::v2::chat::ChatEvent::Reaction { .. } | crate::community::v2::chat::ChatEvent::Edit { .. } | crate::community::v2::chat::ChatEvent::Delete { .. }) => unapplied.push(i),
                    None => {}
                }
            }
            // Pass 2 — persist: message saves COLLECT into batched transactions; deletes are
            // flush barriers (a save committing after a delete it preceded on the wire would
            // resurrect the deleted row). One tx per page in the common no-delete case.
            // Bytes we already hold verify at arrival (indexed probe first, hash
            // only on a plausible candidate), mirroring the DM ingest — the batch
            // below borrows, so claims convert here while outcomes are still owned.
            for o in &mut outcomes {
                if let ChatPersist::New(m) | ChatPersist::Updated { message: m, .. } = o {
                    crate::db::attachments::verify_message_attachments(m, Some(channel_id)).await;
                }
            }
            crate::community::v2::inbound::persist_chat_page(channel_id, &outcomes, &session).await;
            if let Some(since) = since {
                crate::community::v2::service::owe_if_moved(channel_id, judged_on, since);
            }
            crate::community::v2::service::owe_if_departed(channel_id, &posted);
            // Resolve each reply's quote before the emit: the renderer has no other source
            // for a parent outside its window and never retries. Placed AFTER the persists
            // so a parent carried by this same page resolves too. One query per page.
            {
                let quoted: Vec<&mut crate::types::Message> = outcomes
                    .iter_mut()
                    .filter_map(|o| match o {
                        ChatPersist::New(m)
                        | ChatPersist::Updated { message: m, .. }
                        | ChatPersist::ReactionRemoved { message: m, .. } => Some(m),
                        ChatPersist::Removed { .. } => None,
                    })
                    .collect();
                let _ = crate::db::events::populate_reply_contexts(quoted).await;
            }
            // Pass 3 — surface to the live UI, mirroring the live dispatch handler:
            // a silent DB-only backfill left the chat-list preview, unread badge, and sort order
            // stale until the channel was opened. Raw emits (no notification ping) — a boot
            // catch-up must not fire an OS ping per message. Headless consumers register no
            // emitter, so these are a no-op there. After the persists so nothing surfaces unsaved.
            for outcome in &outcomes {
                match outcome {
                    ChatPersist::New(msg) => crate::traits::emit_message_new(channel_id, msg),
                    ChatPersist::Updated { message, .. }
                    | ChatPersist::ReactionRemoved { message, .. } => {
                        let mut message = message.clone();
                        let target_id = message.id.clone();
                        crate::traits::emit_message_update(channel_id, &target_id, &mut message).await;
                    }
                    ChatPersist::Removed { id: target_id, .. } => crate::traits::emit_event(
                        "message_removed",
                        &serde_json::json!({ "id": target_id, "chat_id": channel_id, "reason": "deleted" }),
                    ),
                }
            }
            // A listener hears what it hadn't yet: a page can be the only path a message sent
            // while this device was away, or still subscribing, ever takes.
            if let Some(listener) = crate::news::listener() {
                for (outcome, i) in outcomes.into_iter().zip(sources) {
                    let event = &page[i].event;
                    let at = match &outcome {
                        ChatPersist::New(m) => m.at,
                        _ => event.opened().at_ms,
                    };
                    if crate::news::is_news(at) {
                        crate::community::v2::inbound::notify_chat_outcome(&*listener, channel_id, event, outcome, true).await;
                    }
                }
            }
            let mut waiting = Vec::new();
            for i in unapplied {
                let f = &page[i];
                if crate::community::v2::inbound::awaits_target(&f.event).await {
                    waiting.push(crate::community::v2::service::FetchedEvent { event: f.event.clone(), epoch: f.epoch, wrap: f.wrap.clone() });
                }
            }
            (new, waiting)
        })
        .await
    }

    /// The held community `community_id` names, or `Ok(None)`. A DB read error
    /// PROPAGATES (fail-closed) rather than reading as "unknown".
    /// A community id read from the caller, for one this device no longer holds.
    fn unheld_id(community_id: &str) -> Result<crate::community::CommunityId> {
        crate::simd::hex::hex_to_bytes_32_checked(community_id)
            .map(crate::community::CommunityId)
            .ok_or_else(|| VectorError::Other("malformed community id".into()))
    }

    fn load_held(community_id: &str) -> Result<Option<crate::community::v2::community::CommunityV2>> {
        if community_id.len() != 64 {
            return Ok(None);
        }
        let cid = crate::community::CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
        crate::db::community::load_community_v2(&cid).map_err(VectorError::Other)
    }

    // ── Community admin actions ── role-gated; vector-core re-checks authority on every action and peers
    // re-verify against the owner-rooted roster, so these can't forge standing. A bunker account can't ban
    // in a private community (the rekey needs a raw local key).

    /// My effective management capabilities in a community (role engine — owner is just position 0). Use to
    /// confirm a promotion/demotion landed. A local read: the roster is folded + persisted by the control
    /// follow, never fetched here.
    pub fn community_capabilities(&self, community_id: &str) -> Result<serde_json::Value> {
        let v2 = Self::load_held(community_id)?.ok_or_else(|| VectorError::Other("community not found".into()))?;
        use crate::community::roles::Permissions;
        let me = state::my_public_key().ok_or_else(|| VectorError::Other("Not logged in".into()))?.to_hex();
        let owner_hex = v2.owner().map_err(VectorError::Other)?.to_hex();
        let roster = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
        // A banned member holds no standing (CORD-04 §4), even if a since-skipped
        // roster persist still lists their grant — the banlist advances on its own gate.
        let banned = crate::db::community::get_community_banlist(community_id).unwrap_or_default();
        if banned.contains(&me) && me != owner_hex {
            return Ok(serde_json::json!({
                "manage_metadata": false, "manage_channels": false, "create_invite": false, "kick": false,
                "ban": false, "manage_messages": false, "manage_roles": false, "manage_admin_role": false,
                "pin_messages": false, "control_write": false, "moderate_members": false, "view_audit_log": false,
                "manage_nicknames": false, "change_nickname": false,
            }));
        }
        // Actions that land as Control editions additionally need the plane's
        // write key (CORD-02 §2): a role-authorized staffer whose control_wrap
        // hasn't arrived yet factually cannot publish, and an honest false here
        // beats a bot retry-looping a publish every reader drops. KICK
        // (Guestbook) and MANAGE_MESSAGES (Chat planes) never need it.
        let control_write = crate::community::v2::control::ControlPlane::of(&v2).can_write();
        let has = |p: u64| roster.is_authorized(&me, Some(&owner_hex), p);
        let has_ctl = |p: u64| control_write && has(p);
        Ok(serde_json::json!({
            "manage_metadata": has_ctl(Permissions::MANAGE_METADATA), "manage_channels": has_ctl(Permissions::MANAGE_CHANNELS),
            "create_invite": has_ctl(Permissions::CREATE_INVITE), "kick": has(Permissions::KICK), "ban": has_ctl(Permissions::BAN),
            "manage_messages": has(Permissions::MANAGE_MESSAGES), "manage_roles": has_ctl(Permissions::MANAGE_ROLES),
            // Only the owner (position 0) strictly outranks the position-1 Admin role.
            "manage_admin_role": me == owner_hex && control_write,
            "pin_messages": has_ctl(Permissions::PIN_MESSAGES),
            "control_write": control_write,
            // A Timeout rides the Guestbook, so it needs no Control write key.
            "moderate_members": has(Permissions::MODERATE_MEMBERS),
            "view_audit_log": has(Permissions::VIEW_AUDIT_LOG),
            // Nicknames ride the Guestbook too.
            "manage_nicknames": has(Permissions::MANAGE_NICKNAMES),
            "change_nickname": roster.may_name(&me, Some(&owner_hex), &me),
        }))
    }

    /// Check each relay `relays` would add to a v2 community before moving it there: whether it
    /// holds what a community needs, and whether it throttles.
    pub async fn check_community_relays(&self, community_id: &str, relays: &[String]) -> Result<Vec<crate::community::v2::service::RelayCheck>> {
        let v2 = Self::load_held(community_id)?.ok_or_else(|| VectorError::Other("community not found".into()))?;
        let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(15));
        crate::community::v2::service::check_relays(&transport, &v2, relays).await.map_err(VectorError::Other)
    }

    /// Move a v2 community to `relays`, copying what its members need onto each new relay first
    /// (see [`crate::community::v2::service::move_relays`]).
    pub async fn move_community_relays(&self, community_id: &str, relays: &[String]) -> Result<crate::community::v2::service::RelayMove> {
        let v2 = Self::load_held(community_id)?.ok_or_else(|| VectorError::Other("community not found".into()))?;
        let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(15));
        crate::community::v2::service::move_relays(&transport, &v2, relays).await.map_err(VectorError::Other)
    }

    /// A v2 community's Audit Log, newest first: who changed what, and when. Any member can read
    /// the chain it comes from; showing it is for the owner and View Audit Log holders.
    pub async fn community_audit_log(&self, community_id: &str) -> Result<crate::community::v2::service::AuditLog> {
        let v2 = Self::load_held(community_id)?.ok_or_else(|| VectorError::Other("community not found".into()))?;
        let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(15));
        crate::community::v2::service::audit_log(&transport, &v2).await.map_err(VectorError::Other)
    }

    /// Pin a message in a v2 community channel (CORD-04 §7). The proof is
    /// rebuilt from the message's recovered wrap; see `service::pin_message`.
    pub async fn pin_community_message(&self, community_id: &str, channel_id: &str, message_id: &str) -> Result<()> {
        use crate::community::{transport::LiveTransport, ChannelId};
        let v2 = Self::load_held(community_id)?
            .ok_or_else(|| VectorError::Other("pins are only available in Concord v2 communities".into()))?;
        let ch = ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
        crate::community::v2::service::pin_message(&transport, &v2, &ch, message_id)
            .await
            .map_err(VectorError::Other)
    }

    /// Unpin a message: the next Pin List edition without the entry.
    pub async fn unpin_community_message(&self, community_id: &str, channel_id: &str, message_id: &str) -> Result<()> {
        use crate::community::{transport::LiveTransport, ChannelId};
        let v2 = Self::load_held(community_id)?
            .ok_or_else(|| VectorError::Other("pins are only available in Concord v2 communities".into()))?;
        let ch = ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
        crate::community::v2::service::unpin_message(&transport, &v2, &ch, message_id)
            .await
            .map_err(VectorError::Other)
    }

    /// Fetch a pinned attachment FROM THE PIN ALONE (CORD-04 §7's whole point:
    /// the proof carries the rumor, whose imeta carries the blob URL and the
    /// file's decryption material — no chat history and no old epoch key
    /// needed). Serves the already-downloaded copy when its content hash
    /// verifies; otherwise runs the full download walk (mirrors + hash-swap),
    /// decrypts, verifies, and caches at the same content-addressed path the
    /// chat pipeline uses. Returns `{ path, mime, name }`.
    pub async fn fetch_pinned_attachment(
        &self,
        community_id: &str,
        channel_id: &str,
        rumor_id: &str,
    ) -> Result<serde_json::Value> {
        crate::db::scoped(async move {
            use crate::community::ChannelId;
            let v2 = Self::load_held(community_id)?
                .ok_or_else(|| VectorError::Other("pins are only available in Concord v2 communities".into()))?;
            let ch = ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
            let pins = crate::community::v2::service::read_channel_pins(&v2, &ch).map_err(VectorError::Other)?;
            let pin = pins
                .pins
                .iter()
                .find(|p| p.rumor_id == rumor_id)
                .ok_or_else(|| VectorError::Other("that message is not pinned".into()))?;
            let dir = crate::db::get_download_dir();
            let tag = pin
                .tags
                .iter()
                .find(|t| t.first().map(String::as_str) == Some("imeta"))
                .map(|t| nostr_sdk::prelude::Tag::custom("imeta", t[1..].to_vec()))
                .ok_or_else(|| VectorError::Other("this pin carries no attachment".into()))?;
            let attachment = crate::community::attachments::attachment_from_imeta(&tag, &dir)
                .ok_or_else(|| VectorError::Other("this pin's attachment metadata is malformed".into()))?;

            let respond = |path: &str| {
                serde_json::json!({
                    "path": path,
                    "name": attachment.name.to_string(),
                    "extension": attachment.extension.to_string(),
                })
            };

            // The author-committed content address (the pin verified the rumor, so
            // `ox` carries the author's signature-weight claim — the same trust the
            // chat pipeline extends). Reuse and fresh downloads both verify it.
            let expected = attachment.original_hash.as_deref();
            // A pin is held in memory like a chat's file; kept too when the account keeps files,
            // or when it is too large to hold.
            let in_memory = crate::media::ram::cache().admits(attachment.size);
            let keep = !in_memory || crate::media::keep_media();
            if let Some(hash) = expected.and_then(crate::simd::hex::hex_to_bytes_32_checked).filter(|h| crate::media::resident(h)) {
                return Ok(respond(&crate::media::MediaRef::held(&hash)));
            }
            let path = std::path::PathBuf::from(&*attachment.path);
            if let Ok(bytes) = std::fs::read(&path) {
                match expected {
                    Some(want) if crate::crypto::sha256_hex(&bytes) == want => return Ok(respond(&path.to_string_lossy())),
                    None => return Ok(respond(&path.to_string_lossy())),
                    _ => {} // stale or foreign bytes at the path: re-download
                }
            }

            let author_npub = nostr_sdk::prelude::PublicKey::from_hex(&pin.author)
                .ok()
                .and_then(|pk| nostr_sdk::prelude::ToBech32::to_bech32(&pk).ok());
            let bytes = self.download_attachment_from(&attachment, author_npub.as_deref()).await?;
            let hash = crate::crypto::sha256_hex(&bytes);
            if expected.is_some_and(|want| hash != want) {
                return Err(VectorError::Other("downloaded bytes do not match the pinned content hash".into()));
            }
            let held = crate::simd::hex::hex_to_bytes_32(&hash);
            let mime = crate::crypto::mime_from_extension(&attachment.extension.to_ascii_lowercase());
            // Kept the way a chat keeps it: sealed in the store, never plain.
            if keep {
                #[cfg(not(target_arch = "wasm32"))]
                crate::media::store::keep_sealed(&bytes, held, mime, crate::db::media_store::Origin::Sealed)
                    .map_err(|e| VectorError::Other(format!("could not keep the attachment: {e}")))?;
                #[cfg(target_arch = "wasm32")]
                crate::media::store::keep_sealed(&bytes, held, mime, crate::db::media_store::Origin::Sealed)
                    .await
                    .map_err(|e| VectorError::Other(format!("could not keep the attachment: {e}")))?;
            }
            if in_memory {
                match crate::media::ram::insert(held, bytes, mime) {
                    Ok(_) => {}
                    Err(_) if keep => {}
                    Err(_) => return Err(VectorError::Other("too much media is open to show this one".into())),
                }
            }
            Ok(respond(&crate::media::MediaRef::held(&held)))
        })
        .await
    }

    /// A channel's verified pins from the locally folded head — local-only read.
    /// `sealed: true` means the list exists but is unreadable on this device;
    /// render it as unavailable, never as empty.
    pub fn get_channel_pins(&self, community_id: &str, channel_id: &str) -> Result<serde_json::Value> {
        use crate::community::ChannelId;
        let Some(v2) = Self::load_held(community_id)? else {
            return Ok(serde_json::json!({ "pins": [], "sealed": false, "version": 0 }));
        };
        let ch = ChannelId(crate::simd::hex::hex_to_bytes_32(channel_id));
        let pins = crate::community::v2::service::read_channel_pins(&v2, &ch).map_err(VectorError::Other)?;
        serde_json::to_value(&pins).map_err(|e| VectorError::Other(e.to_string()))
    }

    /// The whole role graph: every role with its position and colour, and who
    /// holds what.
    ///
    /// `community_roles` above answers only "who is an admin", which is all the
    /// crown ever needed. A member list that groups people by rank needs the
    /// hierarchy itself, and npubs rather than hex so it can match a roster it
    /// already holds.
    pub fn community_role_graph(&self, community_id: &str) -> Result<serde_json::Value> {
        use nostr_sdk::prelude::{PublicKey, ToBech32};
        let roster = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
        // A banned member is gone from every read (§4), roles included.
        let banned = crate::db::community::get_community_banlist(community_id).unwrap_or_default();
        let roles: Vec<serde_json::Value> = roster
            .roles
            .iter()
            .map(|r| {
                // A channel-scoped role is that channel's access list (CORD-04 §2), which
                // is what a Private Channel's member list is drawn from.
                let channel_id = match &r.scope {
                    crate::community::roles::RoleScope::Channel(c) => Some(c.to_ascii_lowercase()),
                    crate::community::roles::RoleScope::Server => None,
                };
                serde_json::json!({
                    "role_id": r.role_id,
                    "name": r.name,
                    "position": r.position,
                    "color": r.color,
                    "channel_id": channel_id,
                    "display": r.display,
                })
            })
            .collect();
        let grants: Vec<serde_json::Value> = roster
            .grants
            .iter()
            .filter(|g| !banned.contains(&g.member))
            .filter_map(|g| {
                let npub = PublicKey::from_hex(&g.member).ok().and_then(|pk| pk.to_bech32().ok())?;
                Some(serde_json::json!({ "npub": npub, "role_ids": g.role_ids }))
            })
            .collect();
        // On Roles v2 a Private Channel's readers are whoever it resolves View Channel for.
        let activated = roster.everyone.is_some();
        let mut readers = serde_json::Map::new();
        if activated {
            if let Some(v2) = Self::load_held(community_id)? {
                let owner_hex = v2.owner().ok().map(|o| o.to_hex());
                let mut candidates: std::collections::BTreeSet<PublicKey> =
                    crate::community::v2::service::stored_memberlist(&v2).unwrap_or_default().into_iter().collect();
                candidates.extend(roster.grants.iter().filter_map(|g| PublicKey::from_hex(&g.member).ok()));
                for ch in v2.channels.iter().filter(|c| c.private) {
                    let chan = crate::simd::hex::bytes_to_hex_32(&ch.id.0);
                    let npubs: Vec<String> = candidates
                        .iter()
                        .filter(|pk| !banned.contains(&pk.to_hex()) && roster.is_entitled(owner_hex.as_deref(), &pk.to_hex(), &chan, &[], &[]))
                        .filter_map(|pk| pk.to_bech32().ok())
                        .collect();
                    readers.insert(chan, npubs.into());
                }
            }
        }
        Ok(serde_json::json!({ "roles": roles, "grants": grants, "activated": activated, "readers": readers }))
    }

    /// Everything a role editor needs, in one local read: every role in display order
    /// (CORD-04 §3: position, then the lower role_id), who holds each, what the caller
    /// may touch, and the channels a role can be scoped to. Permissions ride as decimal
    /// strings, the wire's own rule, since a JS number corrupts past 2^53.
    pub fn community_roles_view(&self, community_id: &str) -> Result<serde_json::Value> {
        use crate::community::roles::{Permissions, RoleScope};
        let v2 = Self::load_held(community_id)?
            .ok_or_else(|| VectorError::Other("roles need a Concord v2 community".into()))?;
        let me = state::my_public_key().ok_or_else(|| VectorError::Other("Not logged in".into()))?.to_hex();
        let owner_hex = v2.owner().map_err(VectorError::Other)?.to_hex();
        let roster = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
        let banned = crate::db::community::get_community_banlist(community_id).unwrap_or_default();
        let is_owner = me == owner_hex;
        let can_manage = is_owner
            || (!banned.contains(&me) && roster.is_authorized(&me, Some(&owner_hex), Permissions::MANAGE_ROLES));
        let rank = if is_owner { Some(0) } else { roster.highest_position(&me) };
        let grantable = if is_owner { u64::MAX } else { roster.effective_permissions(&me).0 };
        let mut roles: Vec<&crate::community::roles::Role> = roster.roles.iter().collect();
        roles.sort_by(|a, b| a.position.cmp(&b.position).then_with(|| a.role_id.cmp(&b.role_id)));
        let activated = Self::roles_v2_active(community_id, &roster);
        let roles: Vec<serde_json::Value> = roles
            .into_iter()
            .map(|r| {
                let holders: Vec<String> = roster
                    .grants
                    .iter()
                    .filter(|g| !banned.contains(&g.member) && g.role_ids.iter().any(|id| id == &r.role_id))
                    .filter_map(|g| nostr_sdk::prelude::PublicKey::from_hex(&g.member).ok())
                    .filter_map(|pk| nostr_sdk::prelude::ToBech32::to_bech32(&pk).ok())
                    .collect();
                serde_json::json!({
                    "role_id": r.role_id,
                    "name": r.name,
                    "position": r.position,
                    "color": r.color,
                    "permissions": r.permissions.0.to_string(),
                    "channel_id": match &r.scope { RoleScope::Channel(c) => Some(c.to_ascii_lowercase()), RoleScope::Server => None },
                    "holders": holders,
                    "display": r.display,
                    "mentionable": r.mentionable,
                    "manageable": can_manage && (is_owner || {
                        let support = roster.permissions_above(&me, r.position);
                        support.contains(Permissions::MANAGE_ROLES) && r.permissions.0 & !support.0 == 0
                    }),
                })
            })
            .collect();
        let channels: Vec<serde_json::Value> = v2
            .channels
            .iter()
            .map(|c| serde_json::json!({
                "channel_id": crate::simd::hex::bytes_to_hex_32(&c.id.0),
                "name": c.name,
                "private": c.private,
            }))
            .collect();
        Ok(serde_json::json!({
            "is_owner": is_owner,
            "can_manage": can_manage,
            "rank": rank,
            "grantable": grantable.to_string(),
            // Roles v2 (CORD-04 §2): deletable Roles, `@everyone`, and the channel bits.
            "activated": activated,
            "everyone": roster.everyone.map(|p| p.0.to_string()),
            "everyone_editable": activated && (is_owner || roster.permissions_above(&me, u32::MAX).contains(Permissions::MANAGE_ROLES)),
            "everyone_default": crate::community::v2::roles::EVERYONE_DEFAULT.to_string(),
            "roles": roles,
            "channels": channels,
            "max_roles": crate::community::v2::roles::MAX_ROLES_PER_COMMUNITY,
            "max_per_member": crate::community::v2::roles::MAX_ROLES_PER_MEMBER,
        }))
    }

    fn parse_permissions(s: &str) -> Result<u64> {
        if s.is_empty() || !s.bytes().all(|b| b.is_ascii_digit()) {
            return Err(VectorError::Other(format!("permissions must be a decimal string, got {s:?}")));
        }
        s.parse::<u64>().map_err(|_| VectorError::Other("permissions out of range".into()))
    }

    fn role_scope(channel_id: Option<&str>) -> Result<crate::community::roles::RoleScope> {
        use crate::community::roles::RoleScope;
        match channel_id {
            None => Ok(RoleScope::Server),
            Some(c) if c.len() == 64 && c.bytes().all(|b| b.is_ascii_hexdigit()) => Ok(RoleScope::Channel(c.to_ascii_lowercase())),
            Some(_) => Err(VectorError::Other("channel_id must be 32-byte hex".into())),
        }
    }

    /// Create a Role at the bottom of the list. Returns its id.
    pub async fn create_role(&self, community_id: &str, name: &str, color: u32, permissions: &str, channel_id: Option<&str>) -> Result<String> {
        let v2 = Self::load_held(community_id)?
            .ok_or_else(|| VectorError::Other("roles need a Concord v2 community".into()))?;
        let perms = Self::parse_permissions(permissions)?;
        let scope = Self::role_scope(channel_id)?;
        let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
        let roster = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
        let id = if Self::roles_v2_active(community_id, &roster) {
            if channel_id.is_some() {
                return Err(VectorError::Other("on the new roles, channel access is set on the channel".into()));
            }
            crate::community::v2::service::create_role_v2(&transport, &v2, name, color, perms).await
        } else {
            crate::community::v2::service::create_role(&transport, &v2, name, color, perms, scope).await
        }
        .map_err(VectorError::Other)?;
        Self::converge_v2_authority(&transport, community_id).await;
        Ok(id)
    }

    /// Edit a Role's name, colour, permissions and scope.
    pub async fn edit_role(&self, community_id: &str, role_id: &str, name: &str, color: u32, permissions: &str, channel_id: Option<&str>) -> Result<()> {
        self.edit_role_shown(community_id, role_id, name, color, permissions, channel_id, None, None).await
    }

    /// [`Self::edit_role`], plus whether a Roles v2 Role shows apart in the member list and
    /// can be mentioned (`None` keeps what it has).
    #[allow(clippy::too_many_arguments)]
    pub async fn edit_role_shown(
        &self,
        community_id: &str,
        role_id: &str,
        name: &str,
        color: u32,
        permissions: &str,
        channel_id: Option<&str>,
        display: Option<bool>,
        mentionable: Option<bool>,
    ) -> Result<()> {
        let roster = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
        if Self::roles_v2_active(community_id, &roster) {
            let v2 = Self::load_held(community_id)?.ok_or_else(|| VectorError::Other("roles need a Concord v2 community".into()))?;
            let perms = Self::parse_permissions(permissions)?;
            let current = roster.role(role_id).ok_or_else(|| VectorError::Other("no such role".into()))?;
            let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
            crate::community::v2::service::edit_role_v2(
                &transport,
                &v2,
                role_id,
                name,
                color,
                perms,
                display.unwrap_or(current.display),
                mentionable.unwrap_or(current.mentionable),
            )
            .await
            .map_err(VectorError::Other)?;
            Self::converge_v2_authority(&transport, community_id).await;
            return Ok(());
        }
        let v2 = Self::load_held(community_id)?
            .ok_or_else(|| VectorError::Other("roles need a Concord v2 community".into()))?;
        let perms = Self::parse_permissions(permissions)?;
        let scope = Self::role_scope(channel_id)?;
        let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
        crate::community::v2::service::edit_role(&transport, &v2, role_id, name, color, perms, scope)
            .await
            .map_err(VectorError::Other)?;
        Self::converge_v2_authority(&transport, community_id).await;
        Ok(())
    }

    /// Reorder the roles beneath the caller, top to bottom. Returns how many moved.
    pub async fn reorder_roles(&self, community_id: &str, ordered: &[String]) -> Result<usize> {
        let v2 = Self::load_held(community_id)?
            .ok_or_else(|| VectorError::Other("roles need a Concord v2 community".into()))?;
        let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
        let roster = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
        if Self::roles_v2_active(community_id, &roster) {
            let moved = crate::community::v2::service::reorder_roles_v2(&transport, &v2, ordered).await.map_err(VectorError::Other)?;
            if moved > 0 {
                Self::converge_v2_authority(&transport, community_id).await;
            }
            return Ok(moved);
        }
        let moved = crate::community::v2::service::reorder_roles(&transport, &v2, ordered)
            .await
            .map_err(VectorError::Other)?;
        if moved > 0 {
            Self::converge_v2_authority(&transport, community_id).await;
        }
        Ok(moved)
    }

    /// Roles v2 is active here (CORD-04 §2), by what this device has folded.
    fn roles_v2_active(community_id: &str, roster: &crate::community::roles::CommunityRoles) -> bool {
        if roster.everyone.is_some() {
            return true;
        }
        let Some(cid) = crate::simd::hex::hex_to_bytes_32_checked(community_id) else { return false };
        let everyone = crate::simd::hex::bytes_to_hex_32(&crate::community::v2::derive::everyone_locator(&crate::community::CommunityId(cid)));
        crate::db::community::get_edition_head(community_id, &everyone).ok().flatten().is_some()
    }

    fn held_v2(community_id: &str) -> Result<crate::community::v2::community::CommunityV2> {
        Self::load_held(community_id)?.ok_or_else(|| VectorError::Other("this needs a Concord v2 community".into()))
    }

    fn short_transport() -> crate::community::transport::LiveTransport {
        crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12))
    }

    /// A Channel view by name: `chat`, `forum` or `voice`.
    fn view_named(view: &str) -> Result<crate::community::v2::community::ChannelView> {
        crate::community::v2::community::ChannelView::try_parse(view)
            .ok_or_else(|| VectorError::Other(format!("no channel view named {view:?}: chat, forum or voice")))
    }

    fn id32(hex: &str, what: &str) -> Result<[u8; 32]> {
        crate::simd::hex::hex_to_bytes_32_checked(hex).ok_or_else(|| VectorError::Other(format!("{what} must be 32-byte hex")))
    }

    /// A channel's permission overwrites and what an editor needs to change them, read
    /// locally. Bits ride as decimal strings.
    pub fn channel_permissions_view(&self, community_id: &str, channel_id: &str) -> Result<serde_json::Value> {
        use crate::community::roles::{OverwriteTarget, Permissions};
        let v2 = Self::held_v2(community_id)?;
        let me = state::my_public_key().ok_or_else(|| VectorError::Other("Not logged in".into()))?.to_hex();
        let owner_hex = v2.owner().map_err(VectorError::Other)?.to_hex();
        let roster = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
        let is_owner = me == owner_hex;
        let chan = channel_id.to_ascii_lowercase();
        let mut roles: Vec<&crate::community::roles::Role> = roster.roles.iter().collect();
        roles.sort_by(|a, b| a.position.cmp(&b.position).then_with(|| a.role_id.cmp(&b.role_id)));
        let overwrites: Vec<serde_json::Value> = roster
            .overwrites
            .iter()
            .filter(|o| o.scope == chan)
            .map(|o| {
                let (kind, id) = match &o.target {
                    OverwriteTarget::Everyone => ("everyone", None),
                    OverwriteTarget::Role(id) => ("role", Some(id.clone())),
                    OverwriteTarget::Member(m) => ("member", Some(m.clone())),
                };
                let npub = (kind == "member").then(|| id.as_deref().and_then(|m| nostr_sdk::prelude::PublicKey::from_hex(m).ok()).and_then(|pk| ToBech32::to_bech32(&pk).ok())).flatten();
                serde_json::json!({ "kind": kind, "id": id, "npub": npub, "allow": o.allow.0.to_string(), "deny": o.deny.0.to_string() })
            })
            .collect();
        let category = crate::simd::hex::hex_to_bytes_32_checked(&chan)
            .and_then(|b| v2.channel(&crate::community::ChannelId(b)))
            .and_then(|c| c.category())
            .filter(|k| v2.categories.iter().any(|x| x.id == *k))
            .map(|k| crate::simd::hex::bytes_to_hex_32(&k));
        Ok(serde_json::json!({
            "activated": Self::roles_v2_active(community_id, &roster),
            // The Category the channel files under, and whether it takes that Category's rules.
            "category": category,
            "synced": roster.syncs.get(&chan),
            "can_manage": is_owner || roster.is_authorized(&me, Some(&owner_hex), Permissions::MANAGE_ROLES),
            "grantable": if is_owner { u64::MAX.to_string() } else { roster.effective_permissions(&me).0.to_string() },
            "roles": roles.iter().map(|r| serde_json::json!({ "role_id": r.role_id, "name": r.name, "color": r.color, "position": r.position })).collect::<Vec<_>>(),
            "overwrites": overwrites,
            // Who a member overwrite can name: everyone this device knows, but the owner.
            "members": crate::community::v2::service::stored_memberlist(&v2)
                .unwrap_or_default()
                .into_iter()
                .filter(|pk| pk.to_hex() != owner_hex)
                .map(|pk| serde_json::json!({ "id": pk.to_hex(), "npub": ToBech32::to_bech32(&pk).ok() }))
                .collect::<Vec<_>>(),
        }))
    }

    /// Set, or with no bits clear, one overwrite on a Channel or Category. `kind` is
    /// `everyone`, `role` (a role id) or `member` (an npub or hex key).
    pub async fn set_channel_overwrite(&self, community_id: &str, scope_id: &str, kind: &str, target_id: Option<&str>, allow: &str, deny: &str) -> Result<()> {
        use crate::community::roles::OverwriteTarget;
        let v2 = Self::held_v2(community_id)?;
        let target = match (kind, target_id) {
            ("everyone", _) => OverwriteTarget::Everyone,
            ("role", Some(id)) => OverwriteTarget::Role(crate::simd::hex::bytes_to_hex_32(&Self::id32(id, "role_id")?)),
            ("member", Some(m)) => OverwriteTarget::Member(
                nostr_sdk::prelude::PublicKey::parse(m).map_err(|_| VectorError::Other("invalid member key".into()))?.to_hex(),
            ),
            _ => return Err(VectorError::Other("an overwrite targets everyone, a role or a member".into())),
        };
        let (allow, deny) = (Self::parse_permissions(allow)?, Self::parse_permissions(deny)?);
        let transport = Self::short_transport();
        crate::community::v2::service::set_overwrite(&transport, &v2, Self::id32(scope_id, "scope_id")?, target, allow, deny)
            .await
            .map_err(VectorError::Other)?;
        Self::converge_v2_authority(&transport, community_id).await;
        Ok(())
    }

    /// Sync a channel to a Category's permissions, or (`None`) back to its own.
    pub async fn set_channel_sync(&self, community_id: &str, channel_id: &str, category_id: Option<&str>) -> Result<()> {
        let v2 = Self::held_v2(community_id)?;
        let channel = crate::community::ChannelId(Self::id32(channel_id, "channel_id")?);
        let category = category_id.map(|c| Self::id32(c, "category_id")).transpose()?;
        let transport = Self::short_transport();
        crate::community::v2::service::set_channel_sync(&transport, &v2, &channel, category).await.map_err(VectorError::Other)?;
        Self::converge_v2_authority(&transport, community_id).await;
        Ok(())
    }

    /// Of `npubs`, those who can't send in a channel by the roster as it stands (CORD-04 §8):
    /// a reader collapses their posts there. Empty on the legacy roster.
    pub fn channel_send_denied(&self, community_id: &str, channel_id: &str, npubs: &[String]) -> Result<Vec<String>> {
        Self::channel_denied(community_id, channel_id, npubs, crate::community::roles::Permissions::SEND_MESSAGES)
    }

    /// Of `npubs`, those who can't react in a channel by the roster as it stands: a reader
    /// doesn't count their reactions there. Empty on the legacy roster.
    pub fn channel_react_denied(&self, community_id: &str, channel_id: &str, npubs: &[String]) -> Result<Vec<String>> {
        Self::channel_denied(community_id, channel_id, npubs, crate::community::roles::Permissions::ADD_REACTIONS)
    }

    fn channel_denied(community_id: &str, channel_id: &str, npubs: &[String], perm: u64) -> Result<Vec<String>> {
        let v2 = Self::held_v2(community_id)?;
        let roster = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
        if roster.everyone.is_none() {
            return Ok(Vec::new());
        }
        let owner = v2.owner().ok().map(|o| o.to_hex());
        let chan = channel_id.to_ascii_lowercase();
        let ch = Self::id32(channel_id, "channel_id").ok().and_then(|b| v2.channel(&crate::community::ChannelId(b)));
        let private = ch.is_some_and(|c| c.private);
        Ok(npubs
            .iter()
            .filter(|n| {
                nostr_sdk::prelude::PublicKey::parse(n.as_str())
                    .is_ok_and(|pk| !roster.channel_permissions(owner.as_deref(), &pk.to_hex(), &chan, private).contains(perm))
            })
            .cloned()
            .collect())
    }

    /// What mentions in a community need (CORD-04 §8): who may mention everyone, and so any
    /// Role (`anyone` when `@everyone` itself may), and its Roles top first, each with
    /// whether any member may mention it and whether I hold it.
    pub fn community_mentions(&self, community_id: &str) -> Result<serde_json::Value> {
        use crate::community::roles::Permissions;
        use nostr_sdk::prelude::PublicKey;
        let v2 = Self::held_v2(community_id)?;
        let owner = v2.owner().map_err(VectorError::Other)?.to_hex();
        let roster = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
        let banned = crate::db::community::get_community_banlist(community_id).unwrap_or_default();
        let me = crate::state::my_public_key().map(|pk| pk.to_hex()).unwrap_or_default();
        let members: std::collections::BTreeSet<&str> = std::iter::once(owner.as_str()).chain(roster.grants.iter().map(|g| g.member.as_str())).collect();
        let pingers: Vec<String> = members
            .into_iter()
            .filter(|m| !banned.iter().any(|b| b == m) && roster.is_authorized(m, Some(&owner), Permissions::MENTION_EVERYONE))
            .filter_map(|m| PublicKey::from_hex(m).ok()?.to_bech32().ok())
            .collect();
        let held: std::collections::HashSet<&str> = roster.roles_of(&me).map(|r| r.role_id.as_str()).collect();
        let mut roles: Vec<&crate::community::roles::Role> = roster.roles.iter().filter(|r| crate::community::mentions::is_role_id(&r.role_id)).collect();
        roles.sort_by_key(|r| r.position);
        let roles: Vec<serde_json::Value> = roles
            .into_iter()
            .map(|r| serde_json::json!({ "id": r.role_id, "name": r.name, "color": r.color, "mentionable": r.mentionable, "held": held.contains(r.role_id.as_str()) }))
            .collect();
        Ok(serde_json::json!({
            "anyone": roster.everyone.is_some_and(|e| e.contains(Permissions::MENTION_EVERYONE)),
            "pingers": pingers,
            "roles": roles,
        }))
    }

    /// Whether a message's Role mentions ping me (CORD-04 §8). False on any read failure.
    pub fn role_mentions_ping_me(&self, community_id: &str, author_npub: &str, content: &str, role_ids: &[String]) -> bool {
        if role_ids.is_empty() {
            return false;
        }
        let (Some(me), Ok(author), Ok(Some(held))) = (
            crate::state::my_public_key(),
            nostr_sdk::prelude::PublicKey::parse(author_npub),
            Self::load_held(community_id),
        ) else {
            return false;
        };
        let (Ok(owner), Ok(roster)) = (held.owner(), crate::db::community::get_community_roles(community_id)) else { return false };
        let author = author.to_hex();
        if crate::db::community::get_community_banlist(community_id).unwrap_or_default().contains(&author) {
            return false;
        }
        crate::community::mentions::pings(&roster, Some(&owner.to_hex()), &author, &me.to_hex(), content, role_ids)
    }

    /// Whether a fresh post by `author_npub` in a channel stays silent (CORD-04 §8): they can't
    /// send there, or a Timeout of theirs is running, whatever date they put on the post.
    pub fn post_silenced(&self, community_id: &str, channel_id: &str, author_npub: &str) -> bool {
        if self.channel_send_denied(community_id, channel_id, &[author_npub.to_string()]).is_ok_and(|d| !d.is_empty()) {
            return true;
        }
        let (Ok(v2), Ok(author)) = (Self::held_v2(community_id), nostr_sdk::prelude::PublicKey::parse(author_npub)) else { return false };
        crate::community::v2::service::community_timeouts(&v2).is_ok_and(|t| t.contains_key(&author))
    }

    /// The Timeouts running in a community: npub → { from, until } (unix seconds).
    pub fn community_timeouts(&self, community_id: &str) -> Result<serde_json::Value> {
        let v2 = Self::held_v2(community_id)?;
        let running = crate::community::v2::service::community_timeouts(&v2).map_err(VectorError::Other)?;
        Ok(running
            .into_iter()
            .filter_map(|(pk, (from, until))| Some((pk.to_bech32().ok()?, serde_json::json!({ "from": from, "until": until }))))
            .collect::<serde_json::Map<_, _>>()
            .into())
    }

    /// Time a member out for `seconds` (at most 28 days); 0 lifts a running Timeout.
    pub async fn timeout_member(&self, community_id: &str, npub: &str, seconds: u64) -> Result<()> {
        let v2 = Self::held_v2(community_id)?;
        let member = nostr_sdk::prelude::PublicKey::parse(npub).map_err(|_| VectorError::Other("invalid npub".into()))?;
        crate::community::v2::service::timeout_member(&Self::short_transport(), &v2, &member, seconds).await.map_err(VectorError::Other)
    }

    /// What members are called in a community, for those with a Nickname there: npub → nickname.
    pub fn community_nicknames(&self, community_id: &str) -> Result<serde_json::Value> {
        let v2 = Self::held_v2(community_id)?;
        let named = crate::community::v2::service::community_nicknames(&v2).map_err(VectorError::Other)?;
        Ok(named
            .into_iter()
            .filter_map(|(pk, nick)| Some((pk.to_bech32().ok()?, serde_json::Value::String(nick))))
            .collect::<serde_json::Map<_, _>>()
            .into())
    }

    /// A member's Nickname in a community, when they have one there.
    pub fn member_nickname(&self, community_id: &str, npub: &str) -> Option<String> {
        let v2 = Self::held_v2(community_id).ok()?;
        let member = nostr_sdk::prelude::PublicKey::parse(npub).ok()?;
        crate::community::v2::service::community_nicknames(&v2).ok()?.remove(&member)
    }

    /// Set a member's Nickname in a community (`""` clears it): your own, or one beneath you.
    pub async fn set_community_nickname(&self, community_id: &str, npub: &str, nickname: &str) -> Result<()> {
        let v2 = Self::held_v2(community_id)?;
        let member = nostr_sdk::prelude::PublicKey::parse(npub).map_err(|_| VectorError::Other("invalid npub".into()))?;
        crate::community::v2::service::set_nickname(&Self::short_transport(), &v2, &member, nickname).await.map_err(VectorError::Other)
    }

    /// Delete a Role (Roles v2 only): terminal, it leaves every holder.
    pub async fn delete_role(&self, community_id: &str, role_id: &str) -> Result<()> {
        let v2 = Self::held_v2(community_id)?;
        let transport = Self::short_transport();
        crate::community::v2::service::delete_role_v2(&transport, &v2, role_id).await.map_err(VectorError::Other)?;
        Self::converge_v2_authority(&transport, community_id).await;
        Ok(())
    }

    /// Set what `@everyone` holds. `permissions` is a decimal string.
    pub async fn set_everyone_permissions(&self, community_id: &str, permissions: &str) -> Result<()> {
        let v2 = Self::held_v2(community_id)?;
        let perms = Self::parse_permissions(permissions)?;
        let transport = Self::short_transport();
        crate::community::v2::service::set_everyone(&transport, &v2, perms).await.map_err(VectorError::Other)?;
        Self::converge_v2_authority(&transport, community_id).await;
        Ok(())
    }

    /// Move the community to Roles v2 (owner only). Returns how many Roles it carried over.
    pub async fn activate_roles_v2(&self, community_id: &str, everyone: &str) -> Result<usize> {
        let v2 = Self::held_v2(community_id)?;
        let perms = Self::parse_permissions(everyone)?;
        let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(30));
        let carried = crate::community::v2::service::activate_roles_v2(&transport, &v2, perms).await.map_err(VectorError::Other)?;
        Self::converge_v2_authority(&transport, community_id).await;
        Ok(carried)
    }

    /// Create a Category at the bottom of the sidebar. Returns its id.
    pub async fn create_category(&self, community_id: &str, name: &str) -> Result<String> {
        let v2 = Self::held_v2(community_id)?;
        let id = crate::community::v2::service::create_category(&Self::short_transport(), &v2, name).await.map_err(VectorError::Other)?;
        Ok(crate::simd::hex::bytes_to_hex_32(&id))
    }

    pub async fn rename_category(&self, community_id: &str, category_id: &str, name: &str) -> Result<()> {
        let v2 = Self::held_v2(community_id)?;
        crate::community::v2::service::rename_category(&Self::short_transport(), &v2, Self::id32(category_id, "category_id")?, name).await.map_err(VectorError::Other)
    }

    /// Delete a Category; its Channels render uncategorized.
    pub async fn delete_category(&self, community_id: &str, category_id: &str) -> Result<()> {
        let v2 = Self::held_v2(community_id)?;
        crate::community::v2::service::delete_category(&Self::short_transport(), &v2, Self::id32(category_id, "category_id")?).await.map_err(VectorError::Other)
    }

    /// Move a Category to `index` among the Categories (0 is the top).
    pub async fn move_category(&self, community_id: &str, category_id: &str, index: usize) -> Result<()> {
        let v2 = Self::held_v2(community_id)?;
        crate::community::v2::service::move_category(&Self::short_transport(), &v2, Self::id32(category_id, "category_id")?, index).await.map_err(VectorError::Other)
    }

    /// Move a Channel into a Category (`None` = uncategorized) at `index` among its Channels.
    pub async fn move_channel(&self, community_id: &str, channel_id: &str, category_id: Option<&str>, index: usize) -> Result<()> {
        let v2 = Self::held_v2(community_id)?;
        let channel = crate::community::ChannelId(Self::id32(channel_id, "channel_id")?);
        let category = category_id.map(|c| Self::id32(c, "category_id")).transpose()?;
        crate::community::v2::service::move_channel(&Self::short_transport(), &v2, &channel, category, index).await.map_err(VectorError::Other)
    }

    /// Edit a Channel's name, topic and view (`chat`, `forum` or `voice`).
    pub async fn edit_channel_details(&self, community_id: &str, channel_id: &str, name: &str, topic: Option<&str>, view: &str) -> Result<()> {
        let view = Self::view_named(view)?;
        let v2 = Self::held_v2(community_id)?;
        let channel = crate::community::ChannelId(Self::id32(channel_id, "channel_id")?);
        crate::community::v2::service::edit_channel_details(&Self::short_transport(), &v2, &channel, name, topic, view).await.map_err(VectorError::Other)
    }

    /// Make a Channel private (a key of its own, CORD-03 §2) or public again.
    pub async fn set_channel_private(&self, community_id: &str, channel_id: &str, private: bool) -> Result<()> {
        let v2 = Self::held_v2(community_id)?;
        let channel = crate::community::ChannelId(Self::id32(channel_id, "channel_id")?);
        let transport = Self::short_transport();
        if private {
            return crate::community::v2::service::privatize_channel(&transport, &v2, &channel).await.map_err(VectorError::Other);
        }
        crate::community::v2::service::publicize_channel(&transport, &v2, &channel).await.map_err(VectorError::Other)
    }

    /// Set exactly which Roles a member holds.
    pub async fn set_member_roles(&self, community_id: &str, npub: &str, role_ids: Vec<String>) -> Result<()> {
        let v2 = Self::load_held(community_id)?
            .ok_or_else(|| VectorError::Other("roles need a Concord v2 community".into()))?;
        let member = nostr_sdk::prelude::PublicKey::parse(npub).map_err(|_| VectorError::Other("invalid npub".into()))?;
        let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
        crate::community::v2::service::set_member_roles(&transport, &v2, &member, role_ids)
            .await
            .map_err(VectorError::Other)?;
        Self::converge_v2_authority_soon(community_id);
        Ok(())
    }

    /// Give a member `add` and take `remove`, against the Roles they hold by the freshest
    /// view, so a Role another moderator granted or took meanwhile stays as they left it.
    pub async fn modify_member_roles(&self, community_id: &str, npub: &str, add: &[String], remove: &[String]) -> Result<()> {
        let v2 = Self::load_held(community_id)?
            .ok_or_else(|| VectorError::Other("roles need a Concord v2 community".into()))?;
        let member = nostr_sdk::prelude::PublicKey::parse(npub).map_err(|_| VectorError::Other("invalid npub".into()))?;
        let (add, remove): (Vec<String>, Vec<String>) =
            (add.iter().map(|r| r.to_ascii_lowercase()).collect(), remove.iter().map(|r| r.to_ascii_lowercase()).collect());
        let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
        crate::community::v2::service::change_member_roles(&transport, &v2, &member, move |current| {
            let mut next: Vec<String> = current.iter().map(|r| r.to_ascii_lowercase()).filter(|r| !remove.contains(r)).collect();
            next.extend(add.into_iter().filter(|r| !remove.contains(r)));
            next
        })
        .await
        .map_err(VectorError::Other)?;
        Self::converge_v2_authority_soon(community_id);
        Ok(())
    }

    /// Whether `npub` holds `permission` in this community, per the folded roster.
    ///
    /// The roster IS the ACL (CORD-04), so this is the same question every
    /// enforcement path asks — a bot gating a chat command on it refuses exactly
    /// what the protocol would, instead of inventing a second permission model
    /// that can disagree with the first.
    ///
    /// Deliberately NOT [`community_capabilities`](Self::community_capabilities): that answers "could I publish
    /// this", which additionally needs the Control Plane write key. Here the
    /// caller is asking *someone else* for authority while the bot does the
    /// publishing, so the write key is the bot's problem, not theirs.
    ///
    /// Fails CLOSED. A banned member holds nothing; an unreadable or not-yet-folded
    /// roster answers `false` for everyone but the owner, because `has_permission`
    /// finds no grant. Authority must never be granted by an absence of data.
    pub fn member_has_permission(&self, community_id: &str, npub: &str, permission: u64) -> Result<bool> {
        use nostr_sdk::prelude::PublicKey;
        let who = PublicKey::parse(npub).map_err(|_| VectorError::Other(format!("invalid npub: {npub}")))?.to_hex();
        let owner_hex = Self::load_held(community_id)?
            .ok_or_else(|| VectorError::Other("community not found".into()))?
            .owner()
            .map_err(VectorError::Other)?
            .to_hex();
        if who != owner_hex && crate::db::community::get_community_banlist(community_id).unwrap_or_default().contains(&who) {
            return Ok(false);
        }
        let roster = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
        Ok(roster.is_authorized(&who, Some(&owner_hex), permission))
    }

    /// The community's owner npub + the admin npubs (role overview). A local read,
    /// like [`Self::community_capabilities`].
    pub fn community_roles(&self, community_id: &str) -> Result<serde_json::Value> {
        use nostr_sdk::prelude::{PublicKey, ToBech32};
        let v2 = Self::load_held(community_id)?.ok_or_else(|| VectorError::Other("community not found".into()))?;
        let owner = v2.owner().map_err(VectorError::Other)?;
        let roster = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
        // Exclude banned members from the admin list (a banned npub vanishes, §4).
        let banned = crate::db::community::get_community_banlist(community_id).unwrap_or_default();
        let admins: Vec<String> = roster.grants.iter()
            .filter(|g| roster.is_admin(&g.member) && !banned.contains(&g.member))
            .filter_map(|g| PublicKey::from_hex(&g.member).ok().and_then(|pk| pk.to_bech32().ok()))
            .collect();
        Ok(serde_json::json!({ "owner": owner.to_bech32().ok(), "admins": admins }))
    }

    /// [`converge_v2_authority`](Self::converge_v2_authority) without holding the caller. A Role
    /// change is in this device's own fold the moment it publishes, so the re-read only catches
    /// what others changed meanwhile, and a bot handing out Roles answers as soon as the keys are out.
    fn converge_v2_authority_soon(community_id: &str) {
        let Some(id) = crate::simd::hex::hex_to_bytes_32_checked(community_id).map(crate::community::CommunityId) else { return };
        // A listening client's worker runs the same re-read, one at a time however many ask.
        if crate::community::v2::realtime::follow_worker_running() {
            crate::community::v2::realtime::enqueue_follow(&id);
            return;
        }
        let community_id = community_id.to_string();
        crate::db::spawn_bound(async move {
            let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
            Self::converge_v2_authority(&transport, &community_id).await;
        });
    }

    /// Fold the v2 control plane back in right after publishing an authority change, so the
    /// LOCAL roster/banlist — which is what every read is served from (crowns, in-chat tags,
    /// capabilities, moderation gates) — is current by the time the call returns. `publish`
    /// only returns once a relay ACKed, so this refetch sees our own edition; the fold
    /// announces `community_refreshed` itself when the roster actually moved.
    ///
    /// Best-effort: the edition is already published, so a failed refold is a stale local
    /// cache the next follow repairs, never a failed action.
    async fn converge_v2_authority(
        transport: &crate::community::transport::LiveTransport,
        community_id: &str,
    ) {
        crate::db::scoped(async move {
            // Reload rather than reuse the caller's clone: the publish advanced edition floors,
            // and a rekey/refound may have moved the control address under us.
            if let Ok(Some(fresh)) = Self::load_held(community_id) {
                let _ = crate::community::v2::service::follow_control(transport, &fresh).await;
                // Membership is part of the view being converged: an unban must
                // re-fetch the Guestbook, because a Join that legally raced the ban
                // window may exist only on the relays — and our own just-published
                // edition doesn't echo back to trigger a follow.
                if let Ok(added) = crate::community::v2::service::sync_guestbook(transport, &fresh).await {
                    if !added.is_empty() {
                        traits::emit_event_json(
                            "community_refreshed",
                            serde_json::json!({ "community_id": community_id }),
                        );
                    }
                }
            }
        })
        .await
    }

    /// Grant a member the @admin role. Requires MANAGE_ROLES + outranking the role's position.
    pub async fn grant_admin(&self, community_id: &str, npub: &str) -> Result<()> {
        use crate::community::transport::LiveTransport;
        let member = nostr_sdk::prelude::PublicKey::parse(npub).map_err(|_| VectorError::Other("invalid npub".into()))?;
        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
        let v2 = Self::load_held(community_id)?.ok_or_else(|| VectorError::Other("community not found".into()))?;
        crate::community::v2::service::grant_admin(&transport, &v2, &member)
            .await
            .map_err(VectorError::Other)?;
        Self::converge_v2_authority(&transport, community_id).await;
        Ok(())
    }

    /// Revoke a member's @admin role.
    pub async fn revoke_admin(&self, community_id: &str, npub: &str) -> Result<()> {
        use crate::community::transport::LiveTransport;
        let member = nostr_sdk::prelude::PublicKey::parse(npub).map_err(|_| VectorError::Other("invalid npub".into()))?;
        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
        let v2 = Self::load_held(community_id)?.ok_or_else(|| VectorError::Other("community not found".into()))?;
        crate::community::v2::service::revoke_admin(&transport, &v2, &member)
            .await
            .map_err(VectorError::Other)?;
        Self::converge_v2_authority(&transport, community_id).await;
        Ok(())
    }

    /// Cooperatively kick a member — they self-remove but can rejoin. Requires KICK + outrank.
    pub async fn kick_member(&self, community_id: &str, npub: &str) -> Result<()> {
        crate::db::scoped(async move {
            use crate::community::transport::LiveTransport;
            let pk = nostr_sdk::prelude::PublicKey::parse(npub).map_err(|_| VectorError::Other("invalid npub".into()))?;
            let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
            let v2 = Self::load_held(community_id)?.ok_or_else(|| VectorError::Other("community not found".into()))?;
            crate::community::v2::service::kick_member(&transport, &v2, &pk)
                .await
                .map_err(VectorError::Other)?;
            // Catch the local Guestbook up on our own Kick, so the memberlist read
            // (which folds the STORE, not the network) drops them before this returns
            // instead of waiting on the relay echo. The control fold follows because a
            // Kick strips roles first (CORD-04 §6), which moves the roster too.
            if let Ok(fresh) = crate::community::v2::service::sync_guestbook(&transport, &v2).await {
                if !fresh.is_empty() {
                    emit_event("community_refreshed", &serde_json::json!({ "community_id": community_id }));
                }
            }
            Self::converge_v2_authority(&transport, community_id).await;
            Ok(())
        })
        .await
    }

    /// Ban (`true`) or unban (`false`) a member. Ban is terminal (no rejoin). The read cut:
    /// a private community re-founds (full rotation); a public one rotates just the private
    /// channels the member could read (CORD-05 §5 — no refound, the link refresh would
    /// re-hand them the root). Requires BAN + outrank, checked against the folded roster
    /// BEFORE any publish.
    pub async fn set_member_banned(&self, community_id: &str, npub: &str, banned: bool) -> Result<()> {
        self.set_members_banned(community_id, &[npub], banned).await
    }

    /// Ban (`true`) or unban (`false`) a whole batch as ONE moderation unit: one
    /// Banlist edition, one grant-strip pass, one read cut — a private community
    /// re-founds ONCE with every target removed, however many there are. Additive
    /// on ban, reductive on unban, over the freshest folded list either way.
    ///
    /// Serialized per community (with every other ban/unban) so concurrent
    /// moderation composes in arrival order instead of the last write erasing
    /// its siblings. The wire caps a Banlist at 500 entries — a batch that would
    /// exceed it fails before anything publishes.
    pub async fn set_members_banned(&self, community_id: &str, npubs: &[&str], banned: bool) -> Result<()> {
        use crate::community::{transport::LiveTransport, CommunityId};
        if npubs.is_empty() {
            return Ok(());
        }
        // Parse every target up front — one bad npub fails the batch before any publish.
        let mut pks: Vec<nostr_sdk::prelude::PublicKey> = Vec::with_capacity(npubs.len());
        for n in npubs {
            let pk = nostr_sdk::prelude::PublicKey::parse(n).map_err(|_| VectorError::Other(format!("invalid npub: {n}")))?;
            if !pks.contains(&pk) {
                pks.push(pk);
            }
        }
        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
        // A v2 Ban is the CORD-04 §6 three-removal composition, in order — the Banlist
        // edition first (instant silence), then the Grant strip (authority removal), then
        // the Refounding read-cut (cryptographic severance).
        if community_id.len() != 64 {
            return Err(VectorError::Other("malformed community id".into()));
        }
        let cid = CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
        crate::community::v2::service::set_members_banned(&transport, &cid, &pks, banned)
            .await
            .map_err(VectorError::Other)?;
        // A ban removes them from the memberlist; the memoised verdict still counts them as
        // present and keeps flagging a raid nobody is running any more.
        Self::invalidate_raid_report(community_id);
        Self::announce_ban_change(community_id);
        Ok(())
    }

    /// Our own ban never reaches the fold as a change (the publish already wrote the
    /// list locally), so announce it: the UI re-reads its filtered history, which takes
    /// their messages and their join/leave lines with it.
    fn announce_ban_change(community_id: &str) {
        emit_event("community_refreshed", &serde_json::json!({ "community_id": community_id }));
    }

    /// Re-vend the epoch chain to members a past rotation forgot.
    ///
    /// A client follows rekeys hop by hop and can only ever derive `held + 1`, so
    /// a member missed at one hop is stranded there permanently — no later
    /// rotation can reach them, and re-inviting does not help because they are
    /// already a member. This publishes the blobs that should have existed, keyed
    /// exactly like the original rotation so they merge into it.
    ///
    /// Requires rotation authority (owner or BAN) and the archived roots, which
    /// the rotator holds. Publishing nothing else and touching no membership.
    pub async fn rescue_stranded_members(&self, community_id: &str, npubs: &[&str]) -> Result<serde_json::Value> {
        use nostr_sdk::prelude::PublicKey;
        let community = Self::load_held(community_id)?
            .ok_or_else(|| VectorError::Other("rescuing requires a Concord v2 community".into()))?;
        let mut targets: Vec<PublicKey> = Vec::with_capacity(npubs.len());
        for n in npubs {
            let pk = PublicKey::parse(n).map_err(|_| VectorError::Other(format!("invalid npub: {n}")))?;
            if !targets.contains(&pk) {
                targets.push(pk);
            }
        }
        let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(30));
        let report = crate::community::v2::service::rescue_stranded_members(&transport, &community, &targets)
            .await
            .map_err(VectorError::Other)?;
        serde_json::to_value(report).map_err(|e| VectorError::Other(e.to_string()))
    }

    /// Repair a v2 community's roster cache: keep what is stored, but reset its
    /// PROVENANCE to zero so the next control fold is allowed to replace it.
    ///
    /// The completeness guard retains the cached roster whenever a stored entity is
    /// floored but folds no head — protection against a relay quietly stripping
    /// admins. If the cache itself is wrong, that same guard pins the wrong data in
    /// place: the fold can see the real roster and still be refused. Zeroing the
    /// provenance marks the cache a seed — a guess, not evidence — which the fold may
    /// overwrite. It publishes nothing and touches no key material; worst case the
    /// next fold writes what it can see, which is what a fresh join would get.
    pub async fn repair_community_roster(&self, community_id: &str) -> Result<serde_json::Value> {
        use crate::community::CommunityId;
        if community_id.len() != 64 {
            return Err(VectorError::Other("malformed community id".into()));
        }
        let cid = CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
        if crate::db::community::load_community_v2(&cid).map_err(VectorError::Other)?.is_none() {
            return Err(VectorError::Other("not a held Concord v2 community".into()));
        }
        let before = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
        let before_at = crate::db::community::get_community_roles_at(community_id).map_err(VectorError::Other)?;
        crate::db::community::set_community_roles(community_id, &before, 0).map_err(VectorError::Other)?;
        // Fold immediately so the repair is one step, not two.
        let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(20));
        let community = crate::db::community::load_community_v2(&cid)
            .map_err(VectorError::Other)?
            .ok_or_else(|| VectorError::Other("community vanished mid-repair".into()))?;
        let follow = crate::community::v2::service::follow_control(&transport, &community).await;
        let after = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
        Ok(serde_json::json!({
            "provenance_before": before_at,
            "provenance_after": crate::db::community::get_community_roles_at(community_id).unwrap_or(0),
            "roles_before": before.roles.len(),
            "grants_before": before.grants.len(),
            "roles_after": after.roles.len(),
            "grants_after": after.grants.len(),
            "fold_error": follow.as_ref().err().cloned(),
            "repaired": after.grants.len() > before.grants.len(),
        }))
    }

    /// Explain this account's epoch state for a v2 community: what it holds, what
    /// the next-epoch rekey plane offers, and why each rotation there was or was not
    /// adopted.
    ///
    /// This is the answer to "is this client stranded, and why" — a question that is
    /// otherwise unanswerable, because a stranded client sees only silence and
    /// silence looks exactly like a quiet community. Run it from two clients on one
    /// community to compare their views; the `held` block is where they diverge
    /// first. Read-only; returns public keys and verdicts, never key material.
    pub async fn explain_epoch_state(&self, community_id: &str) -> Result<serde_json::Value> {
        use crate::community::{transport::LiveTransport, CommunityId};
        if community_id.len() != 64 {
            return Err(VectorError::Other("malformed community id".into()));
        }
        let cid = CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
        let community = crate::db::community::load_community_v2(&cid)
            .map_err(VectorError::Other)?
            .ok_or_else(|| VectorError::Other("not a held Concord v2 community".into()))?;
        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(15));
        crate::community::v2::service::explain_epoch_state(&transport, &community)
            .await
            .map_err(VectorError::Other)
    }

    /// Contain a raid (v2 only): ban the named raiders, cut everyone who joined
    /// through the door during the raid window, and perform a SEVERING Refounding
    /// — the rotation that REVOKES the public invite links instead of carrying
    /// them into the new epoch.
    ///
    /// This is the raid lane. An ordinary ban keeps its shipped behaviour, where a
    /// Public community deliberately does not roll the root (the stable-URL refresh
    /// would undo it). Here the link IS the attack surface, so it closes.
    ///
    /// `window_start_secs` is the raid's opening edge (unix seconds); pass 0 to cut
    /// only the convicted. Returns an honest report — a failed refound is reported,
    /// never dressed up as a closed door.
    pub async fn contain_raid(
        &self,
        community_id: &str,
        npubs: &[&str],
        window_start_secs: u64,
        cut_also: &[&str],
    ) -> Result<crate::community::v2::service::ContainmentReport> {
        use crate::community::{transport::LiveTransport, CommunityId};
        if community_id.len() != 64 {
            return Err(VectorError::Other("malformed community id".into()));
        }
        let mut pks: Vec<nostr_sdk::prelude::PublicKey> = Vec::with_capacity(npubs.len());
        for n in npubs {
            let pk = nostr_sdk::prelude::PublicKey::parse(n).map_err(|_| VectorError::Other(format!("invalid npub: {n}")))?;
            if !pks.contains(&pk) {
                pks.push(pk);
            }
        }
        let mut extra: Vec<nostr_sdk::prelude::PublicKey> = Vec::with_capacity(cut_also.len());
        for n in cut_also {
            let pk = nostr_sdk::prelude::PublicKey::parse(n).map_err(|_| VectorError::Other(format!("invalid npub: {n}")))?;
            if !extra.contains(&pk) {
                extra.push(pk);
            }
        }
        let cid = CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
        if !crate::db::community::community_held(&cid).map_err(VectorError::Other)? {
            return Err(VectorError::Other("community not found".into()));
        }
        // Unbound caller (SDK/command): a swap mid-containment would ban in one
        // account and rotate in another.
        let session = crate::db::current_session();
        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(20));
        let report = crate::community::v2::service::contain_raid(&transport, &cid, &pks, window_start_secs, &extra)
            .await
            .map_err(VectorError::Other)?;
        if !session.is_live() {
            return Err(VectorError::Other("account changed during raid containment".into()));
        }
        Self::invalidate_raid_report(community_id);
        Ok(report)
    }

    /// Owner dissolution / "Delete Community": publish the terminal GroupDissolved tombstone (and
    /// retire the owner's own invite links, no rekey), sealing the community permanently. Owner-only
    /// (re-verified cryptographically in `service::dissolve_community`); irreversible.
    pub async fn dissolve_community(&self, community_id: &str) -> Result<()> {
        use crate::community::{transport::LiveTransport, CommunityId};
        if community_id.len() != 64 {
            return Err(VectorError::Other("malformed community id".into()));
        }
        let cid = CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
        // Dissolves at the `community_id`-derived dissolved plane (CORD-02 §9).
        let community = crate::db::community::load_community_v2(&cid)
            .map_err(VectorError::Other)?
            .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
        crate::community::v2::service::dissolve_community(&transport, &community)
            .await
            .map_err(VectorError::Other)?;
        // Its icon and banner have nothing left to show on: off the media server too.
        drop_community_image(community.icon.as_ref().map(|i| i.url.clone()), None);
        drop_community_image(community.banner.as_ref().map(|i| i.url.clone()), community.icon.as_ref().map(|i| i.url.as_str()));
        Ok(())
    }

    /// Edit community metadata (name / description) as an authorized member (MANAGE_METADATA). `None` leaves
    /// a field unchanged; an empty description clears it.
    pub async fn edit_community_metadata(&self, community_id: &str, name: Option<&str>, description: Option<&str>) -> Result<()> {
        use crate::community::{transport::LiveTransport, CommunityId};
        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
        // An authorized vsk-0 control edition, overlaid onto the FULL held document
        // (`CommunityV2::metadata()`): an edition replaces the entity, so a bare name edit
        // would otherwise wipe the icon/banner for every member (CORD-02 §6).
        if community_id.len() != 64 {
            return Err(VectorError::Other("malformed community id".into()));
        }
        let cid = CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
        let community = crate::db::community::load_community_v2(&cid)
            .map_err(VectorError::Other)?
            .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
        let mut meta = community.metadata();
        if let Some(n) = name {
            meta.name = n.to_string();
        }
        if let Some(d) = description {
            meta.description = if d.is_empty() { None } else { Some(d.to_string()) };
        }
        crate::community::v2::service::edit_community_metadata(&transport, &community, &meta)
            .await
            .map_err(VectorError::Other)
    }

    /// Take a Community's logo or banner away (MANAGE_METADATA). An edition is the whole
    /// document, so one without the image removes it for every member.
    pub async fn remove_community_image(&self, community_id: &str, is_banner: bool) -> Result<()> {
        use crate::community::{transport::LiveTransport, CommunityId};
        let session = crate::db::current_session();
        let cid = CommunityId(Self::id32(community_id, "community_id")?);
        let community = crate::db::community::load_community_v2(&cid)
            .map_err(VectorError::Other)?
            .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
        let mut meta = community.metadata();
        let gone = if is_banner { meta.banner.take() } else { meta.icon.take() };
        let kept = if is_banner { meta.icon.as_ref() } else { meta.banner.as_ref() }.map(|i| i.url.clone());
        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
        crate::community::v2::service::edit_community_metadata(&transport, &community, &meta)
            .await
            .map_err(VectorError::Other)?;
        // Unbound caller: the edition is out, but the account on screen may no longer be its own.
        if !session.is_live() {
            return Err(VectorError::Other("account changed while removing the image".into()));
        }
        drop_community_image(gone.map(|i| i.url), kept.as_deref());
        if let Some(updated) = crate::community::v2::service::persist_community_image(&cid, None, is_banner).await {
            self.register_v2_chats(&updated, &session).await;
        }
        Ok(())
    }

    /// Set a Community's icon, or its banner when `is_banner`, from image bytes (MANAGE_METADATA).
    /// The image is stripped of metadata and fitted first, then encrypted so only members can
    /// open it. Returns the uploaded blob's URL.
    pub async fn set_community_image(&self, community_id: &str, bytes: &[u8], is_banner: bool) -> Result<String> {
        let usage = if is_banner { crate::image_prep::ImageUse::Banner } else { crate::image_prep::ImageUse::Icon };
        let raw = bytes.to_vec();
        let prepared = crate::rt::spawn_blocking(move || crate::image_prep::prepare(&raw, usage))
            .await
            .map_err(|e| VectorError::Other(format!("image preparation stopped: {e}")))?
            .map_err(VectorError::Other)?;
        self.publish_community_image(community_id, prepared.bytes, prepared.extension, is_banner, None).await
    }

    /// [`set_community_image`](Self::set_community_image) for bytes already prepared, which
    /// are published as given. `progress` hears the upload.
    pub async fn publish_community_image(
        &self,
        community_id: &str,
        bytes: Vec<u8>,
        extension: &str,
        is_banner: bool,
        progress: Option<crate::blossom::ProgressCallback>,
    ) -> Result<String> {
        use crate::community::{transport::LiveTransport, CommunityId};
        let session = crate::db::current_session();
        let cid = CommunityId(Self::id32(community_id, "community_id")?);
        crate::db::community::load_community_v2(&cid)
            .map_err(VectorError::Db)?
            .ok_or_else(|| VectorError::NotFound("community".into()))?;
        if crate::svg::looks_like_svg(&bytes) {
            return Err(VectorError::Other(crate::community::SVG_REFUSED.to_string()));
        }
        let hash = crate::crypto::sha256_hex(&bytes);
        // A fresh key per image: it rides the members-only metadata edition.
        let params = crate::crypto::generate_encryption_params();
        let encrypted = crate::crypto::encrypt_data(&bytes, &params).map_err(VectorError::Other)?;
        let signer = crate::signer::active_signer().map_err(|e| VectorError::Other(format!("signer: {e}")))?;
        let servers = state::get_blossom_servers();
        if servers.is_empty() {
            return Err(VectorError::Other("no Blossom servers configured".into()));
        }
        let progress = progress.unwrap_or_else(|| std::sync::Arc::new(|_, _| Ok(())));
        let url = crate::blossom::upload_blob_with_progress_and_failover(
            signer,
            servers,
            std::sync::Arc::new(encrypted),
            Some("application/octet-stream"),
            true,
            progress,
            None,
            None,
            None,
        )
        .await
        .map_err(VectorError::Other)?
        .url;
        let mut extra = serde_json::Map::new();
        extra.insert("ext".into(), serde_json::Value::String(extension.to_string()));
        let image = crate::community::v2::control::ImageRef { url: url.clone(), key: params.key.clone(), nonce: params.nonce.clone(), hash, extra };
        // The edition signs as whoever is live: never as the account that took over mid-upload.
        if !session.is_live() {
            return Err(VectorError::Other("account changed while setting the image".into()));
        }
        // Overlaid onto the document as it stands after the upload, so an edit made meanwhile
        // survives; an edition replaces the whole of it.
        let community = crate::db::community::load_community_v2(&cid)
            .map_err(VectorError::Db)?
            .ok_or_else(|| VectorError::NotFound("community".into()))?;
        let mut meta = community.metadata();
        let replaced = if is_banner { meta.banner.replace(image.clone()) } else { meta.icon.replace(image.clone()) };
        let kept = if is_banner { meta.icon.as_ref() } else { meta.banner.as_ref() }.map(|i| i.url.clone());
        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
        crate::community::v2::service::edit_community_metadata(&transport, &community, &meta)
            .await
            .map_err(VectorError::Other)?;
        if !session.is_live() {
            return Err(VectorError::Other("account changed while setting the image".into()));
        }
        drop_community_image(replaced.map(|i| i.url).filter(|u| *u != url), kept.as_deref());
        if let Some(updated) = crate::community::v2::service::persist_community_image(&cid, Some(image), is_banner).await {
            self.register_v2_chats(&updated, &session).await;
        }
        Ok(url)
    }

    /// A Community's icon, or its banner when `is_banner`, as a member sees it: downloaded,
    /// decrypted and checked against the hash the metadata commits to. `None` when it has none.
    pub async fn community_image(&self, community_id: &str, is_banner: bool) -> Result<Option<Vec<u8>>> {
        use crate::community::CommunityId;
        let cid = CommunityId(Self::id32(community_id, "community_id")?);
        let community = crate::db::community::load_community_v2(&cid)
            .map_err(VectorError::Other)?
            .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
        let Some(image) = (if is_banner { community.banner } else { community.icon }) else {
            return Ok(None);
        };
        let cap: usize = if is_banner { 16 } else { 10 } * 1024 * 1024;
        // The URL is the editor's to write: refuse one aimed inside this machine's network.
        crate::net::validate_url_not_private(&image.url).map_err(|e| VectorError::Network(format!("community image URL refused: {e}")))?;
        let client = crate::net::build_http_client(std::time::Duration::from_secs(30)).map_err(VectorError::Network)?;
        let resp = crate::net::proxied_request(&client, reqwest::Method::GET, &image.url)
            .await
            .send()
            .await
            .map_err(|e| VectorError::Network(format!("download: {e}")))?;
        if !resp.status().is_success() {
            return Err(VectorError::Network(format!("download failed: HTTP {}", resp.status())));
        }
        let mut encrypted: Vec<u8> = Vec::with_capacity(resp.content_length().map_or(64 * 1024, |l| (l as usize).min(cap)));
        let mut body = resp.bytes_stream();
        while let Some(chunk) = futures_util::StreamExt::next(&mut body).await {
            let chunk = chunk.map_err(|e| VectorError::Network(format!("read body: {e}")))?;
            if encrypted.len() + chunk.len() > cap {
                return Err(VectorError::Other("community image too large".into()));
            }
            encrypted.extend_from_slice(&chunk);
        }
        let plain = crate::crypto::decrypt_data_owned(encrypted, &image.key, &image.nonce).map_err(VectorError::Crypto)?;
        if crate::crypto::sha256_hex(&plain) != image.hash {
            return Err(VectorError::Crypto("community image failed its integrity check".into()));
        }
        if crate::svg::looks_like_svg(&plain) {
            return Err(VectorError::Other(crate::community::SVG_REFUSED.to_string()));
        }
        Ok(Some(plain))
    }

    /// Set the iroh relays a Community's voice channels use (CORD-07 §8): at most eight, https
    /// only; none means iroh's defaults. Overlaid onto the held document like any metadata edit.
    pub async fn set_voice_relays(&self, community_id: &str, relays: &[String]) -> Result<Vec<String>> {
        use crate::community::{transport::LiveTransport, CommunityId};
        let cid = CommunityId(Self::id32(community_id, "community_id")?);
        let community = crate::db::community::load_community_v2(&cid)
            .map_err(VectorError::Other)?
            .ok_or_else(|| VectorError::Other("v2 community not found".into()))?;
        let mut clean: Vec<String> = Vec::new();
        for r in relays.iter().map(|r| r.trim().trim_end_matches('/').to_string()).filter(|r| !r.is_empty()) {
            let parsed = url::Url::parse(&r).map_err(|_| VectorError::Other(format!("{r} isn't a relay address")))?;
            if parsed.scheme() != "https" || parsed.host_str().is_none() {
                return Err(VectorError::Other(format!("{r}: a voice relay is an https:// address")));
            }
            let normal = format!("{}/", parsed.as_str().trim_end_matches('/'));
            if !clean.contains(&normal) {
                clean.push(normal);
            }
        }
        if clean.len() > crate::community::v2::community::MAX_VOICE_RELAYS {
            return Err(VectorError::Other(format!("at most {} voice relays", crate::community::v2::community::MAX_VOICE_RELAYS)));
        }
        let mut meta = community.metadata();
        if clean.is_empty() {
            meta.extra.remove("voice_relays");
        } else {
            meta.extra.insert("voice_relays".into(), serde_json::json!(clean));
        }
        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
        crate::community::v2::service::edit_community_metadata(&transport, &community, &meta).await.map_err(VectorError::Other)?;
        Ok(clean)
    }

    /// Leave a Community: announce a best-effort "left" presence (before dropping keys), then
    /// drop the held keys + local channel chats. You need a fresh invite to rejoin.
    pub async fn leave_community(&self, community_id: &str) -> Result<()> {
        crate::db::scoped(async move {
            use crate::community::transport::LiveTransport;
            if community_id.len() != 64 {
                return Err(VectorError::Other("malformed community id".into()));
            }
            use crate::community::v2::service;
            let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
            let Some(v2) = Self::load_held(community_id)? else {
                let cid = Self::unheld_id(community_id)?;
                let at_ms = service::leave_unheld_locally(&cid).await.ok_or_else(|| VectorError::Other("community not found".into()))?;
                service::announce_unheld_leave(&transport, &cid, at_ms).await;
                return Ok(());
            };
            // Guestbook Leave + cross-device List tombstone + local delete, in the service.
            let channel_ids: Vec<String> =
                v2.channels.iter().map(|ch| crate::simd::hex::bytes_to_hex_32(&ch.id.0)).collect();
            service::leave_community(&transport, &v2).await.map_err(VectorError::Other)?;
            service::forget_community_chats(&crate::simd::hex::bytes_to_hex_32(&v2.id().0), &channel_ids).await;
            Ok(())
        })
        .await
    }

    /// [`Self::leave_community`] for a caller that repaints at once: the community is gone
    /// here when this returns, and the announcements publish behind it. The List
    /// tombstone is kept pending first, so a leave survives a restart before it lands.
    pub async fn leave_community_now(&self, community_id: &str) -> Result<()> {
        crate::db::scoped(async move {
            use crate::community::v2::service;
            let Some(v2) = Self::load_held(community_id)? else {
                let cid = Self::unheld_id(community_id)?;
                let at_ms = service::leave_unheld_locally(&cid).await.ok_or_else(|| VectorError::Other("community not found".into()))?;
                crate::db::spawn_bound(async move {
                    let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
                    service::announce_unheld_leave(&transport, &cid, at_ms).await;
                });
                return Ok(());
            };
            let channel_ids: Vec<String> =
                v2.channels.iter().map(|ch| crate::simd::hex::bytes_to_hex_32(&ch.id.0)).collect();
            let at_ms = service::leave_locally(&v2).map_err(VectorError::Other)?;
            service::forget_community_chats(&crate::simd::hex::bytes_to_hex_32(&v2.id().0), &channel_ids).await;
            crate::db::spawn_bound(async move {
                let transport = crate::community::transport::LiveTransport::with_timeout(std::time::Duration::from_secs(12));
                service::announce_leave(&transport, &v2, at_ms).await;
                if let Some(client) = state::nostr_client() {
                    crate::community::v2::realtime::refresh_subscription(&client).await;
                }
                // After the announcements, which still need these relays.
                crate::community::transport::prune_unneeded_community_relays(&v2.relays).await;
            });
            Ok(())
        })
        .await
    }

    /// Decline a parked invite: dropped here, tombstoned in the Community List so no device parks
    /// it again, the wraps that delivered it deleted from our relays, and the relays its bundle
    /// named shed.
    pub async fn decline_community_invite(&self, community_id: &str) -> Result<()> {
        crate::db::scoped(async move {
            use crate::db::community as db;
            // A bundle this build can't parse names no community the List could ever hold: only drop it.
            let bundle = db::get_pending_invite(community_id)
                .ok()
                .flatten()
                .and_then(|j| crate::community::v2::invite::CommunityInvite::from_bundle_json(&j).ok());
            let relays: Vec<String> = bundle.as_ref().map(|b| b.relays.clone()).unwrap_or_default();
            let wraps = db::pending_invite_wraps(community_id).unwrap_or_default();
            db::delete_pending_invite(community_id).map_err(VectorError::Other)?;
            if let Some(cid) = bundle.and_then(|_| crate::simd::hex::hex_to_bytes_32_checked(community_id)) {
                let removed_at = crate::clock::now_ms();
                crate::community::v2::service::tombstone_community_list_durable(crate::community::CommunityId(cid), relays.clone(), removed_at);
            }
            for wrap in wraps.iter().filter_map(|w| nostr_sdk::prelude::EventId::from_hex(w).ok()) {
                crate::deletion::delete_received_wrap(wrap);
            }
            if !relays.is_empty() {
                crate::community::transport::prune_unneeded_community_relays(&relays).await;
            }
            Ok(())
        })
        .await
    }

    /// Sync DM history from relays using NIP-77 negentropy set reconciliation.
    ///
    /// Reconciles local wrapper history with relay state, fetches missing events,
    /// and processes them through the standard prepare → commit pipeline.
    ///
    /// Returns (total_events, new_messages).
    ///
    /// ```no_run
    /// # async fn example() -> vector_core::Result<()> {
    /// let core = vector_core::VectorCore;
    /// // Sync last 7 days of DMs
    /// let (events, new) = core.sync_dms(Some(7), &vector_core::NoOpEventHandler).await?;
    /// println!("Processed {} events, {} new messages", events, new);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn sync_dms(
        &self,
        since_days: Option<u64>,
        handler: &dyn InboundEventHandler,
    ) -> Result<(u32, u32)> {
        crate::db::scoped(async move {
            use futures_util::StreamExt;
            use nostr_sdk::prelude::*;

            let client = state::nostr_client()
                .ok_or(VectorError::Other("Not connected".into()))?;
            let my_pk = state::my_public_key()
                .ok_or(VectorError::Other("Not logged in".into()))?;

            // Load known wrapper IDs + timestamps for negentropy fingerprinting.
            // A windowed sync bounds the read in SQL: materialising all of
            // history to keep a few days of it is most of this function's cost
            // on an established account.
            let (items, filter) = if let Some(days) = since_days {
                let since_ts = crate::clock::timestamp().as_secs().saturating_sub(days * 24 * 3600);
                let items = db::wrappers::load_negentropy_items_since(since_ts)
                    .unwrap_or_default();
                let filter = Filter::new()
                    .pubkey(my_pk)
                    .kind(Kind::GiftWrap)
                    .since(Timestamp::from_secs(since_ts));
                (items, filter)
            } else {
                let items = db::wrappers::load_negentropy_items().unwrap_or_default();
                let filter = Filter::new()
                    .pubkey(my_pk)
                    .kind(Kind::GiftWrap);
                (items, filter)
            };

            log_info!("[SyncDMs] {} negentropy items, since_days={:?}", items.len(), since_days);
            let items = std::sync::Arc::new(items);

            // Dry-run negentropy: exchange fingerprints to identify missing events
            let sync_opts = nostr_sdk::prelude::SyncOptions::new()
                .direction(nostr_sdk::prelude::SyncDirection::Down)
                .initial_timeout(relay_request_timeout(std::time::Duration::from_secs(10)))
                .dry_run();

            // Race all relays — first to reconcile drives the fetch. Relays with a
            // fresh no-NIP-77 verdict skip the doomed reconcile and get a bounded
            // REQ pass below instead.
            let relay_map = client.relays().await;
            let (all_relays, no_neg_relays): (Vec<_>, Vec<_>) =
                relay_map.iter()
                    .map(|(url, relay)| (url.clone(), relay.clone()))
                    .partition(|(url, _)| negentropy::neg_supported_cached(url.as_str()) != Some(false));
            drop(relay_map);
            let skipped_no_neg: Vec<String> = no_neg_relays.iter().map(|(u, _)| u.to_string()).collect();
            if !skipped_no_neg.is_empty() {
                log_info!("[SyncDMs] {} relay(s) on REQ path (no NIP-77)", skipped_no_neg.len());
            }

            // Tor-aware like the GUI path — a fixed clearnet budget over Tor makes
            // a healthy relay's slow first frame look like connected-silence and
            // earns it a false 24h no-NEG verdict in the shared account KV.
            let neg_budget = relay_request_timeout(std::time::Duration::from_secs(10));
            let neg_outer = neg_budget + std::time::Duration::from_secs(5);
            let connect_allowance = relay_request_timeout(std::time::Duration::from_secs(3))
                .min(neg_outer);
            let mut relay_futs = futures_util::stream::FuturesUnordered::new();
            for (url, relay) in &all_relays {
                let url = url.clone();
                let relay = relay.clone();
                let f = filter.clone();
                let i = items.clone();
                let o = sync_opts.clone();
                relay_futs.push(async move {
                    if !negentropy::wait_connected(&relay, connect_allowance).await {
                        return (url, None, false);
                    }
                    // Outer slack over the initial_timeout so the SDK's error
                    // (which distinguishes refusal from silence) surfaces first.
                    let result = crate::rt::time::timeout(
                        neg_outer,
                        relay.sync(f).items(i.iter().copied()).opts(o),
                    ).await;
                    let connected = relay.status() == RelayStatus::Connected;
                    (url, Some(result), connected)
                });
            }

            // Collect missing IDs from all relays
            let cap_session = crate::db::current_session();
            let mut all_missing: std::collections::HashSet<EventId> = std::collections::HashSet::new();
            while let Some((url, result, connected)) = relay_futs.next().await {
                let Some(result) = result else {
                    log_warn!("[SyncDMs] {} skipped: not connected", url);
                    continue;
                };
                match result {
                    Ok(Ok(recon)) => {
                        let count = recon.remote.len();
                        all_missing.extend(recon.remote);
                        log_info!("[SyncDMs] {} reconciled: {} missing", url, count);
                        negentropy::record_neg_support(url.as_str(), true);
                    }
                    Ok(Err(e)) => {
                        log_warn!("[SyncDMs] {} failed: {}", url, e);
                        if cap_session.is_live()
                            && negentropy::classify_neg_sync_error(&e.to_string(), connected && !negentropy::neg_ever_confirmed(url.as_str())) == Some(false)
                        {
                            log_info!("[SyncDMs] {} marked no-NIP-77 for 24h", url);
                            negentropy::record_neg_support(url.as_str(), false);
                        }
                    }
                    Err(_) => log_warn!("[SyncDMs] {} timed out ({:?})", url, neg_outer),
                }
            }

            let mut total_events = 0u32;
            let mut new_messages = 0u32;

            // No-NIP-77 relays still contribute: one bounded REQ over the same
            // filter. The 500-event cap keeps a `since_days: None` call from
            // pulling a whole mailbox — deep history is negentropy's job on the
            // relays that speak it.
            if !skipped_no_neg.is_empty() {
                let req_filter = filter.clone().limit(500);
                match client
                    .stream_events(nostr_sdk::prelude::ReqTarget::manual(
                        skipped_no_neg.iter().cloned().map(|u| (u, vec![req_filter.clone()])),
                    ))
                    .timeout(relay_request_timeout(std::time::Duration::from_secs(20)))
                    .await
                {
                    Ok(stream) => {
                        let mut seen: std::collections::HashSet<[u8; 32]> = std::collections::HashSet::new();
                        let stream = stream.ready_chunks(event_handler::UNWRAP_BATCH);
                        tokio::pin!(stream);
                        while let Some(chunk) = stream.next().await {
                            // Straddles the stream: a swap mid-drain must not push
                            // the old account's wrappers through the new account's
                            // pipeline (ErrorSkip would ledger them there).
                            let events: Vec<Event> = chunk
                                .into_iter()
                                .filter_map(|(_relay, res)| res.ok())
                                .filter(|event| seen.insert(event.id.to_bytes()))
                                .collect();
                            total_events += events.len() as u32;
                            for prepared in event_handler::prepare_events(&events, my_pk).await {
                                if event_handler::commit_prepared_event(prepared, false, handler).await {
                                    new_messages += 1;
                                }
                            }
                        }
                    }
                    Err(e) => log_warn!("[SyncDMs] REQ pass failed: {}", e),
                }
            }

            if all_missing.is_empty() {
                log_info!("[SyncDMs] No missing events");
                return Ok((total_events, new_messages));
            }

            // Fetch missing events in batches
            log_info!("[SyncDMs] Fetching {} missing events", all_missing.len());
            let ids: Vec<EventId> = all_missing.into_iter().collect();
            let relay_strs: Vec<String> = client.relays().await.keys()
                .map(|u| u.to_string()).collect();

            const BATCH_SIZE: usize = 500;

            for batch in ids.chunks(BATCH_SIZE) {
                // The #p is not redundant: Ditto refuses gift-wrap REQs that carry
                // neither authors nor #p, even authed — ids-only returns nothing.
                let f = Filter::new().ids(batch.to_vec()).kind(Kind::GiftWrap).pubkey(my_pk);
                match client
                    .stream_events(nostr_sdk::prelude::ReqTarget::manual(
                        relay_strs.iter().cloned().map(|u| (u, vec![f.clone()])),
                    ))
                    .timeout(std::time::Duration::from_secs(30))
                    .await
                {
                    Ok(stream) => {
                        let prepared_stream = stream
                            .filter_map(|(_relay, res)| async move { res.ok() })
                            .ready_chunks(event_handler::UNWRAP_BATCH)
                            .map(move |events| {
                                db::spawn_bound(async move {
                                    event_handler::prepare_events(&events, my_pk).await
                                })
                            })
                            .buffer_unordered(8);
                        tokio::pin!(prepared_stream);

                        while let Some(result) = prepared_stream.next().await {
                            let Ok(batch) = result else { continue };
                            total_events += batch.len() as u32;
                            for prepared in batch {
                                if event_handler::commit_prepared_event(prepared, false, handler).await {
                                    new_messages += 1;
                                }
                            }
                        }
                    }
                    Err(e) => log_warn!("[SyncDMs] Batch fetch error: {}", e),
                }
            }

            log_info!("[SyncDMs] Complete: {} events processed, {} new messages", total_events, new_messages);
            Ok((total_events, new_messages))
        })
        .await
    }

    // ========================================================================
    // Event Subscription
    // ========================================================================

    /// Subscribe to incoming DM events (NIP-17 GiftWraps).
    ///
    /// Returns the subscription ID for use in a custom notification loop.
    /// For a complete listen-and-process loop, use [`listen()`](Self::listen) instead.
    pub async fn subscribe_dms(&self) -> Result<nostr_sdk::prelude::SubscriptionId> {
        use nostr_sdk::prelude::*;
        let client = state::nostr_client()
            .ok_or(VectorError::Other("Not connected".into()))?;
        let my_pk = state::my_public_key()
            .ok_or(VectorError::Other("Not logged in".into()))?;

        let filter = Filter::new()
            .pubkey(my_pk)
            .kind(Kind::GiftWrap)
            .limit(0);

        let output = client.subscribe(filter.clone()).await
            .map_err(|e| VectorError::Nostr(e.to_string()))?;
        live_subs::keep_output(&output, vec![filter]);
        Ok(output.value)
    }

    /// Catch up every locally-held Community: fold control / re-foundings / rekeys / banlist and
    /// fetch recent messages into local state for each channel. History stays local; a listener is
    /// told what it fetched that was sent since it began listening ([`news`]). Called at `listen()`
    /// start and on reconnect; also safe to call manually after a known disconnect.
    ///
    /// Catch up every locally-held Community. Each is ENQUEUED for the follow worker (control/rekey re-fold + adopt),
    /// non-blocking. History is never replayed to a handler. Called at `listen()`
    /// start and on reconnect; safe to call manually — the v2 enqueue is a no-op if
    /// no `listen()` worker is running.
    /// Returns each community's non-fatal follow warnings (rekey/control catch-up
    /// failures), prefixed with the id. A caller that discards them is blind to
    /// "the sync ran, but this account never adopted the rotation" — which reads
    /// exactly like a healthy quiet sync while the account sits on a dead epoch.
    pub async fn sync_communities(&self) -> Result<Vec<String>> {
        let mut all_warnings: Vec<String> = Vec::new();
        // Discover + rehydrate memberships from the Community List across devices (CORD-02 §8),
        // bootstrapping from the client's connected relays so even a fresh device that
        // holds no community yet can find them. Best-effort.
        {
            use crate::community::{transport::LiveTransport, v2::service as v2};
            let bootstrap: Vec<String> = match crate::state::nostr_client() {
                Some(client) => client.relays().await.keys().map(|r| r.to_string()).collect(),
                None => Vec::new(),
            };
            let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
            if let Ok(outcome) = v2::sync_community_list(&transport, &bootstrap).await {
                // Headless: core already dropped the rows; a GUI shell additionally clears the
                // chat rows + STATE via `removed` (see `ListSyncOutcome`).
                let joined = outcome.joined;
                for c in &joined {
                    if community::v2::realtime::follow_worker_running() {
                        community::v2::realtime::enqueue_follow(c.id());
                    } else {
                        let cid_hex = crate::simd::hex::bytes_to_hex_32(&c.id().0);
                        all_warnings.extend(
                            Self::v2_inline_follow(c.id()).await.into_iter().map(|w| format!("{}: {w}", &cid_hex[..8])),
                        );
                    }
                }
                if !joined.is_empty() {
                    if let Some(client) = crate::state::nostr_client() {
                        community::v2::realtime::refresh_subscription(&client).await;
                    }
                }
            }
        }

        let ids = db::community::list_community_ids().map_err(VectorError::from)?;
        for id in ids {
            // With a live listen() the coalescing worker owns the follow; headless
            // (no worker) it would be dropped, so walk it inline instead.
            if community::v2::realtime::follow_worker_running() {
                community::v2::realtime::enqueue_follow(&id);
            } else {
                let cid_hex = crate::simd::hex::bytes_to_hex_32(&id.0);
                all_warnings.extend(
                    Self::v2_inline_follow(&id).await.into_iter().map(|w| format!("{}: {w}", &cid_hex[..8])),
                );
            }
            // Back-fill each channel's chat. Without this a headless client only ever sees messages that arrive
            // LIVE: anything sent while it was down — or while it held no key for
            // a private channel — is never fetched, so a bot granted access reads
            // an empty room. Cheap when there is nothing new (id-deduped), and a
            // channel we cannot read simply yields nothing.
            if let Ok(Some(c)) = db::community::load_community_v2(&id) {
                for ch in &c.channels {
                    let hex = crate::simd::hex::bytes_to_hex_32(&ch.id.0);
                    let _ = Self::v2_backfill_channel(
                        &id, &hex, 50, 2, None, None,
                        crate::community::transport::Evidence::Fast, 12,
                    ).await;
                }
            }
        }
        Ok(all_warnings)
    }


    /// Start listening for incoming DMs.
    ///
    /// Blocks until the client disconnects. Processes GiftWraps
    /// (DMs, files) → prepare_event → commit_prepared_event.
    ///
    /// ```no_run
    /// use vector_core::*;
    /// use std::sync::Arc;
    ///
    /// struct MyBot;
    /// impl InboundEventHandler for MyBot {
    ///     fn on_dm_received(&self, chat_id: &str, msg: &Message, _is_new: bool) {
    ///         if msg.mine { return; }
    ///         let to = chat_id.to_string();
    ///         let reply = format!("Echo: {}", msg.content);
    ///         tokio::spawn(async move {
    ///             let _ = VectorCore.send_dm(&to, &reply).await;
    ///         });
    ///     }
    /// }
    ///
    /// # async fn example() -> vector_core::Result<()> {
    /// let core = VectorCore::init(CoreConfig {
    ///     data_dir: "/tmp/bot-data".into(),
    ///     event_emitter: None,
    /// })?;
    /// core.login("nsec1...", None).await?;
    /// core.listen(Arc::new(MyBot)).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn listen(&self, handler: Arc<dyn InboundEventHandler>) -> Result<()> {
        self.listen_with(handler, CatchUp::Inline).await
    }

    /// `listen`, choosing who fetches what was published while offline.
    pub async fn listen_with(&self, handler: Arc<dyn InboundEventHandler>, catch_up: CatchUp) -> Result<()> {
        use nostr_sdk::prelude::*;

        let client = state::nostr_client()
            .ok_or(VectorError::Other("Not connected".into()))?;
        let my_pk = state::my_public_key()
            .ok_or(VectorError::Other("Not logged in".into()))?;

        // Start the stream-AUTH responder BEFORE any relay interaction: a gating
        // relay issues its NIP-42 challenge ONCE per connection, and the DM
        // subscribe below consumes it via nostr-sdk's user auto-auth — if the
        // responder isn't already watching, that challenge is never remembered
        // and the stream keys registered later can NEVER authenticate (the relay
        // won't re-challenge an authed connection; the v2 sub dies silently).
        community::v2::streamauth::ensure_responder(&client);

        // From here on, whatever is sent is news to this listener however it arrives: live, a
        // catch-up or a replay, once each. A UI pages history itself and keeps freshness.
        let listening_since = crate::clock::now_ms();
        let inline = catch_up == CatchUp::Inline;
        if inline {
            news::begin(handler.clone(), listening_since);
        } else {
            news::end();
        }
        let live_from = news::cutoff().unwrap_or(listening_since);

        // The change baseline is what this device holds before anything folds, so a change
        // the catch-up brings in is compared rather than absorbed; one made before listening
        // began is history.
        if handler.wants_community_changes() {
            community::v2::changes::prime_all(&*handler);
        }

        // Spawn the single per-community follow worker for this session; the v2
        // follow queue (fed by dispatch, catch-up, and sync) drains through it.
        community::v2::realtime::spawn_follow_worker(handler.clone());
        early::start(handler.clone());

        // DMs go live BEFORE the catch-up: the subscription only carries what is
        // published after it starts, so a wrap sent mid-catch-up reaches us by one
        // or the other. Wrapper dedup absorbs any it gets from both. The stream is
        // read from here on, catch-up included, keeping only live subscriptions'
        // events: the catch-up's own traffic shares the notification ring and
        // would otherwise push them out of it.
        let notifications = client.notifications();
        let dm_sub_id = self.subscribe_dms().await?;
        live_subs::watch(&client);
        let (live_tx, mut live_rx) = tokio::sync::mpsc::channel::<(LiveRoute, Box<nostr_sdk::prelude::Event>)>(4096);
        let dm_sid = dm_sub_id.clone();
        db::spawn_bound(async move {
            let mut notifications = notifications;
            while let Some(notification) = notifications.next().await {
                // Relay OKs feed the send pipeline: an OK that outlives the
                // per-attempt wait still confirms delivery, and can rescue a
                // message already marked Failed.
                if let nostr_sdk::prelude::ClientNotification::Message { message, .. } = &notification {
                    if let nostr_sdk::prelude::RelayMessage::Ok { event_id, status, .. } = &**message {
                        sending::note_relay_ok(event_id, *status);
                    }
                }
                let nostr_sdk::prelude::ClientNotification::Event { event, subscription_id, .. } = notification else { continue };
                let route = if subscription_id == dm_sid {
                    LiveRoute::Dm
                } else if community::v2::realtime::routes_live(&subscription_id) {
                    LiveRoute::CommunityV2
                } else {
                    continue;
                };
                if live_tx.send((route, event)).await.is_err() {
                    break;
                }
            }
        });

        // Outage resilience — catch up on connect, then re-sync periodically.
        //
        // Communities catch up BEFORE their subscriptions so a bot that was offline folds any
        // missed re-foundings / metadata / banlist changes (and recent messages) into local state,
        // and subscribes at the CURRENT epoch pseudonyms. History stays local (query it via
        // `get_messages`); what it brings in that was sent since listening began is news, and
        // reaches the handler once (see `news`, `LiveOnly`).
        if inline {
            let _ = self.sync_communities().await;
            let _ = self.sync_dms(None, &event_handler::LiveOnly::from(&*handler, live_from)).await;
        }

        // Community channel events share the DM loop below, so `on_dm_received` /
        // `on_community_message` share a sink.
        community::v2::realtime::refresh_subscription(&client).await;

        // The Community subscriptions start after the catch-up: what was published between the
        // two reaches the listener through a replay of the planes since listening began.
        if inline {
            Self::owe_catch_up(false, false, [(EVERY_RELAY.to_string(), live_from)]);
            // A relay closing a subscription, or the machine sleeping, leaves a gap the same
            // runner fills. The app sets its own.
            live_subs::set_catch_up(|what| {
                let now = crate::clock::now_ms();
                match what {
                    live_subs::CatchUp::All { away_ms } => Self::owe_catch_up(true, true, [(EVERY_RELAY.to_string(), now.saturating_sub(away_ms))]),
                    live_subs::CatchUp::Relay(url) => Self::owe_catch_up(false, false, [(url, now.saturating_sub(live_subs::MAX_BACKOFF.as_millis() as u64))]),
                }
            });
            #[cfg(not(target_arch = "wasm32"))]
            live_subs::start_wake_watch();
        }

        // The subscriptions above are COMMITTED: live events flow from here. Say
        // so — the startup gauntlet (relay-connect wait + stream-auth priming)
        // can take a minute against a slow relay set, and without this signal a
        // bot cannot tell "still connecting" from "subscribed to nothing".
        // Fires even with 0 communities: that too is a completed, ready state.
        handler.on_subscription_ready(db::community::list_community_ids().map(|v| v.len()).unwrap_or(0));

        // Outage resilience via the relay Monitor — event-driven, not polling.
        //
        // (1) Reconnect-driven catch-up: a `limit(0)` realtime sub never replays what was published
        // while we were down, so a relay (re)connecting is exactly when we must catch up: the
        // Communities refold, DMs reconcile (NIP-77 negentropy → only the diff), and the relay's
        // share of the planes is replayed from when it dropped. Idle when healthy. Stops on swap.
        if let Some(monitor) = client.monitor().filter(|_| catch_up == CatchUp::Inline) {
            let mut rx = monitor.subscribe();
            let pool = client.clone();
            db::spawn_bound(async move {
                // When each relay went down: on its return, it's replayed from there. One not up
                // by now has been down since listening began, as far as this listener knows.
                let mut down: std::collections::HashMap<String, u64> = std::collections::HashMap::new();
                for (url, relay) in pool.relays().await {
                    if relay.status() != RelayStatus::Connected {
                        down.insert(url.to_string(), live_from);
                    }
                }
                loop {
                    match rx.recv().await {
                        Ok(MonitorNotification::StatusChanged { relay_url, status }) => {
                            let url = relay_url.to_string();
                            match status {
                                RelayStatus::Disconnected | RelayStatus::Terminated => {
                                    down.entry(url).or_insert_with(crate::clock::now_ms);
                                }
                                // Everything since listening began is news, so what the outage held back is too.
                                RelayStatus::Connected => {
                                    if let Some(since) = down.remove(&url) {
                                        VectorCore::owe_catch_up(true, true, [(url, since)]);
                                    }
                                }
                                _ => {}
                            }
                        }
                        // Status changes went by unread: catch up on everything recent.
                        Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {
                            VectorCore::owe_catch_up(true, true, [(EVERY_RELAY.to_string(), crate::clock::now_ms().saturating_sub(30 * 60_000))]);
                        }
                        Err(tokio::sync::broadcast::error::RecvError::Closed) => break,
                    }
                }
            });
        }

        // (2) Health probe: a relay can report Connected while silently dead. Every 60s probe each
        // with a tiny query + timeout; a zombie is force-reconnected (which fires the monitor above
        // → catch-up), and Disconnected/Terminated relays are reconnected directly.
        {
            let client_health = client.clone();
            db::spawn_bound(async move {
                crate::rt::time::sleep(std::time::Duration::from_secs(30)).await; // warm-up
                // Bytes each relay had delivered when last checked: a relay that sent anything
                // since is serving, so it skips the probe.
                let heard = std::sync::Mutex::new(std::collections::HashMap::<RelayUrl, usize>::new());
                loop {
                    // A false "unhealthy" costs a full reconnect, so the probe follows the
                    // transport; probed concurrently so one slow relay can't stall the rest.
                    let budget = relay_request_timeout(std::time::Duration::from_secs(8));
                    let client_health = &client_health;
                    let heard = &heard;
                    futures_util::future::join_all(client_health.relays().await.into_iter().map(|(url, relay)| async move {
                        match relay.status() {
                            RelayStatus::Connected => {
                                let received = relay.stats().bytes_received();
                                let before = heard.lock().unwrap().insert(url.clone(), received);
                                if before.is_some_and(|b| received > b) {
                                    return;
                                }
                                // An id no event can have: the relay answers with a bare EOSE.
                                let probe = crate::rt::time::timeout(
                                    budget + std::time::Duration::from_secs(2),
                                    client_health
                                        .fetch_events(nostr_sdk::prelude::ReqTarget::single(
                                            url.to_string(),
                                            [Filter::new().id(EventId::from_byte_array([0; 32]))],
                                        ))
                                        .timeout(budget),
                                )
                                .await;
                                heard.lock().unwrap().insert(url.clone(), relay.stats().bytes_received());
                                if !matches!(probe, Ok(Ok(_))) {
                                    relay.disconnect();
                                    crate::rt::time::sleep(std::time::Duration::from_millis(500)).await;
                                    let _ = relay.try_connect().timeout(crate::relay_connect_timeout(std::time::Duration::from_secs(10))).await;
                                }
                            }
                            RelayStatus::Terminated | RelayStatus::Disconnected => {
                                let _ = relay.try_connect().timeout(crate::relay_connect_timeout(std::time::Duration::from_secs(10))).await;
                            }
                            _ => {}
                        }
                    })).await;
                    crate::rt::time::sleep(std::time::Duration::from_secs(60)).await;
                }
            });
        }

        let client_for_closure = client.clone();

        // The intake above ends when the client shuts down, which is what stops
        // this loop on `swap_session`.
        while let Some((route, event)) = live_rx.recv().await {
            match route {
                // DMs, files, reactions
                LiveRoute::Dm => {
                    let prepared = event_handler::prepare_event(*event, &client_for_closure, my_pk).await;
                    event_handler::commit_prepared_event(prepared, true, &*handler).await;
                }
                // Concord v2 plane events (authors-addressed kind-1059/21059).
                LiveRoute::CommunityV2 => community::v2::realtime::dispatch_event(*event, handler.clone()).await,
            }
        }

        news::end();
        Ok(())
    }

    /// Owe this session's listener a replay of every live plane from `since_ms` on.
    pub(crate) fn owe_live_replay(since_ms: u64) {
        Self::owe_catch_up(false, false, [(EVERY_RELAY.to_string(), since_ms)]);
    }

    /// Owe this session's listener a catch-up: `communities` re-reads every Community, `dms`
    /// reconciles DMs, and each relay (or [`EVERY_RELAY`]) is replayed from its own time. One
    /// runs at a time; what's owed meanwhile runs next, merged.
    pub(crate) fn owe_catch_up(communities: bool, dms: bool, relays: impl IntoIterator<Item = (String, u64)>) {
        if news::listening_since().is_none() {
            return;
        }
        let session = db::current_session_id();
        let start = {
            let mut owed = CATCH_UPS.lock().unwrap_or_else(|e| e.into_inner());
            if owed.session != session {
                *owed = Owed { session, ..Owed::default() };
            }
            owed.communities |= communities;
            owed.dms |= dms;
            for (relay, since) in relays {
                let at = owed.relays.entry(relay).or_insert(since);
                *at = (*at).min(since);
            }
            !std::mem::replace(&mut owed.running, true)
        };
        if start {
            db::spawn_bound(Self::run_catch_ups(session));
        }
    }

    async fn run_catch_ups(session: u64) {
        loop {
            // A burst of reconnects settles into one pass.
            crate::rt::time::sleep(std::time::Duration::from_secs(1)).await;
            let listener = news::listener().zip(news::cutoff());
            let owed = {
                let mut owed = CATCH_UPS.lock().unwrap_or_else(|e| e.into_inner());
                let nothing = !owed.communities && !owed.dms && owed.relays.is_empty();
                if owed.session != session || nothing || listener.is_none() {
                    owed.running = false;
                    return;
                }
                std::mem::replace(&mut *owed, Owed { session, running: true, ..Owed::default() })
            };
            let Some((handler, from)) = listener else { return };
            if owed.communities {
                let _ = VectorCore.sync_communities().await;
            }
            if owed.dms {
                let _ = VectorCore.sync_dms(None, &event_handler::LiveOnly::from(&*handler, from)).await;
            }
            if let Some(client) = state::nostr_client() {
                if owed.communities {
                    community::v2::realtime::refresh_subscription(&client).await;
                }
                for (relay, since) in owed.relays {
                    let since = since.saturating_sub(news::ALLOWANCE_MS).max(from);
                    let only = (relay != EVERY_RELAY).then_some(relay.as_str());
                    community::v2::realtime::replay(&client, nostr_sdk::prelude::Timestamp::from_secs(since / 1000), only, handler.clone()).await;
                }
            }
        }
    }

    /// Disconnect and clean up.
    pub async fn logout(&self) {
        news::end();
        if let Some(client) = state::nostr_client() {
            let _ = client.disconnect().await;
        }
        db::close_database();
    }

    /// Tear down the current session for an in-process account swap — the account-agnostic core of
    /// the app's `reset_session()`. Advances the session generation FIRST so any background task
    /// holding a `std::sync::Arc<crate::db::Session>` short-circuits before it can touch the next account's storage; shuts
    /// the client down (which ends any `listen()` notification loop bound to it, so the old account's
    /// events can't land in the new account's DB); closes the DB pool; and clears the key vaults plus
    /// all in-memory per-account state. Follow with `login()` to bind the next account, then re-attach
    /// `listen()`. (The app's `reset_session()` additionally clears Tauri-only caches it owns.)
    pub async fn swap_session(&self) {
        // FIRST — invalidate every captured guard before any teardown begins.
        state::clear_message_tombstones();
        news::end();

        // Mini App sessions end as the account that joined them, while its client
        // and key still exist to announce the departure.
        #[cfg(feature = "xdc")]
        crate::xdc::session::leave_all(std::time::Duration::from_secs(4)).await;
        // Voice calls too: each announces its departure while it still can.
        #[cfg(feature = "calls")]
        crate::calls::voice::leave().await;

        // Shut the client down before anything else: this detaches relay subscriptions and ends the
        // prior `listen()` loop, so it stops firing the old account's events into the new session.
        if let Some(client) = state::take_nostr_client() {
            let _ = client.shutdown().await;
        }
        db::close_database();

        // Key vaults + transient secrets.
        state::ENCRYPTION_KEY.clear(&[&state::MY_SECRET_KEY]);
        state::MY_SECRET_KEY.clear(&[&state::ENCRYPTION_KEY]);
        {
            use zeroize::Zeroize;
            if let Ok(mut g) = state::MNEMONIC_SEED.lock() {
                if let Some(s) = g.as_mut() { s.zeroize(); }
                *g = None;
            }
            if let Ok(mut g) = state::PENDING_NSEC.lock() {
                if let Some(s) = g.as_mut() { s.zeroize(); }
                *g = None;
            }
        }

        // Everything else the account owned — chats, profiles, wrapper ids,
        // parked events, row-id caches, the sync queue, the relay caches, the
        // theme tags, the active chat — went with the session `close_database`
        // released. Only teardown that DOES something beyond forgetting is left.

        // Unsubscribing is an action: these hold live relay subscriptions keyed
        // to the prior account's plane pseudonyms.
        crate::community::v2::realtime::clear().await;
        // So is disconnecting: the pooled clients are AUTHENTICATED as the prior
        // account's plane secret keys, and must not be left holding sockets.
        crate::community::transport::clear_plane_pool();
    }
}

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

    #[tokio::test]
    async fn what_a_listener_is_owed_merges_and_runs_once() {
        let _g = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
        *CATCH_UPS.lock().unwrap() = Owed::default();
        VectorCore::owe_catch_up(true, false, [("wss://a".to_string(), 100)]);
        assert!(!CATCH_UPS.lock().unwrap().running, "nobody listening: nothing owed");

        let _listening = news::listen_for_test(Arc::new(event_handler::NoOpEventHandler), crate::clock::now_ms());
        VectorCore::owe_catch_up(false, false, [("wss://a".to_string(), 100)]);
        VectorCore::owe_catch_up(false, true, [("wss://a".to_string(), 50), ("wss://b".to_string(), 70)]);
        let owed = CATCH_UPS.lock().unwrap();
        assert!(owed.running && owed.dms && !owed.communities);
        assert_eq!((owed.relays.get("wss://a"), owed.relays.get("wss://b")), (Some(&50), Some(&70)), "each relay from its earliest gap");
    }
}

/// Up to `limit` messages strictly before the `(at_ms, id)` cursor, chronological, from a
/// chat's held messages (sorted by `at` alone). Only the page is converted, never the chat:
/// the cursor's own same-`at` run filtered by id, then older rows back to `limit`, widened to
/// a whole same-`at` run at that edge since the id tiebreak decides inside it.
fn page_before(
    held: &[compact::CompactMessage],
    interner: &compact::NpubInterner,
    before: Option<(u64, &str)>,
    limit: usize,
) -> Vec<Message> {
    let (lo, mut msgs) = match before {
        None => (held.len(), Vec::new()),
        Some((at, id)) => {
            let lo = held.partition_point(|m| m.at < at);
            let hi = held.partition_point(|m| m.at <= at);
            let tie = held[lo..hi].iter().map(|m| m.to_message(interner)).filter(|m| m.id.as_str() < id).collect();
            (lo, tie)
        }
    };
    let mut start = lo.saturating_sub(limit.saturating_sub(msgs.len()));
    while start > 0 && start < lo && held[start - 1].at == held[start].at {
        start -= 1;
    }
    msgs.extend(held[start..lo].iter().map(|m| m.to_message(interner)));
    msgs.sort_by(|a, b| (a.at, a.id.as_str()).cmp(&(b.at, b.id.as_str())));
    if msgs.len() > limit {
        msgs.drain(..msgs.len() - limit);
    }
    msgs
}

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

    #[test]
    fn it_matches_converting_the_whole_chat() {
        let mut interner = compact::NpubInterner::new();
        let mut held = compact::CompactMessageVec::new();
        let mut seed: u64 = 7;
        for n in 0..400u64 {
            seed ^= seed << 13; seed ^= seed >> 7; seed ^= seed << 17;
            // Few distinct timestamps, so same-`at` runs are long and everywhere.
            let msg = Message { id: format!("{:064x}", seed), at: (n / 9) * 1000 + (seed % 3), ..Default::default() };
            held.insert(compact::CompactMessage::from_message(&msg, &mut interner));
        }
        let mut all: Vec<Message> = held.iter().map(|m| m.to_message(&interner)).collect();
        all.sort_by(|a, b| (a.at, a.id.as_str()).cmp(&(b.at, b.id.as_str())));
        let reference = |before: Option<(u64, &str)>, limit: usize| {
            let mut v: Vec<String> = all.iter()
                .filter(|m| before.is_none_or(|(at, id)| (m.at, m.id.as_str()) < (at, id)))
                .map(|m| m.id.clone())
                .collect();
            if v.len() > limit { v.drain(..v.len() - limit); }
            v
        };
        let ids = |v: Vec<Message>| v.into_iter().map(|m| m.id).collect::<Vec<_>>();
        for limit in [1, 3, 10, 50, 1000] {
            assert_eq!(ids(page_before(held.messages(), &interner, None, limit)), reference(None, limit));
            for c in all.iter().step_by(13) {
                for cursor in [(c.at, c.id.as_str()), (c.at, "0"), (c.at, "g"), (c.at + 1, "0")] {
                    assert_eq!(ids(page_before(held.messages(), &interner, Some(cursor), limit)), reference(Some(cursor), limit), "cursor {cursor:?} limit {limit}");
                }
            }
        }
    }
}

#[cfg(all(test, feature = "tor", not(target_arch = "wasm32")))]
mod transport_policy_tests {
    use std::time::Duration;

    use crate::transport::{egress, Egress, Kind, Lane};

    fn live() -> u64 {
        crate::db::live_session_id()
    }

    /// ONE test covering proxy + budgets: the preference lives on the live session, shared by
    /// every test, so it holds the database guard and restores Clearnet.
    #[test]
    fn tor_transport_policy() {
        let _serial = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
        let short = Duration::from_secs(5);
        let long = Duration::from_secs(300);

        // Tor off: connections may go direct, and every caller's clearnet budget
        // passes through untouched so the common path is never slowed down.
        crate::transport::set_preference(Some(Kind::Clearnet));
        crate::tor::set_tor_enabled_pref(false);
        assert_eq!(egress(live(), Lane::Account, "relay.example.com", 443), Egress::Direct);
        assert_eq!(super::relay_connect_timeout(short), short);
        assert_eq!(super::relay_request_timeout(short), short);

        // `RequiredButInactive` (Tor chosen, not up yet) must raise the floor just like
        // `Active`: that window is when connects are slowest.
        crate::tor::set_tor_enabled_pref(true);
        assert!(matches!(
            crate::tor::transport_state(),
            crate::tor::TorTransportState::RequiredButInactive
        ));
        // THE leak invariant: while Tor is the chosen transport nothing is direct, least of
        // all during bootstrap, which is exactly when a naive implementation falls through.
        assert!(
            matches!(egress(live(), Lane::Account, "relay.example.com", 443), Egress::Refuse(_)),
            "Tor enabled but inactive must never connect direct"
        );
        assert_eq!(super::relay_connect_timeout(short), Duration::from_secs(60));
        assert_eq!(super::relay_request_timeout(short), Duration::from_secs(30));

        // Tor chosen on the welcome screen: an account whose own preference is off still opens
        // on Tor until it commits, so a staged sign-in can never connect direct.
        crate::tor::set_tor_enabled_pref(false);
        crate::tor::arm_prelogin_carry(true);
        assert!(crate::tor::effective_tor_pref(false), "an armed carry raises an off preference");
        crate::tor::set_tor_enabled_pref(crate::tor::effective_tor_pref(false));
        assert!(
            matches!(egress(live(), Lane::Account, "relay.example.com", 443), Egress::Refuse(_)),
            "an armed carry must refuse until Tor is up, never connect direct"
        );
        crate::tor::arm_prelogin_carry(false);
        assert!(!crate::tor::effective_tor_pref(false), "a disarmed carry leaves the preference alone");
        assert!(crate::tor::effective_tor_pref(true));

        // The NIP-46 client the SDK builds for a remote signer gets the same policy.
        let opts = super::transport_relay_options();
        assert!(format!("{opts:?}").contains("proxy: Some"), "remote-signer relays must carry the transport");

        // The floor only ever raises. A caller asking for longer than the floor has
        // a reason to, and shortening it would abort operations that used to finish.
        for tor in [true, false] {
            crate::tor::set_tor_enabled_pref(tor);
            assert_eq!(super::relay_connect_timeout(long), long, "connect, tor={tor}");
            assert_eq!(super::relay_request_timeout(long), long, "request, tor={tor}");
        }
        crate::transport::set_preference(Some(Kind::Clearnet));
    }
}

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

    /// SSRF regression: `download_attachment` must reject a private/link-local URL via
    /// `validate_url_not_private` BEFORE any network fetch (the URL is attacker-controlled).
    #[tokio::test]
    async fn download_attachment_rejects_private_url() {
        let att = crate::types::Attachment {
            url: "http://169.254.169.254/latest/meta-data/".to_string(),
            ..Default::default()
        };
        match VectorCore.download_attachment(&att).await {
            Err(VectorError::Other(msg)) => {
                assert!(msg.contains("Private/internal"), "expected SSRF rejection, got: {msg}")
            }
            other => panic!("expected SSRF rejection, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn download_attachment_rejects_empty_url() {
        let att = crate::types::Attachment::default();
        assert!(VectorCore.download_attachment(&att).await.is_err());
    }

    /// A community surfaces in `list_communities` with `version: 2`, and
    /// `v2_community_for_channel` routes its channels to the send path.
    #[tokio::test]
    async fn list_communities_and_channel_routing_are_protocol_aware() {
        use crate::community::transport::memory::MemoryRelay;
        use nostr_sdk::prelude::Keys;

        let _guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
        crate::db::close_database();
        crate::db::clear_id_caches();
        let tmp = tempfile::tempdir().unwrap();
        // A valid bech32-charset, npub-length account dir name.
        let acct = {
            const B: &[u8] = b"qpzry9x8gf2tvdw0s3jn54khce6mua7l";
            let mut s = String::from("npub1");
            for i in 0..58 {
                s.push(B[(i * 7 + 3) % 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 directly through the v2 service (offline).
        let relay = MemoryRelay::new();
        let community = crate::community::v2::service::create_community(&relay, "V2 Guild", vec!["wss://r".into()], None)
            .await
            .unwrap();
        let channel_hex = crate::simd::hex::bytes_to_hex_32(&community.channels[0].id.0);

        // The facade lists it as version 2, owned by me.
        let listed = VectorCore.list_communities().await;
        let v2 = listed.iter().find(|c| c["version"] == 2).expect("the v2 community is listed");
        assert_eq!(v2["name"], "V2 Guild");
        assert_eq!(v2["is_owner"], true);
        assert_eq!(v2["channels"][0]["channel_id"], channel_hex);

        // The channel routes to the v2 send path.
        assert_eq!(
            VectorCore.v2_community_for_channel(&channel_hex).unwrap(),
            Some(community.identity.community_id),
            "a v2 channel is routed to v2"
        );
        // An unknown channel routes nowhere.
        assert_eq!(VectorCore.v2_community_for_channel(&"00".repeat(32)).unwrap(), None);
    }

    /// The facade builds an invite URL by trimming `/invite` off the base constant
    /// (`build_invite_url` re-appends its own `/invite/<naddr>`).
    /// Lock that the derived URL is v2-shaped and round-trips through the v2
    /// parser — a stale constant or a double-`/invite` would silently break joins.
    #[test]
    fn v2_invite_url_base_derivation_round_trips() {
        use crate::community::v2::derive::TOKEN_LEN;
        use crate::community::v2::invite::{build_invite_url, parse_invite_link};
        use nostr_sdk::prelude::Keys;
        let base = crate::community::v2::invite::INVITE_URL_BASE.trim_end_matches("/invite");
        assert!(!base.ends_with("/invite"), "the bare domain must not carry /invite");
        let signer = Keys::generate();
        let token = [0x07u8; TOKEN_LEN];
        let url = build_invite_url(base, &signer.public_key(), &token, &[]).unwrap();
        assert!(url.contains("/invite/"), "a v2 URL carries the naddr path");
        assert!(!url.contains("/invite/invite/"), "no doubled /invite from the base");
        let parsed = parse_invite_link(&url).unwrap();
        assert_eq!(parsed.link_signer, signer.public_key());
        assert_eq!(parsed.token, token);
    }
}

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

    fn msg(at: u64, id_byte: u8, content: &str) -> Message {
        Message {
            id: format!("{:02x}", id_byte).repeat(32),
            content: content.to_string(),
            at,
            ..Default::default()
        }
    }

    /// The cursor is compared by VALUE: paging must step strictly through a
    /// same-millisecond wall (the id tiebreak) and must survive the cursored
    /// message being deleted — a persisted cursor must never wedge the walk.
    #[tokio::test]
    async fn history_pages_through_a_same_ms_wall_and_a_deleted_cursor() {
        let chat_id = "test-history-paging-wall";
        {
            let mut st = state::STATE.lock().await;
            st.ensure_community_chat(chat_id);
            // A wall of three messages in the SAME millisecond, plus one older.
            for m in [msg(500, 0x01, "old"), msg(900, 0xaa, "wall-a"), msg(900, 0xbb, "wall-b"), msg(900, 0xcc, "wall-c")] {
                st.add_message_to_chat(chat_id, &m);
            }
        }
        let core = VectorCore;

        // Newest 2 — the tail of the wall, chronological.
        let newest = core.get_messages_before(chat_id, None, 2).await;
        assert_eq!(newest.iter().map(|m| m.content.as_str()).collect::<Vec<_>>(), ["wall-b", "wall-c"]);

        // Page strictly before wall-b: its same-ms predecessor, then the older one.
        let cursor = (newest[0].at, newest[0].id.as_str().to_string());
        let page = core.get_messages_before(chat_id, Some((cursor.0, &cursor.1)), 10).await;
        assert_eq!(page.iter().map(|m| m.content.as_str()).collect::<Vec<_>>(), ["old", "wall-a"]);

        // The cursored message vanishes (delete / self-destruct): the SAME cursor
        // still resolves to the same page, because nothing resolves it to a row.
        {
            let mut st = state::STATE.lock().await;
            let chat = st.get_chat_mut(chat_id).unwrap();
            chat.messages.remove_by_hex_id(&cursor.1);
        }
        let page = core.get_messages_before(chat_id, Some((cursor.0, &cursor.1)), 10).await;
        assert_eq!(
            page.iter().map(|m| m.content.as_str()).collect::<Vec<_>>(),
            ["old", "wall-a"],
            "a deleted cursor pages identically"
        );

        // Unknown chat: empty, not an error.
        assert!(core.get_messages_before("test-history-paging-nochat", None, 5).await.is_empty());
    }
}

#[cfg(test)]
mod moderation_cache_audit {
    /// Every moderation action changes who is a member, and the console's verdict is
    /// memoised for 90s. An action that does not drop the memo leaves the console
    /// listing people it just removed and flagging a raid that is already over —
    /// which is exactly what shipped: `invalidate_raid_report` existed with no
    /// caller at all. Parsed from source, so a new action cannot quietly skip it.
    #[test]
    fn every_moderation_action_drops_the_memoised_verdict() {
        let src = include_str!("lib.rs");
        for name in [
            "pub async fn refound_community",
            "pub async fn kick_community_members",
            "pub async fn set_members_banned",
            "pub async fn contain_raid",
        ] {
            let start = src.find(name).unwrap_or_else(|| panic!("{name} not found — rename?"));
            // The body ends where the next item at method indentation begins.
            let rest = &src[start + name.len()..];
            let end = rest.find("\n    pub ").unwrap_or(rest.len());
            assert!(
                rest[..end].contains("invalidate_raid_report"),
                "{name} mutates membership but never drops the memoised console verdict"
            );
        }
    }

    /// A ban by ANOTHER admin reaches this device as an adopted fold, not a local
    /// call — and with a moderation bot doing the work, that is the ONLY way it ever
    /// arrives. The three stores the console reports from must drop the memo on
    /// write, or the human admin watches a raid that was handled 90 seconds ago.
    #[test]
    fn an_adopted_change_drops_the_verdict_too() {
        let src = include_str!("db/community.rs");
        for name in ["pub fn set_community_banlist", "pub fn set_community_roles", "pub fn set_guestbook"] {
            let start = src.find(name).unwrap_or_else(|| panic!("{name} not found — rename?"));
            let rest = &src[start + name.len()..];
            let end = rest.find("\npub fn ").unwrap_or(rest.len());
            assert!(
                rest[..end].contains("forget_console_verdict"),
                "{name} changes who the console reports on but leaves the memo standing"
            );
        }
    }
}