vector-core 0.13.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
//! v2 inbound bridge — turns opened v2 events into the protocol-agnostic
//! [`InboundEventHandler`] callbacks the rest of Vector (and the SDK's
//! `on_message`) already consumes, so a bot receives community messages through
//! the same seam as DMs.
//!
//! Dispatch is by which plane a kind-1059 wrap opens under. A received wrap is
//! tried against each held channel's Chat-Plane key (author match, no trial
//! decrypt), then the Guestbook plane; a control-plane fold is a heavier
//! separate path (metadata/roster), handled by the service refresh, not here.

use nostr_sdk::prelude::PublicKey;
use nostr_sdk::prelude::ToBech32;

use super::super::attachments::attachments_from_tags;
use super::chat::{self, ChatEvent};
use super::community::CommunityV2;
use super::guestbook::{self, GuestbookEntry};
use super::stream;
use crate::event_handler::InboundEventHandler;
use crate::state::ChatState;
use crate::types::{EmojiTag, Message, Reaction};

/// Build a protocol-agnostic [`Message`] from an opened v2 chat Message event.
/// Every field a renderer reads (id = the rumor id, ms time, `mine`, npub, imeta
/// attachments, NIP-30 emoji, the reply reference), so the frontend/SDK renderers
/// treat a community message identically to a DM one.
pub fn chat_message_to_message(
    opened: &stream::OpenedStream,
    reply_to: &Option<chat::ReplyRef>,
    emoji: &[(String, String)],
    my_pubkey: &PublicKey,
) -> Message {
    let (replied_to, replied_to_npub) = match reply_to {
        Some(r) => (
            crate::simd::hex::bytes_to_hex_32(&r.id),
            r.author.and_then(|a| a.to_bech32().ok()),
        ),
        None => (String::new(), None),
    };
    let attachments = attachments_from_tags(opened.rumor.tags.iter(), &crate::db::get_download_dir());
    // Drop any blob URL a foreign client (e.g. Armada) also inlined into the caption.
    let content = super::super::attachments::strip_attachment_urls(&opened.rumor.content, &attachments);
    // Spans count chars of the content as sent; a stripped link would shift them.
    let text_spans = if content == opened.rumor.content {
        crate::text_spans::from_tags(opened.rumor.tags.iter(), &content)
    } else {
        Vec::new()
    };
    Message {
        id: opened.rumor_id.to_hex(),
        content,
        text_spans,
        replied_to,
        replied_to_npub,
        at: opened.at_ms,
        mine: opened.author == *my_pubkey,
        npub: opened.author.to_bech32().ok(),
        attachments,
        emoji_tags: emoji
            .iter()
            .map(|(shortcode, url)| EmojiTag { shortcode: shortcode.clone(), url: url.clone() })
            .collect(),
        addressed_bots: crate::bot_interface::addressed_bots(opened.rumor.tags.iter()),
        role_mentions: crate::community::mentions::from_tags(opened.rumor.tags.iter()),
        // Only a writer address opens a rumor carrying a writer epoch.
        writer: chat::carries_writer_epoch(&opened.rumor),
        unauthorized: opened.held,
        wrapper_event_id: Some(opened.wrapper_id.to_hex()),
        // Self-Destruct Timer: the sender's NIP-40 expiry drives our local purge.
        expiration: chat::message_expiration(&opened.rumor),
        ..Default::default()
    }
}

/// Whether `author` sits on the banlist of the community owning `channel_id`
/// (fail-open on a lookup error: availability must never hide honest traffic —
/// the ban re-applies on the next fold). `community` is the owner when the
/// caller already routed the wrap to it.
fn author_is_banned_here(channel_id: &str, community: Option<&[u8; 32]>, author: &PublicKey) -> bool {
    let resolved;
    let community = match community {
        Some(c) => c,
        None => {
            let Some(Ok(Some(c))) =
                crate::community::id32_from_hex(channel_id).map(|ch| crate::db::community::community_for_channel(&ch))
            else {
                return false;
            };
            resolved = c;
            &resolved
        }
    };
    crate::db::community::is_author_banned_in(community, author)
}

/// May `deleter` remove a message authored by `author` in this channel? The
/// deleter needs `MANAGE_MESSAGES`, a strict outrank, and a synced citation.
/// Blocked once dissolved: a dead community honors no new authority action, only
/// the self-deletes its seal deliberately leaves open (CORD-02 §9).
struct EarlyDeletes;

/// How many targets' early deletes a session remembers; the oldest make way.
const EARLY_DELETES_KEPT: usize = 2048;

/// Deletes that arrived ahead of the message they name: who asked, and what they cited.
#[derive(Default)]
struct EarlyDeleteSet {
    by_target: std::collections::HashMap<[u8; 32], Vec<(PublicKey, nostr_sdk::prelude::Tags)>>,
    order: std::collections::VecDeque<[u8; 32]>,
}

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

/// Keep a delete whose message isn't here yet (a take-back racing the resend it cancels, a
/// newer page read before an older one). Only the message's author settles who may delete
/// it, so the judgment waits for the message.
fn park_early_delete(target: &[u8; 32], by: PublicKey, tags: &nostr_sdk::prelude::Tags) {
    let kept = early_deletes();
    let Ok(mut set) = kept.lock() else { return };
    if !set.by_target.contains_key(target) {
        if set.order.len() >= EARLY_DELETES_KEPT {
            if let Some(oldest) = set.order.pop_front() {
                set.by_target.remove(&oldest);
            }
        }
        set.order.push_back(*target);
    }
    let asked = set.by_target.entry(*target).or_default();
    if !asked.iter().any(|(pk, _)| *pk == by) {
        asked.push((by, tags.clone()));
    }
}

/// Whether a delete that came ahead of `target` stands now that its author is known, and
/// whether it was a moderator's. Asked once: the entry goes either way.
fn early_delete_of(channel_id: &str, target: &[u8; 32], author: &PublicKey) -> Option<bool> {
    let asked = {
        let kept = early_deletes();
        let mut set = kept.lock().ok()?;
        let asked = set.by_target.remove(target)?;
        set.order.retain(|t| t != target);
        asked
    };
    if asked.iter().any(|(by, _)| by == author) {
        return Some(false);
    }
    asked.iter().any(|(by, tags)| moderation_delete_authorized(channel_id, by, author, tags)).then_some(true)
}

fn moderation_delete_authorized(
    channel_id: &str,
    deleter: &PublicKey,
    author: &PublicKey,
    tags: &nostr_sdk::prelude::Tags,
) -> bool {
    let Ok(Some(cid_hex)) = crate::db::community::community_id_for_channel(channel_id) else {
        return false;
    };
    if crate::db::community::get_community_dissolved(&cid_hex).unwrap_or(false) {
        return false;
    }
    let Some(owner_hex) = crate::community::moderation::owner_hex(&cid_hex) else {
        return false; // no provable owner → no provable authority chain
    };
    let deleter_hex = deleter.to_hex();
    let citation = crate::community::edition::AuthorityCitation::from_tags(tags);
    if !super::service::citation_is_synced(&cid_hex, &owner_hex, &deleter_hex, citation.as_ref()) {
        return false;
    }
    let roster = crate::db::community::get_community_roles(&cid_hex).unwrap_or_default();
    let private = crate::db::community::channel_is_private(channel_id).ok().flatten().unwrap_or(false);
    crate::community::moderation::can_hide_in_channel(Some(&owner_hex), &roster, &deleter_hex, &author.to_hex(), channel_id, private)
}

/// Note a moderator's delete for the Audit Log, written once the STATE lock is behind us.
fn note_moderation_delete(channel_id: &str, opened: &stream::OpenedStream, author: &PublicKey) {
    let Some(id) = opened.rumor.id.map(|i| i.to_hex()) else { return };
    let (channel, actor, author, at_ms) = (channel_id.to_string(), opened.author.to_hex(), author.to_hex(), opened.at_ms);
    crate::db::spawn_bound(async move {
        if let Ok(Some(cid)) = crate::db::community::community_id_for_channel(&channel) {
            super::service::note_moderation_delete(&cid, &id, at_ms, &actor, &author, &channel);
        }
    });
}

/// What applying a v2 chat event to STATE yielded — the caller persists it (async)
/// once the STATE lock is dropped. A message row is saved fresh or re-saved (a landed
/// reaction rides the row), a delete drops it. Persistence is the caller's so the apply
/// step stays sync + lock-scoped.
pub enum ChatPersist {
    /// A brand-new message — save its row.
    New(Message),
    /// A message changed: a reaction landed (`edit_event` None → store its kind-7 row) or an
    /// edit applied (`edit_event` Some → save the folded MESSAGE_EDIT event, event-sourced
    /// like DMs). Neither rewrites the message's own row.
    Updated { message: Message, edit_event: Option<Box<crate::stored_event::StoredEvent>> },
    /// A message removed by its author, or by a moderator when `moderated` — drop its row.
    Removed { id: String, moderated: bool },
    /// A reaction revoked by its reactor — drop the kind-7 row (save is
    /// additive; a lingering row would resurrect the chip on the next load).
    ReactionRemoved { reaction_id: String, message: Message },
}

/// Apply an opened v2 [`ChatEvent`] to STATE (dedup + aggregate onto the SHARED
/// [`ChatState`]). Sync: the DB dedup read + STATE mutation run under the caller's lock;
/// the caller then does the async DB persist on the returned [`ChatPersist`] (see
/// [`persist_chat`]). Returns `None` for a duplicate, an already-expired rumor, a
/// non-persisted kind (typing/webxdc), or an aggregate whose target isn't resident in
/// this channel.
pub fn apply_chat_to_state(state: &mut ChatState, event: &ChatEvent, channel_id: &str, my_pubkey: &PublicKey) -> Option<ChatPersist> {
    apply_chat_to_state_in(state, event, channel_id, None, my_pubkey, None)
}

/// [`apply_chat_to_state`] for one event of a page whose stored ids `stored` were read in one go
/// ([`crate::db::events::existing_event_ids`]) rather than one query each.
pub(crate) fn apply_page_event_to_state(state: &mut ChatState, event: &ChatEvent, channel_id: &str, my_pubkey: &PublicKey, stored: &std::collections::HashSet<String>) -> Option<ChatPersist> {
    apply_chat_to_state_in(state, event, channel_id, None, my_pubkey, Some(stored))
}

/// The ids of a page's events that [`apply_chat_to_state`] asks the store about.
pub(crate) fn page_event_ids<'a>(events: impl IntoIterator<Item = &'a ChatEvent>) -> Vec<String> {
    events
        .into_iter()
        .filter(|e| matches!(e, ChatEvent::Message { .. } | ChatEvent::Edit { .. }))
        .map(|e| e.opened().rumor_id.to_hex())
        .collect()
}

/// [`apply_chat_to_state`], given the owning community when the caller already knows it.
fn apply_chat_to_state_in(
    state: &mut ChatState,
    event: &ChatEvent,
    channel_id: &str,
    community: Option<&[u8; 32]>,
    my_pubkey: &PublicKey,
    stored: Option<&std::collections::HashSet<String>>,
) -> Option<ChatPersist> {
    let is_stored = |id: &str| match stored {
        Some(ids) => ids.contains(id),
        None => crate::db::events::event_exists(id).unwrap_or(false),
    };
    // CORD-04 §4: a banned npub VANISHES — every chat event they author (message,
    // reaction, edit, delete) is dropped at fold time. Severance (the rekey) only
    // cuts their READ of new epochs; they still hold old epoch keys and can post
    // to old planes forever — refusing to fold them is what makes the ban hold.
    // The persisted banlist can never name the owner (the authority fold refuses
    // a ban whose target is position 0), so no owner exemption is needed here.
    if author_is_banned_here(channel_id, community, &event.opened().author) {
        return None;
    }
    // CORD-08 §3: the rumor's own NIP-40 expiry governs, the wrap's copy is relay hygiene.
    // Never a delete: refusing an expired tombstone would bring back what it erased.
    if !matches!(event, ChatEvent::Delete { .. })
        && crate::rumor::already_expired(chat::message_expiration(&event.opened().rumor))
    {
        return None;
    }
    match event {
        ChatEvent::Message { opened, reply_to, emoji } => {
            let msg = chat_message_to_message(opened, reply_to, emoji, my_pubkey);
            // Our own failed message, read back from a relay, landed after all.
            if let Some(moderated) = early_delete_of(channel_id, opened.rumor_id.as_bytes(), &opened.author) {
                let _ = state.remove_message(&msg.id);
                return Some(ChatPersist::Removed { id: msg.id, moderated });
            }
            if msg.mine && state.find_message(&msg.id).is_some_and(|(_, m)| m.failed) {
                super::service::confirm_in(state, &msg.id);
            }
            // DB dedup: a known inner id is already stored — don't re-ingest/re-emit (a
            // catch-up sweep re-fetches the whole page; in-memory STATE holds only a window).
            // A deleted one has no row left to find, so its tombstone answers instead.
            if is_stored(&msg.id) || crate::state::was_message_deleted(&msg.id) {
                return None;
            }
            state.ensure_community_chat(channel_id);
            // Persist regardless of the STATE-add result: `event_exists` already proved
            // it's not in the DB, so a `false` here means only that another writer put it
            // in STATE first — the row must still be saved, or it's lost until re-fetch.
            // A page's stored ids were read before the page began, so that writer may have
            // saved it since: ask the store again.
            if !state.add_message_to_chat(channel_id, &msg) && stored.is_some() && crate::db::events::event_exists(&msg.id).unwrap_or(false) {
                return None;
            }
            Some(ChatPersist::New(msg))
        }
        ChatEvent::Reaction { opened, target, emoji, emoji_url, .. } => {
            if !crate::types::is_renderable_reaction(emoji) {
                return None;
            }
            let target_id = crate::simd::hex::bytes_to_hex_32(target);
            // Cross-channel guard: a reaction lands only on a target resident in the SAME
            // channel it was sealed under (its binding authenticates its own channel, never
            // the target's) — else a member could inject reactions across channels.
            if !matches!(state.find_message(&target_id), Some((chat, _)) if chat.id == channel_id) {
                return None;
            }
            let reaction = Reaction {
                id: opened.rumor_id.to_hex(),
                reference_id: target_id.clone(),
                // npub, not hex: the frontend's whole reaction contract (profile
                // name resolve + the own-reaction highlight vs strPubkey) keys on
                // bech32.
                author_id: opened.author.to_bech32().unwrap_or_else(|_| opened.author.to_hex()),
                emoji: emoji.clone(),
                emoji_url: emoji_url.clone(),
            };
            let (_c, added) = state.add_reaction_to_message(&target_id, reaction)?;
            added.then(|| state.find_message(&target_id).map(|(_c, m)| ChatPersist::Updated { message: m, edit_event: None }))?
        }
        ChatEvent::Edit { opened, target, new_content, emoji } => {
            // Dedup by the edit's own rumor id (its MESSAGE_EDIT row below): the
            // in-message `apply_edit` dedups silently, so without this a re-wrapped
            // duplicate would still return Updated and re-fire the handler — the
            // replay hole the persist-gated callbacks exist to close.
            if is_stored(&opened.rumor_id.to_hex()) {
                return None;
            }
            let target_id = crate::simd::hex::bytes_to_hex_32(target);
            // Author-scoped + same-channel: only the original author edits their own message.
            let editor_npub = opened.author.to_bech32().ok()?;
            if !matches!(state.find_message(&target_id), Some((chat, m)) if chat.id == channel_id && m.npub.as_deref() == Some(editor_npub.as_str())) {
                return None;
            }
            // Apply to STATE via the shared canonical applier (seeds history with the
            // original once, dedups by `edited_at`, swaps content), shared with DMs.
            // The edit's emoji pairs ride along: apply_edit adopts the LATEST edit's
            // set, so peers render the replacement text from the replacement's tags.
            let edited_at = opened.at_ms;
            let emoji_tags: Vec<crate::types::EmojiTag> = emoji
                .iter()
                .map(|(shortcode, url)| crate::types::EmojiTag { shortcode: shortcode.clone(), url: url.clone() })
                .collect();
            let text_spans = crate::text_spans::from_tags(opened.rumor.tags.iter(), new_content);
            let (_c, message) = state.update_message_with(&target_id, |m, i| m.apply_edit(new_content.clone(), edited_at, emoji_tags.clone(), text_spans.clone(), i))?;
            // Persist as a folded MESSAGE_EDIT event (chat_id set at save time), emoji
            // tags included, or the reload fold re-strips what the live fold kept.
            let edit_event = crate::stored_event::StoredEventBuilder::new()
                .id(opened.rumor_id.to_hex())
                .kind(crate::stored_event::event_kind::MESSAGE_EDIT)
                .content(new_content.clone())
                .tags(
                    emoji.iter().map(|(s, u)| vec!["emoji".to_string(), s.clone(), u.clone()])
                        .chain(text_spans.iter().map(|s| s.to_tag_parts()))
                        // To the millisecond: what a later stop or restrict judges it by.
                        .chain((edited_at % 1000 > 0).then(|| vec!["ms".to_string(), (edited_at % 1000).to_string()]))
                        // A writer-address edit is no sign of presence, as its post isn't.
                        .chain(super::chat::carries_writer_epoch(&opened.rumor).then(|| vec!["writer".to_string()]))
                        .collect(),
                )
                .reference_id(Some(target_id.clone()))
                .wrapper_event_id(Some(opened.wrapper_id.to_hex()))
                .created_at(edited_at / 1000)
                .mine(opened.author == *my_pubkey)
                .npub(opened.author.to_bech32().ok())
                .build();
            Some(ChatPersist::Updated { message, edit_event: Some(Box::new(edit_event)) })
        }
        ChatEvent::Delete { opened, target, .. } => {
            let target_id = crate::simd::hex::bytes_to_hex_32(target);
            // A delete may target a REACTION (an un-react) rather than a message.
            // Reactions are author-revocable only: the deleter must be the
            // reactor. Checked before the message path so a reaction id never
            // falls through to message-removal logic.
            if let Some((_chat, message_id, author_npub, _)) = state.find_reaction(&target_id) {
                let reactor_ok = PublicKey::parse(&author_npub).map(|pk| pk == opened.author).unwrap_or(false);
                if !reactor_ok {
                    return None;
                }
                return state
                    .remove_reaction_from_message(&message_id, &target_id)
                    .map(|(_cid, message)| ChatPersist::ReactionRemoved { reaction_id: target_id, message });
            }
            // A delete removes its author's OWN message, or someone else's under
            // MANAGE_MESSAGES. Resolve the target's author from the resident copy, then
            // the DB for a paged-out row — residency is a cache detail, and authorizing
            // only what's in the window would let a moderator's hide of an older message
            // land on some peers and not others.
            let resident = state.find_message(&target_id).and_then(|(_, m)| m.npub.clone());
            let author_npub = match resident {
                Some(n) => Some(n),
                None => crate::db::events::event_author(&target_id).ok().flatten(),
            };
            let Some(author) = author_npub.as_deref().and_then(|n| PublicKey::parse(n).ok()) else {
                if !crate::state::was_message_deleted(&target_id) {
                    park_early_delete(target, opened.author, &opened.rumor.tags);
                }
                return None;
            };
            let authorized = author == opened.author
                || moderation_delete_authorized(channel_id, &opened.author, &author, &opened.rumor.tags);
            if !authorized {
                return None;
            }
            if author != opened.author {
                note_moderation_delete(channel_id, opened, &author);
            }
            // A paged-out target isn't in STATE to remove; the caller's persist step
            // drops the stored row either way.
            let _ = state.remove_message(&target_id);
            Some(ChatPersist::Removed { id: target_id, moderated: author != opened.author })
        }
        ChatEvent::Typing { .. } | ChatEvent::Webxdc { .. } | ChatEvent::VoicePresence { .. } | ChatEvent::VoiceDirective { .. } => None,
    }
}

/// Bring the message a reaction, edit or un-react aims at into STATE from the database when
/// it isn't resident: STATE holds a window, and the aggregate must land on older rows too.
pub async fn hydrate_target(event: &ChatEvent, channel_id: &str) {
    let msg_id = match event {
        ChatEvent::Reaction { target, .. } | ChatEvent::Edit { target, .. } => crate::simd::hex::bytes_to_hex_32(target),
        ChatEvent::Delete { target, .. } => {
            let id = crate::simd::hex::bytes_to_hex_32(target);
            if crate::state::STATE.lock().await.find_reaction(&id).is_some() {
                return;
            }
            match crate::db::events::reaction_target(&id) {
                Ok(Some(parent)) => parent,
                _ => return,
            }
        }
        _ => return,
    };
    if crate::state::STATE.lock().await.find_message(&msg_id).is_some() {
        return;
    }
    if let Ok(Some((chat, msg))) = crate::db::events::get_message_by_id(&msg_id).await {
        if chat == channel_id {
            crate::state::STATE.lock().await.add_message_to_chat(channel_id, &msg);
        }
    }
}

/// Whether `event` targets a message (or, for a delete, a reaction) not held yet: applying it
/// waits for the target, so its wrap must stay retryable. Run after [`persist_chat_event`],
/// whose hydration has already loaded any stored target.
pub async fn awaits_target(event: &ChatEvent) -> bool {
    let target = match event {
        ChatEvent::Reaction { target, .. } | ChatEvent::Edit { target, .. } | ChatEvent::Delete { target, .. } => {
            crate::simd::hex::bytes_to_hex_32(target)
        }
        _ => return false,
    };
    let st = crate::state::STATE.lock().await;
    st.find_message(&target).is_none() && st.find_reaction(&target).is_none()
}

/// Apply an already-opened chat event to STATE + the shared store — the LIVE
/// counterpart of `VectorCore::v2_backfill_channel`'s catch-up persistence.
/// The dispatcher opened the wrap (so nothing decrypts twice); the returned outcome
/// is what the caller's callbacks fire from — a duplicate, a non-resident target,
/// or a forged edit/delete yields `None` and nothing re-fires.
pub async fn persist_chat_event(
    event: &ChatEvent,
    channel_id: &str,
    my_pubkey: &PublicKey,
) -> Option<ChatPersist> {
    persist_chat_event_in(event, channel_id, None, my_pubkey).await
}

/// [`persist_chat_event`] for a wrap the dispatcher already routed to `community`.
pub(crate) async fn persist_routed_chat_event(
    event: &ChatEvent,
    channel_id: &str,
    community: &[u8; 32],
    my_pubkey: &PublicKey,
) -> Option<ChatPersist> {
    persist_chat_event_in(event, channel_id, Some(community), my_pubkey).await
}

async fn persist_chat_event_in(
    event: &ChatEvent,
    channel_id: &str,
    community: Option<&[u8; 32]>,
    my_pubkey: &PublicKey,
) -> Option<ChatPersist> {
    hydrate_target(event, channel_id).await;
    let outcome = {
        let mut st = crate::state::STATE.lock().await;
        apply_chat_to_state_in(&mut st, event, channel_id, community, my_pubkey, None)
    }?;
    // Resolve a reply's preview (content/npub) from the DB before persist + emit:
    // the parent is often persisted but outside the in-memory window,
    // and without this the live render shows a reply with no context.
    let outcome = match outcome {
        ChatPersist::New(mut m) => {
            if !m.replied_to.is_empty() {
                let _ = crate::db::events::populate_reply_context(&mut m).await;
            }
            // Bytes we already hold verify at ARRIVAL, mirroring the DM ingest:
            // before the persist below, so the row lands downloaded; the hint
            // patches the STATE copy apply_chat_to_state already inserted.
            crate::db::attachments::verify_message_attachments(&mut m, Some(channel_id)).await;
            ChatPersist::New(m)
        }
        o => o,
    };
    // …and only persist to THIS account's DB (the save straddles an await).
    persist_chat(channel_id, &outcome).await;
    // §7 pin duties: a deleted pinned message wants the omitting edition, an
    // edited one a refreshed proof bundle. Fired only from a PERSISTED outcome
    // (the dedup/authorization gates above already passed); non-curators no-op.
    match (&outcome, event) {
        (ChatPersist::Removed { id: target, .. }, _) => {
            super::service::spawn_pin_duty(channel_id, target, None);
        }
        (ChatPersist::Updated { .. }, ChatEvent::Edit { opened, target, .. }) => {
            let target_hex = crate::simd::hex::bytes_to_hex_32(target);
            super::service::spawn_pin_duty(channel_id, &target_hex, Some(opened.clone()));
        }
        _ => {}
    }
    Some(outcome)
}

/// Persist an [`apply_chat_to_state`] outcome to the shared events DB — async, run by the
/// caller AFTER the STATE lock drops. Only a new message writes a message row.
pub async fn persist_chat(channel_id: &str, outcome: &ChatPersist) {
    match outcome {
        ChatPersist::New(m) => {
            let _ = crate::db::events::save_message(channel_id, m).await;
        }
        ChatPersist::Updated { message, edit_event: None } => {
            let _ = crate::db::events::save_new_reactions(channel_id, message).await;
        }
        ChatPersist::Updated { edit_event: Some(ev), .. } => save_edit_event(channel_id, ev).await,
        ChatPersist::Removed { id, .. } => remove_message(id).await,
        ChatPersist::ReactionRemoved { reaction_id, .. } => {
            let _ = crate::db::events::delete_event(reaction_id).await;
        }
    }
}

/// Hand an applied outcome to `handler`: the coarse hook a renderer redraws from, then the typed
/// one naming what happened, only when it is [news](crate::news::is_news). Without a listener,
/// `live` lets a new message ring; a re-judged or replayed one never does. A listener is told
/// whatever was sent since it began, however it arrived.
pub async fn notify_chat_outcome(handler: &dyn InboundEventHandler, channel_id: &str, event: &ChatEvent, outcome: ChatPersist, live: bool) {
    let by = || event.opened().author.to_bech32().unwrap_or_else(|_| event.opened().author.to_hex());
    let at = event.opened().at_ms;
    // Told once: two paths storing one event a moment apart can each think they stored it first.
    let news = || crate::news::is_news(at) && crate::news::first_telling(event.opened().rumor_id.as_bytes());
    match outcome {
        ChatPersist::New(message) => {
            let fresh = match crate::news::listening_since() {
                Some(_) => crate::news::is_news(message.at) && crate::news::first_telling_hex(&message.id),
                None => live && crate::community::is_realtime_fresh(message.at),
            };
            handler.on_community_message(channel_id, &message, fresh);
        }
        // Both come back out of STATE, whose compact form drops the quoted attachment's
        // extension, so re-resolve before rendering.
        ChatPersist::Updated { mut message, edit_event } => {
            let _ = crate::db::events::populate_reply_context(&mut message).await;
            handler.on_community_update(channel_id, &message.id, &message);
            match (edit_event, event) {
                _ if !news() => {}
                (Some(_), _) => handler.on_message_edited(channel_id, &message, at),
                (None, ChatEvent::Reaction { opened, .. }) => {
                    let id = opened.rumor_id.to_hex();
                    if let Some(reaction) = message.reactions.iter().find(|r| r.id == id) {
                        handler.on_reaction_added(channel_id, &message, reaction, at);
                    }
                }
                _ => {}
            }
        }
        // An un-react redraws the PARENT: its chips changed.
        ChatPersist::ReactionRemoved { reaction_id, mut message } => {
            let _ = crate::db::events::populate_reply_context(&mut message).await;
            handler.on_community_update(channel_id, &message.id, &message);
            if news() {
                handler.on_reaction_removed(channel_id, &message, &reaction_id, &by(), at);
            }
        }
        ChatPersist::Removed { id, moderated } => {
            handler.on_community_removed(channel_id, &id);
            if news() {
                handler.on_message_removed(channel_id, &id, Some(&by()), moderated, at);
            }
        }
    }
}

/// Drop a deleted message, tombstone first: a relay re-serving the original after a restart
/// would otherwise ingest it again, and a moderator's delete would quietly undo itself.
async fn remove_message(id: &str) {
    crate::state::note_message_deleted(id);
    if let Err(e) = crate::db::events::add_message_tombstone(id) {
        crate::log_warn!("[v2 delete] tombstone write failed: {e}");
    }
    let _ = crate::db::events::delete_event(id).await;
}

/// [`persist_chat`] for a catch-up page, in wire order: new messages batch into one
/// transaction, and a delete is a barrier, so nothing saved before it on the wire lands after it.
pub async fn persist_chat_page(channel_id: &str, outcomes: &[ChatPersist], session: &std::sync::Arc<crate::db::Session>) {
    let mut pending: Vec<&Message> = Vec::new();
    let mut reacted: Vec<&Message> = Vec::new();
    for outcome in outcomes {
        if !session.is_live() {
            return;
        }
        match outcome {
            ChatPersist::New(m) => pending.push(m),
            ChatPersist::Updated { message, edit_event: None } => reacted.push(message),
            ChatPersist::Updated { edit_event: Some(ev), .. } => save_edit_event(channel_id, ev).await,
            ChatPersist::Removed { id, .. } => {
                flush_page(channel_id, &mut pending, &mut reacted, session).await;
                remove_message(id).await;
            }
            ChatPersist::ReactionRemoved { reaction_id, .. } => {
                flush_page(channel_id, &mut pending, &mut reacted, session).await;
                let _ = crate::db::events::delete_event(reaction_id).await;
            }
        }
    }
    flush_page(channel_id, &mut pending, &mut reacted, session).await;
}

async fn flush_page<'a>(
    channel_id: &str,
    pending: &mut Vec<&'a Message>,
    reacted: &mut Vec<&'a Message>,
    session: &std::sync::Arc<crate::db::Session>,
) {
    crate::db::events::flush_message_batch(channel_id, pending, session).await;
    for message in reacted.drain(..) {
        if session.is_live() {
            let _ = crate::db::events::save_new_reactions(channel_id, message).await;
        }
    }
}

async fn save_edit_event(channel_id: &str, ev: &crate::stored_event::StoredEvent) {
    let mut ev = ev.clone();
    // get-or-CREATE: a lookup-only id would leave a fresh channel's edit at
    // chat_id 0 (orphaned, dropped on the reload fold).
    if let Ok(cid) = crate::db::id_cache::get_or_create_chat_id(channel_id) {
        ev.chat_id = cid;
    }
    let _ = crate::db::events::save_event(&ev).await;
}

/// The typed outcome of dispatching one v2 wrap.
#[derive(Debug, Clone)]
pub enum DispatchedV2 {
    /// An OPENED chat event (message/reaction/edit/delete) on `channel_id` (hex),
    /// NOT yet applied. The realtime layer runs it through [`persist_chat_event`]
    /// and fires the matching callback from the outcome — so a re-wrapped
    /// duplicate (any keyholder can re-wrap a signed seal into a fresh 1059) or a
    /// forged edit/delete never re-fires a handler.
    Chat { channel_id: String, event: Box<ChatEvent> },
    /// A typing indicator from `npub` on `channel_id`.
    Typing { channel_id: String, npub: String },
    /// A voice presence that changed who is in `channel_id`'s call.
    VoicePresence { channel_id: String },
    /// A Guestbook join/leave for `npub`. Each Guestbook variant carries the event it opened, for
    /// the store.
    Presence { npub: String, joined: bool, event: Box<guestbook::GuestbookEvent> },
    /// A Guestbook Kick naming `target`. Returned unjudged: the store keeps the
    /// raw rumor and the memberlist fold is what applies KICK authority, so the
    /// realtime layer ingests it and re-folds rather than trusting the wrap.
    Kick { target: PublicKey, event: Box<guestbook::GuestbookEvent> },
    /// A Guestbook Nickname, unjudged like a Kick: the store keeps it and the fold judges it.
    Nickname(Box<guestbook::GuestbookEvent>),
    /// A Guestbook Timeout, unjudged the same way.
    Timeout(Box<guestbook::GuestbookEvent>),
    /// A wrap on this community's Control Plane — its metadata/channel set may
    /// have changed. Recognized here (address match) but NOT folded: the fold
    /// needs the whole edition chain, so the realtime layer re-fetches + re-folds
    /// + re-subscribes. `community_id` is hex.
    Control { community_id: String },
    /// A wrap on one of this community's next-epoch rekey planes — a rotation is in
    /// flight. Recognized by address; the realtime layer runs the stateful catch-up
    /// ([`super::service::follow_rekeys`]) across every scope. `community_id` is hex.
    Rekey { community_id: String },
    /// A verified owner-signed tombstone at the dissolved plane (CORD-02 §9): the
    /// community is dead. The realtime layer seals it read-only. `community_id` is hex.
    Dissolved { community_id: String },
    /// A post `channel_id`'s writers' rules don't stand behind on arrival: the realtime layer
    /// holds the wrap for a later judgment, and keeps `marked`, the copy a reader who manages the
    /// Channel sees, without ringing anything.
    Held { channel_id: String, author: PublicKey, at_ms: u64, marked: Option<Box<ChatEvent>> },
    /// A message dated ahead of this device's clock, to be held until `at_ms` ([`crate::early`]),
    /// before any rule judges it.
    Early { at_ms: u64 },
    /// The wrap opened on a v2 plane but carries nothing the handler renders
    /// (e.g. a WebXDC signal, or a kick we don't surface in the first cut).
    Ignored,
    /// Not a v2 plane of this community — try elsewhere / drop.
    NotOurs,
}

/// Dispatch a received kind-1059 wrap for `community`: route it to the plane it
/// opens under. Chat events are returned OPENED (the realtime layer persists,
/// then fires callbacks from the outcome); only the non-persisted kinds (typing,
/// guestbook presence) fire their callback inline here. Purely in-memory — so
/// this stays offline-testable.
pub fn dispatch_wrap(
    wrap: &nostr_sdk::prelude::Event,
    community: &CommunityV2,
    my_pubkey: &PublicKey,
    handler: &dyn InboundEventHandler,
) -> DispatchedV2 {
    // 1. Chat planes: try each held channel by its group key (author match).
    for ch in &community.channels {
        // A keyless private channel is UNREADABLE — never address it at the root plane
        // (channel_secret falls back to the root, which would be a private→public leak).
        if ch.private && ch.key.is_none() {
            continue;
        }
        let (secret, epoch) = community.channel_secret(ch);
        let group = super::derive::channel_group_key(&secret, &ch.id, epoch);
        if wrap.pubkey != group.pk() {
            continue;
        }
        // Dated where a Locked Channel's read address takes nothing, or below its seal, which
        // names all that stands there: never worth opening.
        let below_seal = |at_ms: u64| ch.writers.as_ref().and_then(|l| l.seal.as_ref()).is_some_and(|s| at_ms < s.until);
        let wrapped_ms = wrap.created_at.as_secs().saturating_mul(1000);
        if ch.writers.as_ref().is_some_and(|l| l.read_address_quiet(wrapped_ms)) || below_seal(wrapped_ms.saturating_add(999)) {
            return DispatchedV2::Ignored;
        }
        let Ok(event) = chat::open_chat_event(wrap, &group, &ch.id, epoch) else {
            return DispatchedV2::NotOurs;
        };
        if below_seal(event.opened().at_ms) {
            return DispatchedV2::Ignored;
        }
        return dispatch_judged(event, community, ch, None, my_pubkey, handler);
    }

    // 1b. A restricted Channel's writer addresses (CORD-03 §1), opened under the read key.
    for ch in &community.channels {
        let Some(ledger) = ch.writers.as_ref() else { continue };
        if ch.private && ch.key.is_none() {
            continue;
        }
        let Some((wepoch, ..)) = ledger.writers().find(|(_, pk, _)| *pk == wrap.pubkey.to_bytes()) else { continue };
        let (secret, epoch) = community.channel_secret(ch);
        let group = super::derive::channel_group_key(&secret, &ch.id, epoch);
        let Ok(event) = chat::open_writer_chat_event(wrap, &wrap.pubkey, wepoch, group.conv_key(), &ch.id, epoch) else {
            return DispatchedV2::NotOurs;
        };
        return dispatch_judged(event, community, ch, Some(wepoch), my_pubkey, handler);
    }

    // 2. Guestbook plane: join/leave presence.
    let gb = super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
    if wrap.pubkey == gb.pk() {
        if let Ok(opened) = stream::open_wrap(wrap, &gb) {
            if let Ok(ev) = guestbook::parse_guestbook_event(&opened) {
                return dispatch_guestbook(ev, community, handler);
            }
        }
        return DispatchedV2::Ignored;
    }

    // 3. Control plane: a metadata/channel edition. Recognized by address only —
    // the fold needs the whole chain, which the realtime layer re-fetches. Shares
    // one address helper with the subscription so the two can't drift.
    if wrap.pubkey == super::realtime::control_author(community) {
        return DispatchedV2::Control { community_id: crate::simd::hex::bytes_to_hex_32(&community.id().0) };
    }

    // 4. Rekey planes: a rotation in flight (base or a private channel), addressed
    // at the next epoch. Same author-set the subscription rides — one source of
    // truth ([`super::realtime::rekey_authors`]) so recognition and subscription
    // can't drift.
    if super::realtime::rekey_authors(community).contains(&wrap.pubkey) {
        return DispatchedV2::Rekey { community_id: crate::simd::hex::bytes_to_hex_32(&community.id().0) };
    }

    // 5. Dissolved plane: the terminal tombstone (CORD-02 §9). Honor ONLY a valid
    // owner seal — a foreign event at this public address is noise.
    if wrap.pubkey == super::derive::dissolved_group_key(community.id()).pk() {
        if super::dissolution::verify_dissolved(wrap, &community.identity) {
            return DispatchedV2::Dissolved { community_id: crate::simd::hex::bytes_to_hex_32(&community.id().0) };
        }
        return DispatchedV2::Ignored;
    }

    DispatchedV2::NotOurs
}

/// Judge `event` by its Channel's writers' rules, then dispatch what stands.
fn dispatch_judged(event: ChatEvent, community: &CommunityV2, ch: &super::community::ChannelV2, wepoch: Option<crate::community::Epoch>, my_pubkey: &PublicKey, handler: &dyn InboundEventHandler) -> DispatchedV2 {
    let channel_id = crate::simd::hex::bytes_to_hex_32(&ch.id.0);
    let (at_ms, author) = (event.opened().at_ms, event.opened().author);
    if matches!(event, ChatEvent::Message { .. }) && crate::early::is_early(at_ms) {
        return DispatchedV2::Early { at_ms };
    }
    // A call's signals ride where the Channel's writes do: in a Locked one, only with Connect.
    if matches!(event, ChatEvent::VoicePresence { .. } | ChatEvent::VoiceDirective { .. }) && super::service::Judge::of(community, ch).is_some_and(|j| !j.admits(&event, wepoch)) {
        return DispatchedV2::Ignored;
    }
    if let ChatEvent::VoicePresence { opened, heard } = event {
        if author_is_banned_here(&channel_id, Some(&community.id().0), &opened.author) {
            return DispatchedV2::Ignored;
        }
        let now = crate::clock::now_ms();
        let noted = super::voice::note(&channel_id, opened.author, at_ms, heard, now);
        if noted.reached {
            super::service::reassert_voice_directives(community, &channel_id, &opened.author);
            #[cfg(feature = "calls")]
            crate::calls::voice::greet(&channel_id, &opened.author);
        }
        if !noted.changed {
            return DispatchedV2::Ignored;
        }
        #[cfg(feature = "calls")]
        crate::calls::voice::nudge(&channel_id);
        handler.on_voice_presence(&channel_id);
        return DispatchedV2::VoicePresence { channel_id };
    }
    if let ChatEvent::VoiceDirective { opened, target, directive, to } = event {
        let cid = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let owner = community.owner().ok().map(|o| o.to_hex());
        let actor = opened.author.to_hex();
        let roles = crate::db::community::get_community_roles(&cid).unwrap_or_default();
        let authorized = (owner.as_deref() == Some(actor.as_str()) && owner.as_deref() != Some(target.to_hex().as_str()))
            || roles.can_act_on_member(&actor, owner.as_deref(), &target.to_hex(), directive.permission());
        if !authorized || author_is_banned_here(&channel_id, Some(&community.id().0), &opened.author) {
            return DispatchedV2::Ignored;
        }
        let now = crate::clock::now_ms();
        // A member holding the key can re-wrap a signed directive it once saw (CORD-07 §7).
        if !super::voice::directive_in_window(&channel_id, &target, at_ms, now) {
            return DispatchedV2::Ignored;
        }
        if super::voice::apply_directive(&channel_id, &target, directive, at_ms, now) {
            super::service::yield_voice_directive(&channel_id, &target, directive);
        }
        if let Some(id) = opened.rumor.id {
            super::service::note_voice_directive(&cid, &id.to_hex(), at_ms, &actor, &target.to_hex(), &channel_id, directive, to.as_ref());
        }
        #[cfg(feature = "calls")]
        crate::calls::voice::on_directive(&channel_id, &target, directive, to);
        #[cfg(not(feature = "calls"))]
        let _ = to;
        handler.on_voice_presence(&channel_id);
        return DispatchedV2::VoicePresence { channel_id };
    }
    match super::service::sort_arrival(super::service::Judge::of(community, ch).as_ref(), event, wepoch) {
        super::service::Arrival::Stands(event) => dispatch_chat_event(event, &channel_id, &community.id().0, my_pubkey, handler),
        super::service::Arrival::Held(marked) => DispatchedV2::Held { channel_id, author, at_ms, marked: marked.map(Box::new) },
        super::service::Arrival::Dropped => DispatchedV2::Ignored,
    }
}

fn dispatch_chat_event(
    event: ChatEvent,
    channel_id: &str,
    community: &[u8; 32],
    my_pubkey: &PublicKey,
    handler: &dyn InboundEventHandler,
) -> DispatchedV2 {
    match event {
        // Typing is ephemeral (never persisted) — fired inline, so it carries its
        // own CORD-04 banned-author drop (the persisted kinds get theirs in
        // `apply_chat_to_state`).
        ChatEvent::Typing { opened } => {
            // Drop by AUTHOR, not by wrap id: another client signing with the same
            // key is still us, and the send-side dedup only knows our own wraps.
            // Drop by AUTHOR, not by wrap id: another client signing with the same
            // key is still us, and the send-side dedup only knows our own wraps.
            if opened.author == *my_pubkey || author_is_banned_here(channel_id, Some(community), &opened.author) {
                return DispatchedV2::Ignored;
            }
            let npub = opened.author.to_bech32().unwrap_or_default();
            let until = opened.at_ms / 1000 + 30;
            handler.on_community_typing(channel_id, &npub, until);
            DispatchedV2::Typing { channel_id: channel_id.to_string(), npub }
        }
        // A WebXDC peer signal fires the shared handler surface: the common
        // tail (30078 persist + recency gate + Iroh wiring + the lobby emit) does
        // the rest. Own-device echoes drop: the local realtime layer tracks itself.
        ChatEvent::Webxdc { opened } => {
            if opened.author == *my_pubkey || author_is_banned_here(channel_id, Some(community), &opened.author) {
                return DispatchedV2::Ignored;
            }
            let Some((topic_id, node_addr)) = crate::webxdc::parse_peer_signal(&opened.rumor.content) else {
                return DispatchedV2::Ignored;
            };
            let npub = opened.author.to_bech32().unwrap_or_default();
            handler.on_community_webxdc(
                channel_id,
                &npub,
                &topic_id,
                node_addr.as_deref(),
                &opened.rumor_id.to_hex(),
                opened.at_ms / 1000,
            );
            DispatchedV2::Ignored
        }
        // Message/Reaction/Edit/Delete all persist first; their callbacks fire from
        // the outcome (dedup + author checks), never optimistically.
        event => DispatchedV2::Chat { channel_id: channel_id.to_string(), event: Box::new(event) },
    }
}

fn dispatch_guestbook(ev: guestbook::GuestbookEvent, community: &CommunityV2, handler: &dyn InboundEventHandler) -> DispatchedV2 {
    // CORD-04 §4 is a RENDER/FOLD rule, not a storage rule: a banned npub's
    // presence draws no line, but the event still reaches the store, because the
    // fold subtracts the banlist REVERSIBLY. Dropping it here instead is
    // destructive: an invite legally races an unban ("any keyholder can whisper
    // keys"), so a Join can arrive seconds before the unban edition — eaten at
    // the store, the member stays invisible after the unban with nothing left to
    // re-fold.
    let suppressed = match &ev.entry {
        GuestbookEntry::Join { member, .. } | GuestbookEntry::Leave { member, .. } => {
            let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
            crate::db::community::is_author_banned(&cid_hex, member)
        }
        _ => false,
    };
    // The REAL rumor id keys the presence line: `save_system_event_at` dedups by
    // it, so every distinct join/leave inserts exactly once no matter how many
    // paths (live replay, reconnect, catch-up) deliver it.
    let event_id = crate::simd::hex::bytes_to_hex_32(&ev.rumor_id);
    // A community with NO channels has nowhere to keep the line: a blank conversation id
    // would collapse every such community into one unopenable chat. The dispatch still
    // reports the presence so the memberlist bookkeeping runs, and the guestbook re-folds the
    // line once a channel exists.
    let home = community.presence_home().map(|h| (crate::simd::hex::bytes_to_hex_32(&h.channel.id.0), h.shown));
    let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
    let tell = |npub: &str, joined: bool, at_ms: u64, invited_by: &Option<(String, String)>| {
        let Some((channel_id, shown)) = home.as_ref().filter(|_| !suppressed) else { return };
        if crate::news::first_telling(&ev.rumor_id) {
            let (by, label) = invited_by.as_ref().map_or((None, None), |(c, l)| (Some(c.as_str()), Some(l.as_str())));
            handler.on_community_presence(&crate::Presence {
                community_id: &cid_hex,
                channel_id,
                shown: *shown,
                npub,
                joined,
                event_id: &event_id,
                created_at: at_ms / 1000,
                invited_by: by,
                invited_label: label,
            });
        }
    };
    match &ev.entry {
        GuestbookEntry::Join { member, at_ms, invited_by } => {
            let npub = member.to_bech32().unwrap_or_default();
            tell(&npub, true, *at_ms, invited_by);
            DispatchedV2::Presence { npub, joined: true, event: Box::new(ev) }
        }
        GuestbookEntry::Leave { member, at_ms } => {
            let npub = member.to_bech32().unwrap_or_default();
            tell(&npub, false, *at_ms, &None);
            DispatchedV2::Presence { npub, joined: false, event: Box::new(ev) }
        }
        // A Kick shapes the memberlist, not the feed — so no presence line, but it
        // MUST reach the store or the target never leaves anyone's roster.
        GuestbookEntry::Kick { target, .. } => DispatchedV2::Kick { target: *target, event: Box::new(ev) },
        GuestbookEntry::Snapshot { .. } => DispatchedV2::Ignored,
        GuestbookEntry::Nickname { .. } => DispatchedV2::Nickname(Box::new(ev)),
        // A Timeout shapes how a member's posts read, not who is a member: no presence line.
        GuestbookEntry::Timeout { .. } => DispatchedV2::Timeout(Box::new(ev)),
    }
}

/// Persist an inbound WebXDC peer signal as a kind-30078 event row — the SAME shape the DM
/// peer-advertisement handler writes (content `peer-advertisement`/`peer-left`, `reference_id`
/// = topic, `webxdc-topic`/`webxdc-node-addr` tags) — so the miniapp layer's
/// `get_active_peer_advertisements` (latest-per-npub, left-tombstone-aware) reads both
/// transports identically. This is what lets a member who closed Vector mid-session rediscover
/// the active players on reopen. Idempotent via `event_exists`.
pub async fn persist_webxdc_signal(
    channel_hex: &str,
    npub: &str,
    topic_id: &str,
    node_addr: Option<&str>,
    event_id: &str,
    created_at: u64,
) {
    if crate::db::events::event_exists(event_id).unwrap_or(true) {
        return;
    }
    // Sender-claimed timestamp: clamp into the near future so a forged far-future ad
    // can't outrank every later genuine peer-left in the latest-per-npub read.
    let now_secs = crate::clock::now_secs();
    let created_at = created_at.min(now_secs + 300);
    let Ok(chat_id) = crate::db::id_cache::get_or_create_chat_id(channel_hex) else { return };
    let mut tags = vec![
        vec!["webxdc-topic".to_string(), topic_id.to_string()],
        vec!["d".to_string(), "vector-webxdc-peer".to_string()],
    ];
    if let Some(addr) = node_addr {
        tags.push(vec!["webxdc-node-addr".to_string(), addr.to_string()]);
    }
    let event = crate::stored_event::StoredEvent {
        id: event_id.to_string(),
        kind: crate::stored_event::event_kind::APPLICATION_SPECIFIC,
        chat_id,
        user_id: None,
        content: if node_addr.is_some() { "peer-advertisement" } else { "peer-left" }.to_string(),
        tags,
        reference_id: Some(topic_id.to_string()),
        created_at,
        received_at: crate::clock::now_ms(),
        mine: false,
        pending: false,
        failed: false,
        wrapper_event_id: None,
        npub: Some(npub.to_string()),
        preview_metadata: None,
    };
    if let Err(e) = crate::db::events::save_event(&event).await {
        crate::log_warn!("[community] failed to persist webxdc peer signal: {e}");
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use super::super::service;
    use crate::community::transport::memory::MemoryRelay;
    use crate::community::transport::Transport;
    use nostr_sdk::prelude::Keys;
    use std::sync::Mutex;

    /// A handler that records every callback it receives.
    #[derive(Default)]
    struct Recorder {
        messages: Mutex<Vec<(String, Message)>>,
        updates: Mutex<Vec<(String, String)>>,
        removed: Mutex<Vec<(String, String)>>,
        presence: Mutex<Vec<(String, bool)>>,
        typing: Mutex<Vec<(String, String)>>,
    }
    impl InboundEventHandler for Recorder {
        fn on_community_message(&self, chat_id: &str, msg: &Message, _is_new: bool) {
            self.messages.lock().unwrap().push((chat_id.to_string(), msg.clone()));
        }
        fn on_community_update(&self, chat_id: &str, target: &str, _msg: &Message) {
            self.updates.lock().unwrap().push((chat_id.to_string(), target.to_string()));
        }
        fn on_community_removed(&self, chat_id: &str, target: &str) {
            self.removed.lock().unwrap().push((chat_id.to_string(), target.to_string()));
        }
        fn on_community_presence(&self, p: &crate::Presence<'_>) {
            self.presence.lock().unwrap().push((p.npub.to_string(), p.joined));
        }
        fn on_community_typing(&self, chat_id: &str, npub: &str, _until: u64) {
            self.typing.lock().unwrap().push((chat_id.to_string(), npub.to_string()));
        }
    }

    fn init() -> (tempfile::TempDir, std::sync::MutexGuard<'static, ()>, Keys) {
        let guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
        crate::db::close_database();
        crate::db::clear_id_caches();
        let tmp = tempfile::tempdir().unwrap();
        static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(90_000);
        let n = N.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        const B: &[u8] = b"qpzry9x8gf2tvdw0s3jn54khce6mua7l";
        let mut acct = String::from("npub1");
        let mut v = n as usize;
        for _ in 0..58 {
            acct.push(B[v % 32] as char);
            v = v / 32 + 7;
        }
        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());
        (tmp, guard, me)
    }

    #[tokio::test]
    async fn a_restricted_channel_dispatches_its_writers_and_holds_the_rest() {
        use super::super::writers::{writer_address, Ledger, Spell};
        use crate::community::Epoch;
        use nostr_sdk::prelude::Timestamp;
        let (_tmp, _guard, me) = init();
        let relay = MemoryRelay::new();
        let mut community = service::create_community(&relay, "Live", vec!["wss://r".into()], None).await.unwrap();
        let general = community.channels[0].id;
        let epoch = community.root_epoch;
        let read = super::super::derive::channel_group_key(&community.community_root, &general, epoch);
        let (s1, s2) = ([0x11; 32], [0x22; 32]);
        let w1 = super::super::derive::channel_writer_group_key(&s1, &general, Epoch(1));
        let w2 = super::super::derive::channel_writer_group_key(&s2, &general, Epoch(2));
        let ledger = Ledger::new(&general)
            .appended(10_000, Spell::Writer { epoch: Epoch(1), pk: writer_address(&s1, &general, Epoch(1)), root: Epoch(0), by: [0x0b; 32], certifier: None })
            .unwrap()
            .appended(20_000, Spell::Writer { epoch: Epoch(2), pk: writer_address(&s2, &general, Epoch(2)), root: Epoch(0), by: [0x0b; 32], certifier: None })
            .unwrap();
        community.channels[0].writers = Some(ledger);
        assert!(super::super::realtime::plane_authors(std::slice::from_ref(&community)).contains(&w2.pk()), "the live writer is subscribed");
        let member = Keys::generate();
        let post = |group: &super::super::derive::GroupKey, wepoch: Option<Epoch>, text: &str, at_ms: u64| {
            let rumor = chat::build_message_rumor(member.public_key(), &general, epoch, text, None, &[], vec![], at_ms);
            let rumor = match wepoch {
                Some(w) => chat::with_writer_epoch(rumor, w),
                None => rumor,
            };
            let split = super::super::derive::GroupKey::from_parts(group.keys().clone(), read.conv_key().clone());
            chat::seal_chat_rumor(&rumor, &split, &member, Timestamp::from_secs(at_ms / 1000), false).unwrap().0
        };
        let rec = Recorder::default();
        let chat = |wrap: &nostr_sdk::prelude::Event| matches!(dispatch_wrap(wrap, &community, &me.public_key(), &rec), DispatchedV2::Chat { .. });
        assert!(chat(&post(&w2, Some(Epoch(2)), "live", 30_000)));
        // A writer address's post carries that provenance; a read-address one doesn't.
        let as_message = |wrap: &nostr_sdk::prelude::Event| match dispatch_wrap(wrap, &community, &me.public_key(), &rec) {
            DispatchedV2::Chat { event, .. } => match *event {
                chat::ChatEvent::Message { opened, reply_to, emoji } => chat_message_to_message(&opened, &reply_to, &emoji, &me.public_key()),
                _ => panic!("not a message"),
            },
            _ => panic!("not dispatched as chat"),
        };
        assert!(as_message(&post(&w2, Some(Epoch(2)), "signed by the key", 30_000)).writer);
        assert!(!as_message(&post(&read, None, "said in the open", 5_000)).writer);
        assert!(chat(&post(&w1, Some(Epoch(1)), "past", 15_000)), "a writer's past posts stay");
        // What the windows don't stand behind is held, and the owner keeps a marked copy.
        let held = |wrap: &nostr_sdk::prelude::Event| matches!(dispatch_wrap(wrap, &community, &me.public_key(), &rec), DispatchedV2::Held { marked: Some(ref e), .. } if e.opened().held);
        assert!(held(&post(&w1, Some(Epoch(1)), "late", 25_000)), "held after its entry ends");
        assert!(!chat(&post(&w2, Some(Epoch(1)), "spliced", 30_000)), "the epoch must be the address's");
        assert!(!chat(&post(&w2, None, "untagged", 30_000)));
        assert!(held(&post(&read, None, "flood", 30_000)), "held inside a writer window");
        assert!(chat(&post(&read, None, "earlier", 5_000)), "before the window it was open");
        assert!(!chat(&post(&read, Some(Epoch(2)), "dressed up", 5_000)), "a read-address post claims no writer epoch");
        let reaction = chat::build_reaction_rumor(member.public_key(), &general, epoch, &crate::simd::hex::bytes_to_hex_32(&[0x33; 32]), &me.public_key().to_hex(), 9, "+", None, 30_000);
        let (wrap, _) = chat::seal_chat_rumor(&reaction, &read, &member, Timestamp::from_secs(30), false).unwrap();
        assert!(chat(&wrap), "reactions stay at the read address");
        // Typing signals posting: only a writer address carries it.
        let typing = |group: &super::super::derive::GroupKey, wepoch: Option<Epoch>| {
            let rumor = chat::build_typing_rumor(member.public_key(), &general, epoch, 30_000);
            let rumor = match wepoch {
                Some(w) => chat::with_writer_epoch(rumor, w),
                None => rumor,
            };
            let split = super::super::derive::GroupKey::from_parts(group.keys().clone(), read.conv_key().clone());
            chat::seal_chat_rumor(&rumor, &split, &member, Timestamp::from_secs(30), true).unwrap().0
        };
        assert!(matches!(dispatch_wrap(&typing(&read, None), &community, &me.public_key(), &rec), DispatchedV2::Ignored), "nobody shows as typing through the read address");
        assert!(matches!(dispatch_wrap(&typing(&w2, Some(Epoch(2))), &community, &me.public_key(), &rec), DispatchedV2::Typing { .. }), "a writer does");
        // Being in a call is CONNECT, not posting: presence counts at the read address.
        let presence = |endpoint: Option<[u8; 32]>, at_ms: u64| {
            let rumor = chat::build_voice_presence_rumor(member.public_key(), &general, epoch, endpoint.as_ref().map(|e| (e, Some("https://relay.example./"))), crate::community::v2::voice::Showing { muted: true, ..Default::default() }, at_ms);
            chat::seal_chat_rumor(&rumor, &read, &member, Timestamp::from_secs(at_ms / 1000), true).unwrap().0
        };
        let now = web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).unwrap().as_millis() as u64;
        let ch_hex = crate::simd::hex::bytes_to_hex_32(&general.0);
        assert!(matches!(dispatch_wrap(&presence(Some([0x44; 32]), now), &community, &me.public_key(), &rec), DispatchedV2::VoicePresence { .. }), "a non-writer is in the call");
        assert_eq!(super::super::voice::author_of(&ch_hex, &[0x44; 32], now), Some(member.public_key()), "the sealed presence binds its endpoint to them");
        assert_eq!(super::super::voice::present(&ch_hex, now)[0].relay.as_deref(), Some("https://relay.example./"), "and names the relay it's reached through");
        assert!(super::super::voice::present(&ch_hex, now)[0].muted && !super::super::voice::present(&ch_hex, now)[0].deafened, "and whether they're muted");
        assert!(matches!(dispatch_wrap(&presence(None, now + 1), &community, &me.public_key(), &rec), DispatchedV2::VoicePresence { .. }));
        assert!(super::super::voice::present(&ch_hex, now + 1).is_empty(), "and leaves it");
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        crate::db::community::set_community_banlist(&cid_hex, &[member.public_key().to_hex()], 1).unwrap();
        assert!(matches!(dispatch_wrap(&presence(Some([0x45; 32]), now + 2), &community, &me.public_key(), &rec), DispatchedV2::Ignored), "a banned member is in no call");
        crate::db::community::set_community_banlist(&cid_hex, &[], 2).unwrap();
        // A forged wrap at the writer address fails the signature a reader checks there.
        let mut forged = post(&w2, Some(Epoch(2)), "forged", 30_000);
        forged.sig = post(&w2, Some(Epoch(2)), "other", 30_001).sig;
        assert!(!chat(&forged));
        // A member who manages nothing keeps no copy of what is held. An epoch whose entry
        // named no certifier is judged on its window alone.
        let reader = Keys::generate();
        crate::state::MY_SECRET_KEY.store_from_keys(&reader, &[]);
        crate::state::set_my_public_key(reader.public_key());
        assert!(matches!(dispatch_wrap(&post(&w1, Some(Epoch(1)), "late again", 25_000), &community, &reader.public_key(), &rec), DispatchedV2::Held { marked: None, .. }));
        assert!(matches!(dispatch_wrap(&post(&read, None, "flood again", 30_000), &community, &reader.public_key(), &rec), DispatchedV2::Held { marked: None, .. }));
        assert!(matches!(dispatch_wrap(&post(&w1, Some(Epoch(1)), "past again", 15_000), &community, &reader.public_key(), &rec), DispatchedV2::Chat { .. }));
        assert!(matches!(dispatch_wrap(&typing(&read, None), &community, &reader.public_key(), &rec), DispatchedV2::Ignored), "a signal of the moment is never held");
    }

    #[tokio::test]
    async fn a_received_message_wrap_opens_then_fires_from_the_persist_outcome() {
        use nostr_sdk::prelude::Timestamp;
        let (_tmp, _guard, me) = init();
        let relay = MemoryRelay::new();
        let community = service::create_community(&relay, "In", vec!["wss://r".into()], None).await.unwrap();
        let general = community.channels[0].id;
        let cid = crate::simd::hex::bytes_to_hex_32(&general.0);

        // ANOTHER member (holds the root) posts — the incoming case, so no local
        // send echo pre-persisted it.
        let member = Keys::generate();
        let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);
        let rumor = chat::build_message_rumor(member.public_key(), &general, community.root_epoch, "ping", None, &[], vec![], 5_000);
        let (wrap, _) = chat::seal_chat_rumor(&rumor, &group, &member, Timestamp::from_secs(5), false).unwrap();

        // Dispatch OPENS the event but fires no message callback — that belongs to
        // the persist outcome (dedup + author checks).
        let rec = Recorder::default();
        let dispatched = dispatch_wrap(&wrap, &community, &me.public_key(), &rec);
        assert!(rec.messages.lock().unwrap().is_empty(), "no optimistic message callback");
        let DispatchedV2::Chat { channel_id, event } = dispatched else {
            panic!("a chat wrap dispatches as Chat");
        };
        assert_eq!(channel_id, cid);

        let outcome = persist_chat_event(&event, &channel_id, &me.public_key()).await;
        let Some(ChatPersist::New(msg)) = outcome else {
            panic!("the first delivery persists as New");
        };
        assert_eq!(msg.content, "ping");
        assert!(!msg.mine, "authored by the other member");

        // A RE-WRAP of the same signed rumor (any keyholder can mint one) is a
        // fresh outer event, but the persist dedups on the inner id — no re-fire.
        let (rewrap, _) = chat::seal_chat_rumor(&rumor, &group, &member, Timestamp::from_secs(6), false).unwrap();
        assert_ne!(rewrap.id, wrap.id, "a re-wrap is a distinct outer event");
        let DispatchedV2::Chat { event: dup, .. } = dispatch_wrap(&rewrap, &community, &me.public_key(), &rec) else {
            panic!("the re-wrap still opens");
        };
        assert!(
            persist_chat_event(&dup, &channel_id, &me.public_key()).await.is_none(),
            "a re-wrapped duplicate yields no outcome (nothing re-fires)"
        );
    }

    #[tokio::test]
    async fn an_already_expired_message_is_refused_at_ingest() {
        use nostr_sdk::prelude::{Tag, Timestamp};
        let (_tmp, _guard, me) = init();
        let relay = MemoryRelay::new();
        let community = service::create_community(&relay, "Exp", vec!["wss://r".into()], None).await.unwrap();
        let general = community.channels[0].id;
        let member = Keys::generate();
        let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);
        let rec = Recorder::default();

        // Only the rumor carries the past expiry: a keyholder re-wrapped the seal
        // without the outer tag, so no relay-side NIP-40 filter drops it first.
        let expired = vec![Tag::expiration(Timestamp::from_secs(1_000_000_000))];
        let rumor = chat::build_message_rumor(member.public_key(), &general, community.root_epoch, "gone", None, &[], expired, 5_000);
        let seal = stream::build_seal(&rumor, stream::SealForm::Encrypted, &group, &member).unwrap();
        let (wrap, _) = stream::wrap_seal(&seal, &group, stream::KIND_WRAP, Timestamp::from_secs(5)).unwrap();
        assert!(
            !wrap.tags.iter().any(|t| t.as_slice().first().map(|k| k == "expiration").unwrap_or(false)),
            "the outer wrap carries no expiration"
        );
        let DispatchedV2::Chat { channel_id, event } = dispatch_wrap(&wrap, &community, &me.public_key(), &rec) else {
            panic!("a chat wrap dispatches as Chat");
        };
        let id = event.opened().rumor_id.to_hex();
        assert!(
            persist_chat_event(&event, &channel_id, &me.public_key()).await.is_none(),
            "an expired message yields no outcome"
        );
        assert!(!crate::db::events::event_exists(&id).unwrap(), "never stored");
        assert!(crate::state::STATE.lock().await.find_message(&id).is_none(), "never resident");

        // A live timer still delivers: only an expiry already in the past is refused.
        let later = vec![Tag::expiration(Timestamp::from_secs(4_000_000_000))];
        let rumor = chat::build_message_rumor(member.public_key(), &general, community.root_epoch, "kept", None, &[], later, 6_000);
        let (wrap, _) = chat::seal_chat_rumor(&rumor, &group, &member, Timestamp::from_secs(6), false).unwrap();
        let DispatchedV2::Chat { channel_id, event } = dispatch_wrap(&wrap, &community, &me.public_key(), &rec) else {
            panic!("a chat wrap dispatches as Chat");
        };
        let Some(ChatPersist::New(msg)) = persist_chat_event(&event, &channel_id, &me.public_key()).await else {
            panic!("an unexpired message persists as New");
        };
        assert_eq!(msg.expiration, Some(4_000_000_000));
    }

    #[tokio::test]
    async fn an_edit_expires_with_the_message_it_edits() {
        use nostr_sdk::prelude::{Tag, Timestamp};
        let (_tmp, _guard, _me) = init();
        let relay = MemoryRelay::new();
        let community = service::create_community(&relay, "EditExp", vec!["wss://r".into()], None).await.unwrap();
        let general = community.channels[0].id;
        let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
        let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);
        // The edit's expiry as published: (inner rumor, outer wrap).
        async fn wire_expiry(
            relay: &MemoryRelay,
            community: &CommunityV2,
            group: &super::super::derive::GroupKey,
            edit_id: &str,
        ) -> (Option<u64>, Option<u64>) {
            let general = community.channels[0].id;
            let q = crate::community::transport::Query { kinds: vec![stream::KIND_WRAP], authors: vec![group.pk_hex()], ..Default::default() };
            let wraps = relay.fetch(&q, &community.relays).await.unwrap();
            wraps
                .iter()
                .find_map(|w| {
                    let ev = chat::open_chat_event(w, group, &general, community.root_epoch).ok()?;
                    (ev.opened().rumor_id.to_hex() == edit_id).then(|| {
                        let outer = w.tags.iter().find_map(|t| {
                            let s = t.as_slice();
                            (s.first().map(String::as_str) == Some("expiration")).then(|| s[1].parse::<u64>().unwrap())
                        });
                        (chat::message_expiration(&ev.opened().rumor), outer)
                    })
                })
                .expect("the edit is on the relay")
        }

        let exp = web_time::SystemTime::now().duration_since(web_time::UNIX_EPOCH).unwrap().as_secs() + 3_600;
        let fleeting = service::send_chat_message(&relay, &community, &general, "fleeting", None, &[], vec![Tag::expiration(Timestamp::from_secs(exp))]).await.unwrap();
        let edit = service::send_edit(&relay, &community, &general, &fleeting, "still fleeting", &[]).await.unwrap();
        assert_eq!(wire_expiry(&relay, &community, &group, &edit).await, (Some(exp), Some(exp)), "the rumor and the wrap both carry the message's expiry");

        let permanent = service::send_message(&relay, &community, &general, "forever").await.unwrap();
        let edit = service::send_edit(&relay, &community, &general, &permanent, "still forever", &[]).await.unwrap();
        assert_eq!(wire_expiry(&relay, &community, &group, &edit).await, (None, None), "a permanent message's edit is permanent");

        // Paged out of memory, the stored row still answers.
        crate::state::STATE.lock().await.remove_message(&fleeting);
        assert_eq!(crate::self_destruct::edit_expiry(&fleeting).await, Ok(Some(exp)));

        let lapsed = Message {
            id: "ab".repeat(32), content: "gone".into(), at: 1_000, mine: true,
            expiration: Some(1_000_000_000), ..Default::default()
        };
        crate::db::events::save_message(&cid, &lapsed).await.unwrap();
        assert!(service::send_edit(&relay, &community, &general, &lapsed.id, "too late", &[]).await.is_err(), "an expired message can't be edited");
    }

    #[tokio::test]
    async fn an_expired_reaction_or_edit_is_refused_but_an_expired_delete_still_lands() {
        use nostr_sdk::prelude::{Tag, Timestamp, UnsignedEvent};
        let (_tmp, _guard, me) = init();
        let relay = MemoryRelay::new();
        let community = service::create_community(&relay, "ExpAgg", vec!["wss://r".into()], None).await.unwrap();
        let general = community.channels[0].id;
        let epoch = community.root_epoch;
        let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
        let group = super::super::derive::channel_group_key(&community.community_root, &general, epoch);
        let member = Keys::generate();
        let expired = |r: &UnsignedEvent| {
            let mut tags: Vec<Tag> = r.tags.iter().cloned().collect();
            tags.push(Tag::expiration(Timestamp::from_secs(1_000_000_000)));
            stream::build_rumor_secs(r.kind.as_u16(), r.pubkey, &r.content, tags, r.created_at.as_secs())
        };
        let ingest = |rumor: UnsignedEvent, at: u64| {
            let (wrap, _) = chat::seal_chat_rumor(&rumor, &group, &member, Timestamp::from_secs(at), false).unwrap();
            chat::open_chat_event(&wrap, &group, &general, epoch).unwrap()
        };

        // A permanent message, so only each aggregate's own expiry is in play.
        let msg = chat::build_message_rumor(member.public_key(), &general, epoch, "permanent", None, &[], vec![], 5_000);
        let msg_id = msg.id.unwrap().to_hex();
        assert!(matches!(persist_chat_event(&ingest(msg, 5), &cid, &me.public_key()).await, Some(ChatPersist::New(_))));

        let reaction = chat::build_reaction_rumor(member.public_key(), &general, epoch, &msg_id, &member.public_key().to_hex(), super::super::kind::MESSAGE, "🔥", None, 6_000);
        assert!(persist_chat_event(&ingest(expired(&reaction), 6), &cid, &me.public_key()).await.is_none(), "an expired reaction is refused");
        let edit = chat::build_edit_rumor(member.public_key(), &general, epoch, &msg_id, "rewritten", &[], None, 7_000);
        assert!(persist_chat_event(&ingest(expired(&edit), 7), &cid, &me.public_key()).await.is_none(), "an expired edit is refused");
        {
            let st = crate::state::STATE.lock().await;
            let (_, held) = st.find_message(&msg_id).expect("the message is resident");
            assert!(held.reactions.is_empty(), "no reaction landed");
            assert_eq!(held.content, "permanent", "no edit landed");
        }
        // The same reaction, unexpired, lands: the refusal is the expiry's alone.
        assert!(matches!(persist_chat_event(&ingest(reaction, 6), &cid, &me.public_key()).await, Some(ChatPersist::Updated { .. })));

        let delete = chat::build_delete_rumor(member.public_key(), &general, epoch, &msg_id, super::super::kind::MESSAGE, 8_000, None);
        let outcome = persist_chat_event(&ingest(expired(&delete), 8), &cid, &me.public_key()).await;
        assert!(matches!(outcome, Some(ChatPersist::Removed { id, .. }) if id == msg_id), "an expired delete still erases");
    }

    #[tokio::test]
    async fn a_reaction_edit_or_unreact_lands_on_a_message_paged_out_of_memory() {
        use nostr_sdk::prelude::{Timestamp, UnsignedEvent};
        let (_tmp, _guard, me) = init();
        let relay = MemoryRelay::new();
        let community = service::create_community(&relay, "PagedOut", vec!["wss://r".into()], None).await.unwrap();
        let general = community.channels[0].id;
        let epoch = community.root_epoch;
        let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
        let group = super::super::derive::channel_group_key(&community.community_root, &general, epoch);
        let member = Keys::generate();
        let ingest = |rumor: UnsignedEvent, at: u64| {
            let (wrap, _) = chat::seal_chat_rumor(&rumor, &group, &member, Timestamp::from_secs(at), false).unwrap();
            chat::open_chat_event(&wrap, &group, &general, epoch).unwrap()
        };
        let page_out = || async {
            let mut st = crate::state::STATE.lock().await;
            st.chats.iter_mut().find(|c| c.id == cid).unwrap().messages.retain_newest(0);
        };

        let msg = chat::build_message_rumor(member.public_key(), &general, epoch, "hello", None, &[], vec![], 5_000);
        let msg_id = msg.id.unwrap().to_hex();
        assert!(matches!(persist_chat_event(&ingest(msg, 5), &cid, &me.public_key()).await, Some(ChatPersist::New(_))));

        page_out().await;
        let reaction = chat::build_reaction_rumor(member.public_key(), &general, epoch, &msg_id, &member.public_key().to_hex(), super::super::kind::MESSAGE, "🔥", None, 6_000);
        let reaction_id = reaction.id.unwrap().to_hex();
        assert!(matches!(persist_chat_event(&ingest(reaction, 6), &cid, &me.public_key()).await, Some(ChatPersist::Updated { .. })), "the reaction lands");

        page_out().await;
        let edit = chat::build_edit_rumor(member.public_key(), &general, epoch, &msg_id, "rewritten", &[], None, 7_000);
        assert!(matches!(persist_chat_event(&ingest(edit, 7), &cid, &me.public_key()).await, Some(ChatPersist::Updated { .. })), "the edit lands");

        page_out().await;
        let unreact = chat::build_delete_rumor(member.public_key(), &general, epoch, &reaction_id, super::super::kind::REACTION, 8_000, None);
        assert!(matches!(persist_chat_event(&ingest(unreact, 8), &cid, &me.public_key()).await, Some(ChatPersist::ReactionRemoved { .. })), "the un-react lands");

        let (_, stored) = crate::db::events::get_message_by_id(&msg_id).await.unwrap().unwrap();
        assert_eq!(stored.content, "rewritten");
        assert!(stored.reactions.is_empty());
    }

    #[tokio::test]
    async fn reactions_on_an_edited_paged_out_message_keep_its_original_under_local_encryption() {
        use nostr_sdk::prelude::{Timestamp, UnsignedEvent};
        struct Vault;
        impl Drop for Vault {
            fn drop(&mut self) {
                crate::state::ENCRYPTION_KEY.clear(&[]);
                crate::state::set_encryption_enabled(false);
            }
        }
        let (_tmp, _guard, me) = init();
        let _vault = Vault;
        crate::state::ENCRYPTION_KEY.set([0x5a; 32], &[]);
        crate::state::set_encryption_enabled(true);
        let relay = MemoryRelay::new();
        let community = service::create_community(&relay, "Sealed", vec!["wss://r".into()], None).await.unwrap();
        let general = community.channels[0].id;
        let epoch = community.root_epoch;
        let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
        let group = super::super::derive::channel_group_key(&community.community_root, &general, epoch);
        let member = Keys::generate();
        let ingest = |rumor: UnsignedEvent, at: u64| {
            let (wrap, _) = chat::seal_chat_rumor(&rumor, &group, &member, Timestamp::from_secs(at), false).unwrap();
            chat::open_chat_event(&wrap, &group, &general, epoch).unwrap()
        };
        let page_out = || async {
            crate::state::STATE.lock().await.chats.iter_mut().find(|c| c.id == cid).unwrap().messages.retain_newest(0);
        };
        let stored_content = |id: &str| {
            let conn = crate::db::get_db_connection_guard_static().unwrap();
            conn.query_row("SELECT content FROM events WHERE id = ?1", [id], |r| r.get::<_, String>(0)).unwrap()
        };
        let msg = chat::build_message_rumor(member.public_key(), &general, epoch, "hello", None, &[], vec![], 5_000);
        let msg_id = msg.id.unwrap().to_hex();
        let react = |emoji: &str, at: u64| {
            chat::build_reaction_rumor(member.public_key(), &general, epoch, &msg_id, &member.public_key().to_hex(), super::super::kind::MESSAGE, emoji, None, at)
        };
        assert!(matches!(persist_chat_event(&ingest(msg, 5), &cid, &me.public_key()).await, Some(ChatPersist::New(_))));
        let written = stored_content(&msg_id);
        let edit = chat::build_edit_rumor(member.public_key(), &general, epoch, &msg_id, "rewritten", &[], None, 6_000);
        assert!(persist_chat_event(&ingest(edit, 6), &cid, &me.public_key()).await.is_some());

        // Live: the target is brought back from the database for the reaction.
        page_out().await;
        let Some(ChatPersist::Updated { message, .. }) = persist_chat_event(&ingest(react("🔥", 7_000), 7), &cid, &me.public_key()).await else {
            panic!("the reaction lands");
        };
        assert_eq!(message.content, "rewritten", "brought back as its text, not its sealed row");

        // Catch-up: a page with a reaction, then that reaction revoked.
        page_out().await;
        let second = react("🎉", 8_000);
        let second_id = second.id.unwrap().to_hex();
        let unreact = chat::build_delete_rumor(member.public_key(), &general, epoch, &second_id, super::super::kind::REACTION, 9_000, None);
        let mut outcomes = Vec::new();
        for (rumor, at) in [(second, 8), (unreact, 9)] {
            let event = ingest(rumor, at);
            hydrate_target(&event, &cid).await;
            let mut st = crate::state::STATE.lock().await;
            outcomes.extend(apply_chat_to_state(&mut st, &event, &cid, &me.public_key()));
        }
        assert_eq!(outcomes.len(), 2, "the page reacts and un-reacts");
        persist_chat_page(&cid, &outcomes, &crate::db::current_session()).await;

        assert_eq!(stored_content(&msg_id), written, "the original row is never rewritten");
        assert_eq!(crate::crypto::maybe_decrypt_text(&written), "hello", "and was sealed once");
        let (_, back) = crate::db::events::get_message_by_id(&msg_id).await.unwrap().unwrap();
        assert_eq!(back.content, "rewritten");
        assert_eq!(back.edit_history.as_ref().unwrap()[0].content, "hello");
        assert_eq!(back.reactions.iter().map(|r| r.emoji.as_str()).collect::<Vec<_>>(), vec!["🔥"], "the revoked one is gone");
    }

    #[tokio::test]
    async fn the_typed_hooks_name_what_happened() {
        use nostr_sdk::prelude::{Timestamp, UnsignedEvent};
        #[derive(Default)]
        struct Typed(std::sync::Mutex<Vec<String>>);
        impl InboundEventHandler for Typed {
            fn on_reaction_added(&self, _c: &str, _m: &Message, r: &Reaction, at: u64) {
                self.0.lock().unwrap().push(format!("react {} {}", r.emoji, at % 100_000));
            }
            fn on_reaction_removed(&self, _c: &str, _m: &Message, _id: &str, _by: &str, _at: u64) {
                self.0.lock().unwrap().push("unreact".into());
            }
            fn on_message_edited(&self, _c: &str, m: &Message, _at: u64) {
                self.0.lock().unwrap().push(format!("edit {}", m.content));
            }
            fn on_message_removed(&self, _c: &str, _id: &str, by: Option<&str>, moderated: bool, _at: u64) {
                self.0.lock().unwrap().push(format!("removed {} {moderated}", &by.unwrap_or_default()[..5]));
            }
        }
        let (_tmp, _guard, me) = init();
        let relay = MemoryRelay::new();
        let community = service::create_community(&relay, "Typed", vec!["wss://r".into()], None).await.unwrap();
        let general = community.channels[0].id;
        let epoch = community.root_epoch;
        let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
        let group = super::super::derive::channel_group_key(&community.community_root, &general, epoch);
        let member = Keys::generate();
        let ingest = |rumor: UnsignedEvent, at: u64| {
            let (wrap, _) = chat::seal_chat_rumor(&rumor, &group, &member, Timestamp::from_secs(at), false).unwrap();
            chat::open_chat_event(&wrap, &group, &general, epoch).unwrap()
        };
        // Recent, so each is news; the reaction lands at a time the hook reports.
        let t0 = crate::clock::now_ms() / 100_000 * 100_000 - 100_000;
        let msg = chat::build_message_rumor(member.public_key(), &general, epoch, "hello", None, &[], vec![], t0 + 5_000);
        let msg_id = msg.id.unwrap().to_hex();
        let react = chat::build_reaction_rumor(member.public_key(), &general, epoch, &msg_id, &member.public_key().to_hex(), super::super::kind::MESSAGE, "🔥", None, t0 + 6_000);
        let react_id = react.id.unwrap().to_hex();
        let rumors = [
            (msg, t0 + 5_000),
            (react, t0 + 6_000),
            (chat::build_edit_rumor(member.public_key(), &general, epoch, &msg_id, "rewritten", &[], None, t0 + 7_000), t0 + 7_000),
            (chat::build_delete_rumor(member.public_key(), &general, epoch, &react_id, super::super::kind::REACTION, t0 + 8_000, None), t0 + 8_000),
            (chat::build_delete_rumor(member.public_key(), &general, epoch, &msg_id, super::super::kind::MESSAGE, t0 + 9_000, None), t0 + 9_000),
        ];
        let typed = Typed::default();
        for (rumor, at) in rumors {
            let event = ingest(rumor, at / 1000);
            let outcome = persist_chat_event(&event, &cid, &me.public_key()).await.expect("each applies");
            notify_chat_outcome(&typed, &cid, &event, outcome, false).await;
        }
        assert_eq!(*typed.0.lock().unwrap(), vec!["react 🔥 6000", "edit rewritten", "unreact", "removed npub1 false"]);
    }

    #[tokio::test]
    async fn a_listener_hears_a_caught_up_message_once_and_never_history() {
        use nostr_sdk::prelude::{Timestamp, UnsignedEvent};
        #[derive(Default)]
        struct Heard(std::sync::Mutex<Vec<(String, bool)>>);
        impl InboundEventHandler for Heard {
            fn on_community_message(&self, _c: &str, m: &Message, is_new: bool) {
                self.0.lock().unwrap().push((m.content.clone(), is_new));
            }
        }
        let (_tmp, _guard, me) = init();
        let relay = MemoryRelay::new();
        let community = service::create_community(&relay, "Gap", vec!["wss://r".into()], None).await.unwrap();
        let general = community.channels[0].id;
        let epoch = community.root_epoch;
        let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
        let group = super::super::derive::channel_group_key(&community.community_root, &general, epoch);
        let member = Keys::generate();
        let fetched = |rumor: UnsignedEvent, at_ms: u64| {
            let (wrap, _) = chat::seal_chat_rumor(&rumor, &group, &member, Timestamp::from_secs(at_ms / 1000), false).unwrap();
            service::FetchedEvent { event: chat::open_chat_event(&wrap, &group, &general, epoch).unwrap(), epoch, wrap: Some(wrap) }
        };
        let now = crate::clock::now_ms();
        let heard = std::sync::Arc::new(Heard::default());
        let _listening = crate::news::listen_for_test(heard.clone(), now - 600_000);

        // Sent ten minutes into an outage, then a week before listening began.
        let gap = chat::build_message_rumor(member.public_key(), &general, epoch, "sent during the gap", None, &[], vec![], now - 300_000);
        let old = chat::build_message_rumor(member.public_key(), &general, epoch, "last week", None, &[], vec![], now - 7 * 86_400_000);
        let page = vec![fetched(gap.clone(), now - 300_000), fetched(old, now - 7 * 86_400_000)];
        crate::VectorCore::v2_ingest_chat_page(&cid, me.public_key(), crate::db::current_session(), page).await;
        assert_eq!(*heard.0.lock().unwrap(), vec![("sent during the gap".to_string(), true)], "the catch-up delivers news, not history");

        // The live feed or a replay carries it again: already held, so not news twice.
        let again = fetched(gap, now - 300_000);
        assert!(persist_chat_event(&again.event, &cid, &me.public_key()).await.is_none());
        assert_eq!(heard.0.lock().unwrap().len(), 1);

        // Two catch-ups reading one page at once: each may think it stored it first.
        let racing = chat::build_message_rumor(member.public_key(), &general, epoch, "caught twice", None, &[], vec![], now - 200_000);
        let page = || vec![fetched(racing.clone(), now - 200_000)];
        let session = crate::db::current_session();
        tokio::join!(
            crate::VectorCore::v2_ingest_chat_page(&cid, me.public_key(), session.clone(), page()),
            crate::VectorCore::v2_ingest_chat_page(&cid, me.public_key(), session.clone(), page()),
        );
        let told = heard.0.lock().unwrap().iter().filter(|(text, news)| text == "caught twice" && *news).count();
        assert_eq!(told, 1, "told once, whichever stored it");
    }

    #[tokio::test]
    async fn a_deleted_message_stays_deleted_when_a_relay_serves_it_again() {
        use nostr_sdk::prelude::{Timestamp, UnsignedEvent};
        let (_tmp, _guard, me) = init();
        let relay = MemoryRelay::new();
        let community = service::create_community(&relay, "Gone", vec!["wss://r".into()], None).await.unwrap();
        let general = community.channels[0].id;
        let epoch = community.root_epoch;
        let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
        let group = super::super::derive::channel_group_key(&community.community_root, &general, epoch);
        let member = Keys::generate();
        let ingest = |rumor: UnsignedEvent, at: u64| {
            let (wrap, _) = chat::seal_chat_rumor(&rumor, &group, &member, Timestamp::from_secs(at), false).unwrap();
            chat::open_chat_event(&wrap, &group, &general, epoch).unwrap()
        };
        let msg = chat::build_message_rumor(member.public_key(), &general, epoch, "regret", None, &[], vec![], 5_000);
        let msg_id = msg.id.unwrap().to_hex();
        let original = ingest(msg, 5);
        assert!(matches!(persist_chat_event(&original, &cid, &me.public_key()).await, Some(ChatPersist::New(_))));
        let delete = chat::build_delete_rumor(member.public_key(), &general, epoch, &msg_id, super::super::kind::MESSAGE, 6_000, None);
        assert!(matches!(persist_chat_event(&ingest(delete, 6), &cid, &me.public_key()).await, Some(ChatPersist::Removed { .. })));

        // A restart forgets this session's set; the durable tombstone is what remains.
        crate::state::clear_message_tombstones();
        crate::state::seed_message_tombstones(crate::db::events::load_message_tombstones().unwrap());
        assert!(persist_chat_event(&original, &cid, &me.public_key()).await.is_none(), "the original, served again, stays gone");
        let page = [apply_chat_to_state(&mut *crate::state::STATE.lock().await, &original, &cid, &me.public_key())];
        assert!(page[0].is_none(), "and a catch-up page refuses it too");
        let at = crate::db::events::locate_message(&msg_id).unwrap();
        assert_eq!((at.chat, at.deleted), (None, true), "a link to it reads as deleted");
    }

    #[tokio::test]
    async fn a_guestbook_join_wrap_fires_presence() {
        let (_tmp, _guard, me) = init();
        let relay = MemoryRelay::new();
        // create_community publishes the owner's genesis Join to the guestbook.
        let community = service::create_community(&relay, "GB", vec!["wss://r".into()], None).await.unwrap();
        let gb = super::super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
        let q = crate::community::transport::Query { kinds: vec![stream::KIND_WRAP], authors: vec![gb.pk_hex()], ..Default::default() };
        let wraps = relay.fetch(&q, &community.relays).await.unwrap();

        let rec = Recorder::default();
        for w in &wraps {
            dispatch_wrap(w, &community, &me.public_key(), &rec);
        }
        let pres = rec.presence.lock().unwrap();
        assert_eq!(pres.len(), 1, "the owner's genesis Join fires one presence");
        assert!(pres[0].1, "it's a join");
        assert_eq!(pres[0].0, me.public_key().to_bech32().unwrap());
    }

    #[tokio::test]
    async fn v2_chat_events_persist_into_the_shared_store() {
        let (_tmp, _guard, me) = init();
        let relay = MemoryRelay::new();
        let community = service::create_community(&relay, "Persist", vec!["wss://r".into()], None).await.unwrap();
        let general = community.channels[0].id;
        let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
        let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);
        let me_hex = me.public_key().to_hex();

        let msg_id = service::send_message(&relay, &community, &general, "persist me").await.unwrap();
        service::send_reaction(&relay, &community, &general, &msg_id, &me_hex, super::super::kind::MESSAGE, "🔥", None).await.unwrap();

        // The SEND ECHO persisted both immediately — send-then-read works with no
        // listen loop (the INT-W3 contract).
        assert!(crate::db::events::event_exists(&msg_id).unwrap(), "the send echo persisted the message row");
        let reacted = {
            let st = crate::state::STATE.lock().await;
            st.find_message(&msg_id).map(|(_, m)| m.reactions.iter().any(|r| r.emoji == "🔥")).unwrap_or(false)
        };
        assert!(reacted, "the send echo aggregated the reaction onto the stored message");

        // The relay's copies of our own sends then arrive — every one dedups
        // against the echoed rows (no double rows, no re-fires).
        let q = crate::community::transport::Query { kinds: vec![stream::KIND_WRAP], authors: vec![group.pk_hex()], ..Default::default() };
        let wraps = relay.fetch(&q, &community.relays).await.unwrap();
        let mut events: Vec<ChatEvent> = wraps.iter().filter_map(|w| chat::open_chat_event(w, &group, &general, community.root_epoch).ok()).collect();
        events.sort_by_key(|e| e.opened().at_ms);
        assert!(!events.is_empty());
        for ev in &events {
            let outcome = {
                let mut st = crate::state::STATE.lock().await;
                apply_chat_to_state(&mut st, ev, &cid, &me.public_key())
            };
            assert!(outcome.is_none(), "the relay echo of an already-echoed send dedups");
        }
    }

    #[tokio::test]
    async fn a_v2_edit_persists_as_a_folded_edit_event() {
        let (_tmp, _guard, me) = init();
        let relay = MemoryRelay::new();
        let community = service::create_community(&relay, "Edit", vec!["wss://r".into()], None).await.unwrap();
        let general = community.channels[0].id;
        let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
        let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);

        let msg_id = service::send_message(&relay, &community, &general, "original").await.unwrap();
        service::send_edit(&relay, &community, &general, &msg_id, "edited!", &[]).await.unwrap();

        // Apply messages BEFORE their edits (a target must be resident to edit).
        let q = crate::community::transport::Query { kinds: vec![stream::KIND_WRAP], authors: vec![group.pk_hex()], ..Default::default() };
        let wraps = relay.fetch(&q, &community.relays).await.unwrap();
        let mut events: Vec<ChatEvent> = wraps.iter().filter_map(|w| chat::open_chat_event(w, &group, &general, community.root_epoch).ok()).collect();
        events.sort_by_key(|e| (!matches!(e, ChatEvent::Message { .. }), e.opened().at_ms));
        for ev in &events {
            let outcome = {
                let mut st = crate::state::STATE.lock().await;
                apply_chat_to_state(&mut st, ev, &cid, &me.public_key())
            };
            if let Some(o) = outcome {
                persist_chat(&cid, &o).await;
            }
        }

        let content = {
            let st = crate::state::STATE.lock().await;
            st.find_message(&msg_id).map(|(_, m)| m.content)
        };
        assert_eq!(content.as_deref(), Some("edited!"), "the edit applied to the stored message");
        let edit_id = events.iter().find_map(|e| matches!(e, ChatEvent::Edit { .. }).then(|| e.opened().rumor_id.to_hex())).unwrap();
        assert!(crate::db::events::event_exists(&edit_id).unwrap(), "the MESSAGE_EDIT event is persisted (folds on reload)");
    }

    /// Colour spans ride the message and its edit as tags, fold onto the resident
    /// message newest-edit-wins, and persist so a reload paints the same.
    #[tokio::test]
    async fn colour_spans_travel_with_messages_and_edits() {
        use crate::text_color::Effect;
        use crate::text_spans::{extract, to_nostr_tags, TextSpan};
        let (_tmp, _guard, me) = init();
        let relay = MemoryRelay::new();
        let community = service::create_community(&relay, "Colour", vec!["wss://r".into()], None).await.unwrap();
        let general = community.channels[0].id;
        let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
        let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);

        let (plain, spans) = extract("hi <rainbow>everyone</rainbow> at <t:0:R>!");
        let msg_id = service::send_chat_message(&relay, &community, &general, &plain, None, &[], to_nostr_tags(&spans).collect()).await.unwrap();
        let (edited, edit_spans) = extract("<color pink>bye</color> all");
        service::send_edit_tagged(&relay, &community, &general, &msg_id, &edited, &[], to_nostr_tags(&edit_spans).collect()).await.unwrap();

        let q = crate::community::transport::Query { kinds: vec![stream::KIND_WRAP], authors: vec![group.pk_hex()], ..Default::default() };
        let wraps = relay.fetch(&q, &community.relays).await.unwrap();
        let mut events: Vec<ChatEvent> = wraps.iter().filter_map(|w| chat::open_chat_event(w, &group, &general, community.root_epoch).ok()).collect();
        events.sort_by_key(|e| (!matches!(e, ChatEvent::Message { .. }), e.opened().at_ms));

        let sent = events.iter().find(|e| matches!(e, ChatEvent::Message { .. })).unwrap().opened();
        assert_eq!(sent.rumor.content, "hi everyone at 1970-01-01 00:00 UTC!", "the markup never reaches the wire");
        let wire = crate::text_spans::from_tags(sent.rumor.tags.iter(), &sent.rumor.content);
        assert_eq!(wire.len(), 2);
        assert!(matches!(&wire[0], TextSpan::Color(c) if (c.from, c.to, c.effect) == (3, 11, Effect::Rainbow)));
        assert!(matches!(&wire[1], TextSpan::Time(t) if (t.from, t.to, t.unix, t.style) == (15, 35, 0, 'R')));
        let built = chat_message_to_message(sent, &None, &[], &me.public_key());
        assert_eq!(built.text_spans, wire, "the inbound message carries the wire's spans");

        for ev in &events {
            let o = {
                let mut st = crate::state::STATE.lock().await;
                apply_chat_to_state(&mut st, ev, &cid, &me.public_key())
            };
            if let Some(o) = o { persist_chat(&cid, &o).await; }
        }
        let folded = crate::state::STATE.lock().await.find_message(&msg_id).map(|(_, m)| m).unwrap();
        assert_eq!(folded.content, "bye all");
        assert_eq!(folded.text_spans, edit_spans, "the edit's spans replace the original's");

        let chat_db = crate::db::id_cache::get_chat_id_by_identifier(&cid).unwrap();
        let reloaded = crate::db::events::get_message_views(chat_db, 50, 0).await.unwrap()
            .into_iter().find(|m| m.id == msg_id).expect("reloaded");
        assert_eq!(reloaded.content, "bye all");
        assert_eq!(reloaded.text_spans, edit_spans, "the reload fold reads the edit's spans");
    }

    /// An edit's custom emoji must survive the whole span: the wire (NIP-30 tags
    /// on the 3302 rumor), the live fold (the message's emoji set), and the
    /// persisted MESSAGE_EDIT row (the reload fold re-reads tags from there).
    /// A receiver has no pack to fall back on — the event is all they get.
    #[tokio::test]
    async fn an_edit_carries_its_custom_emoji_to_peers_and_across_restart() {
        let (_tmp, _guard, me) = init();
        let relay = MemoryRelay::new();
        let community = service::create_community(&relay, "EditEmoji", vec!["wss://r".into()], None).await.unwrap();
        let general = community.channels[0].id;
        let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
        let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);

        let msg_id = service::send_message(&relay, &community, &general, "plain").await.unwrap();
        service::send_edit(
            &relay, &community, &general, &msg_id,
            "now with :vectorlove:",
            &[("vectorlove", "https://cdn.example/vectorlove.webp")],
        ).await.unwrap();

        let q = crate::community::transport::Query { kinds: vec![stream::KIND_WRAP], authors: vec![group.pk_hex()], ..Default::default() };
        let wraps = relay.fetch(&q, &community.relays).await.unwrap();
        let mut events: Vec<ChatEvent> = wraps.iter().filter_map(|w| chat::open_chat_event(w, &group, &general, community.root_epoch).ok()).collect();
        events.sort_by_key(|e| (!matches!(e, ChatEvent::Message { .. }), e.opened().at_ms));

        let wire_emoji = events.iter().find_map(|e| match e {
            ChatEvent::Edit { emoji, .. } => Some(emoji.clone()),
            _ => None,
        }).expect("the edit decodes");
        assert_eq!(
            wire_emoji,
            vec![("vectorlove".to_string(), "https://cdn.example/vectorlove.webp".to_string())],
            "the 3302 rumor carries the NIP-30 pair on the wire"
        );

        for ev in &events {
            let outcome = {
                let mut st = crate::state::STATE.lock().await;
                apply_chat_to_state(&mut st, ev, &cid, &me.public_key())
            };
            if let Some(o) = outcome {
                persist_chat(&cid, &o).await;
            }
        }

        let folded = {
            let st = crate::state::STATE.lock().await;
            st.find_message(&msg_id).map(|(_, m)| m.emoji_tags.clone())
        }.expect("message resident");
        assert_eq!(folded.len(), 1, "the fold adopted the edit's emoji set");
        assert_eq!(folded[0].shortcode, "vectorlove");
        assert_eq!(folded[0].url, "https://cdn.example/vectorlove.webp");

        let edit_id = events.iter().find_map(|e| matches!(e, ChatEvent::Edit { .. }).then(|| e.opened().rumor_id.to_hex())).unwrap();
        let (_wrap, stored_tags) = crate::db::events::get_event_wrap_context(&edit_id)
            .unwrap()
            .expect("the MESSAGE_EDIT row is persisted");
        let restored = crate::types::EmojiTag::extract_from_stored(&stored_tags);
        assert_eq!(restored.len(), 1, "the MESSAGE_EDIT row carries the tags the reload fold reads");
        assert_eq!(restored[0].shortcode, "vectorlove");
    }

    #[tokio::test]
    async fn a_reaction_after_a_rekey_aggregates_onto_a_prior_epoch_message() {
        // Sync stability across a rekey: a message written at epoch 0 and a reaction
        // to it written at epoch 1 (its wrap sealed + bound under the NEW epoch key)
        // must still aggregate — STATE keys by rumor id, not epoch, so a reaction to
        // pre-refound history lands. The reaction's OWN binding is epoch 1; the
        // target's is epoch 0.
        use nostr_sdk::prelude::Timestamp;
        let (_tmp, _guard, me) = init();
        let relay = MemoryRelay::new();
        let community = service::create_community(&relay, "Rekeyed", vec!["wss://r".into()], None).await.unwrap();
        let general = community.channels[0].id;
        let cid = crate::simd::hex::bytes_to_hex_32(&general.0);

        // Epoch-0 message, opened under the epoch-0 public key, persisted.
        let member = Keys::generate();
        let g0 = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);
        let msg = chat::build_message_rumor(member.public_key(), &general, community.root_epoch, "before the rekey", None, &[], vec![], 5_000);
        let msg_id = msg.id.unwrap().to_hex();
        let (mw, _) = chat::seal_chat_rumor(&msg, &g0, &member, Timestamp::from_secs(5), false).unwrap();
        let ev = chat::open_chat_event(&mw, &g0, &general, community.root_epoch).unwrap();
        assert!(matches!(persist_chat_event(&ev, &cid, &me.public_key()).await, Some(ChatPersist::New(_))));

        // Epoch-1 reaction (same root, next epoch → a distinct channel key) to that
        // epoch-0 message, opened under the epoch-1 key.
        let next = crate::community::Epoch(community.root_epoch.0 + 1);
        let g1 = super::super::derive::channel_group_key(&community.community_root, &general, next);
        let reaction = chat::build_reaction_rumor(member.public_key(), &general, next, &msg_id, &member.public_key().to_hex(), super::super::kind::MESSAGE, "🎉", None, 6_000);
        let (rw, _) = chat::seal_chat_rumor(&reaction, &g1, &member, Timestamp::from_secs(6), false).unwrap();
        let rev = chat::open_chat_event(&rw, &g1, &general, next).unwrap();
        let outcome = persist_chat_event(&rev, &cid, &me.public_key()).await;
        assert!(matches!(outcome, Some(ChatPersist::Updated { .. })), "the cross-epoch reaction updates the target");

        let reaction_author = {
            let st = crate::state::STATE.lock().await;
            st.find_message(&msg_id)
                .and_then(|(_, m)| m.reactions.iter().find(|r| r.emoji == "🎉").map(|r| r.author_id.clone()))
        };
        let author = reaction_author.expect("the epoch-1 reaction aggregated onto the epoch-0 message");
        // npub, never hex: the frontend resolves the reactor's profile and detects
        // "my reaction" by comparing against the user's npub.
        assert_eq!(author, member.public_key().to_bech32().unwrap(), "reaction author is stored as bech32");
    }

    #[tokio::test]
    async fn an_un_react_removes_the_reaction_for_receivers_and_only_for_its_reactor() {
        use nostr_sdk::prelude::Timestamp;
        let (_tmp, _guard, me) = init();
        let relay = MemoryRelay::new();
        let community = service::create_community(&relay, "UnReact", vec!["wss://r".into()], None).await.unwrap();
        let general = community.channels[0].id;
        let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
        let (secret, epoch) = community.channel_secret(&community.channels[0]);
        let group = super::super::derive::channel_group_key(&secret, &general, epoch);

        // A message, then the member's reaction to it.
        let member = Keys::generate();
        let msg = chat::build_message_rumor(member.public_key(), &general, epoch, "react to me", None, &[], vec![], 5_000);
        let msg_id = msg.id.unwrap().to_hex();
        let (mw, _) = chat::seal_chat_rumor(&msg, &group, &member, Timestamp::from_secs(5), false).unwrap();
        let ev = chat::open_chat_event(&mw, &group, &general, epoch).unwrap();
        assert!(matches!(persist_chat_event(&ev, &cid, &me.public_key()).await, Some(ChatPersist::New(_))));

        let reaction = chat::build_reaction_rumor(member.public_key(), &general, epoch, &msg_id, &member.public_key().to_hex(), super::super::kind::MESSAGE, "🔥", None, 6_000);
        let reaction_id = reaction.id.unwrap().to_hex();
        let (rw, _) = chat::seal_chat_rumor(&reaction, &group, &member, Timestamp::from_secs(6), false).unwrap();
        let rev = chat::open_chat_event(&rw, &group, &general, epoch).unwrap();
        assert!(matches!(persist_chat_event(&rev, &cid, &me.public_key()).await, Some(ChatPersist::Updated { .. })));

        // A NON-reactor's delete targeting the reaction is dropped outright.
        let outsider = Keys::generate();
        let forged = chat::build_delete_rumor(outsider.public_key(), &general, epoch, &reaction_id, super::super::kind::MESSAGE, 7_000, None);
        let (fw, _) = chat::seal_chat_rumor(&forged, &group, &outsider, Timestamp::from_secs(7), false).unwrap();
        let fev = chat::open_chat_event(&fw, &group, &general, epoch).unwrap();
        assert!(persist_chat_event(&fev, &cid, &me.public_key()).await.is_none(), "only the reactor revokes their reaction");

        // The REACTOR's delete removes it: STATE chip gone, kind-7 row gone
        // (a lingering row would resurrect the chip on the next load), parent intact.
        let revoke = chat::build_delete_rumor(member.public_key(), &general, epoch, &reaction_id, super::super::kind::MESSAGE, 8_000, None);
        let (vw, _) = chat::seal_chat_rumor(&revoke, &group, &member, Timestamp::from_secs(8), false).unwrap();
        let vev = chat::open_chat_event(&vw, &group, &general, epoch).unwrap();
        assert!(matches!(persist_chat_event(&vev, &cid, &me.public_key()).await, Some(ChatPersist::ReactionRemoved { .. })));
        let (has_reaction, parent_alive) = {
            let st = crate::state::STATE.lock().await;
            (
                st.find_reaction(&reaction_id).is_some(),
                st.find_message(&msg_id).is_some(),
            )
        };
        assert!(!has_reaction, "the chip is gone from STATE");
        assert!(parent_alive, "the parent message survives an un-react");
        assert!(!crate::db::events::event_exists(&reaction_id).unwrap(), "the kind-7 row is deleted");
    }

    #[tokio::test]
    async fn a_guestbook_join_fires_presence_with_its_real_rumor_id() {
        use nostr_sdk::prelude::Timestamp;
        use std::sync::Mutex as StdMutex;
        let (_tmp, _guard, me) = init();
        let relay = MemoryRelay::new();
        let community = service::create_community(&relay, "Pres", vec!["wss://r".into()], None).await.unwrap();

        #[derive(Default)]
        struct Capture(StdMutex<Vec<(String, bool, String)>>);
        impl InboundEventHandler for Capture {
            fn on_community_presence(&self, p: &crate::Presence<'_>) {
                self.0.lock().unwrap().push((p.npub.into(), p.joined, p.event_id.into()));
            }
        }

        let member = Keys::generate();
        let gb = super::super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
        let rumor = guestbook::build_join_rumor(member.public_key(), None, 5_000);
        let (wrap, _) = super::super::guestbook::seal_guestbook_rumor(&rumor, &gb, &member, Timestamp::from_secs(5)).unwrap();
        let expected_id = rumor.id.unwrap().to_hex();

        let cap = Capture::default();
        let out = dispatch_wrap(&wrap, &community, &me.public_key(), &cap);
        assert!(matches!(out, DispatchedV2::Presence { joined: true, .. }));
        let seen = cap.0.lock().unwrap().clone();
        assert_eq!(seen.len(), 1);
        assert_eq!(seen[0].0, member.public_key().to_bech32().unwrap());
        // The REAL rumor id keys the line — an empty id would collapse every
        // distinct join into one dedup slot (first wins, the rest vanish).
        assert_eq!(seen[0].2, expected_id, "presence carries the join's own rumor id");
    }

    #[tokio::test]
    async fn a_join_line_goes_where_the_system_channel_says() {
        use nostr_sdk::prelude::Timestamp;
        use std::sync::Mutex as StdMutex;
        let (_tmp, _guard, me) = init();
        let relay = MemoryRelay::new();
        let community = service::create_community(&relay, "Lines", vec!["wss://r".into()], None).await.unwrap();
        let welcome = service::create_public_channel(&relay, &community, "welcome").await.unwrap();
        let mut community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let general = crate::simd::hex::bytes_to_hex_32(&community.channels.iter().find(|c| c.name == "general").unwrap().id.0);

        #[derive(Default)]
        struct Capture(StdMutex<Vec<(String, String, bool)>>);
        impl InboundEventHandler for Capture {
            fn on_community_presence(&self, p: &crate::Presence<'_>) {
                self.0.lock().unwrap().push((p.community_id.into(), p.channel_id.into(), p.shown));
            }
        }
        let gb = super::super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
        let join = |at: u64| {
            let member = Keys::generate();
            let rumor = guestbook::build_join_rumor(member.public_key(), None, at);
            super::super::guestbook::seal_guestbook_rumor(&rumor, &gb, &member, Timestamp::from_secs(at / 1000)).unwrap().0
        };
        let set = |c: &mut CommunityV2, ch: Option<&crate::community::ChannelId>| {
            let mut meta = c.metadata();
            super::super::community::set_system_channel_in(&mut meta, ch);
            c.meta_custom = meta.custom;
        };

        let cap = Capture::default();
        set(&mut community, Some(&welcome));
        dispatch_wrap(&join(5_000), &community, &me.public_key(), &cap);
        set(&mut community, None);
        dispatch_wrap(&join(6_000), &community, &me.public_key(), &cap);
        let cid = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let seen = cap.0.lock().unwrap().clone();
        assert_eq!(seen, vec![
            (cid.clone(), crate::simd::hex::bytes_to_hex_32(&welcome.0), true),
            (cid, general, false),
        ], "the chosen channel shows it; off keeps it, unseen, in the default");
    }

    #[tokio::test]
    async fn a_guestbook_kick_dispatches_its_target_and_raises_no_presence_line() {
        // Routing regression: a Kick used to fall to `Ignored`, so realtime dropped it
        // and the target never left anyone's memberlist (nor their own community).
        use nostr_sdk::prelude::Timestamp;
        use std::sync::Mutex as StdMutex;
        let (_tmp, _guard, me) = init();
        let relay = MemoryRelay::new();
        let community = service::create_community(&relay, "Kicks", vec!["wss://r".into()], None).await.unwrap();

        #[derive(Default)]
        struct Capture(StdMutex<usize>);
        impl InboundEventHandler for Capture {
            fn on_community_presence(&self, _p: &crate::Presence<'_>) {
                *self.0.lock().unwrap() += 1;
            }
        }

        let target = Keys::generate();
        let gb = super::super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
        let rumor = guestbook::build_kick_rumor(me.public_key(), target.public_key(), None, 5_000);
        let (wrap, _) = super::super::guestbook::seal_guestbook_rumor(&rumor, &gb, &me, Timestamp::from_secs(5)).unwrap();

        let cap = Capture::default();
        let out = dispatch_wrap(&wrap, &community, &me.public_key(), &cap);
        match out {
            DispatchedV2::Kick { target: t, .. } => assert_eq!(t, target.public_key(), "the kick names its target"),
            other => panic!("a Kick must reach the store, got {other:?}"),
        }
        // A kick shapes the memberlist, not the feed.
        assert_eq!(*cap.0.lock().unwrap(), 0, "a kick raises no presence line");
    }

    #[tokio::test]
    async fn a_webxdc_peer_ad_fires_the_shared_handler_and_own_echo_drops() {
        use nostr_sdk::prelude::Timestamp;
        use std::sync::Mutex as StdMutex;
        let (_tmp, _guard, me) = init();
        let relay = MemoryRelay::new();
        let community = service::create_community(&relay, "XDC", vec!["wss://r".into()], None).await.unwrap();
        let general = community.channels[0].id;

        #[derive(Default)]
        struct Capture(StdMutex<Vec<(String, String, Option<String>)>>);
        impl InboundEventHandler for Capture {
            fn on_community_webxdc(&self, _chat_id: &str, npub: &str, topic_id: &str, node_addr: Option<&str>, _event_id: &str, _created_at: u64) {
                self.0.lock().unwrap().push((npub.into(), topic_id.into(), node_addr.map(String::from)));
            }
        }

        let topic = "B".repeat(52);
        let content = crate::webxdc::peer_signal_content(&topic, Some("iroh:node/xyz"));
        let (secret, epoch) = community.channel_secret(&community.channels[0]);
        let group = super::super::derive::channel_group_key(&secret, &general, epoch);

        // A PEER's ad fires the shared handler surface.
        let peer = Keys::generate();
        let rumor = chat::build_webxdc_rumor(peer.public_key(), &general, epoch, &content, vec![], 5_000);
        let (wrap, _) = chat::seal_chat_rumor(&rumor, &group, &peer, Timestamp::from_secs(5), false).unwrap();
        let cap = Capture::default();
        let out = dispatch_wrap(&wrap, &community, &me.public_key(), &cap);
        assert!(matches!(out, DispatchedV2::Ignored), "fired inline, nothing to persist v2-side");
        let seen = cap.0.lock().unwrap().clone();
        assert_eq!(seen.len(), 1);
        assert_eq!(seen[0].0, peer.public_key().to_bech32().unwrap());
        assert_eq!(seen[0].1, topic);
        assert_eq!(seen[0].2.as_deref(), Some("iroh:node/xyz"));

        // Our OWN echo never re-fires — the local realtime layer tracks itself.
        let own = chat::build_webxdc_rumor(me.public_key(), &general, epoch, &content, vec![], 6_000);
        let (own_wrap, _) = chat::seal_chat_rumor(&own, &group, &me, Timestamp::from_secs(6), false).unwrap();
        let cap2 = Capture::default();
        dispatch_wrap(&own_wrap, &community, &me.public_key(), &cap2);
        assert!(cap2.0.lock().unwrap().is_empty(), "own-device echo drops");
    }

    #[tokio::test]
    async fn a_v2_message_with_an_imeta_attachment_surfaces_as_an_attachment() {
        use nostr_sdk::prelude::Timestamp;
        let (_tmp, _guard, me) = init();
        let relay = MemoryRelay::new();
        let community = service::create_community(&relay, "Files", vec!["wss://r".into()], None).await.unwrap();
        let general = community.channels[0].id;
        let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
        let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);

        // Build a valid NIP-92 imeta tag via the same encoder the v2 file pipeline
        // uses, so the round-trip mirrors production exactly.
        let attachment = crate::types::Attachment {
            id: "a".repeat(64),
            key: "0".repeat(64),
            nonce: "1".repeat(32),
            extension: "png".into(),
            name: "photo.png".into(),
            url: "https://blossom.example/abc".into(),
            path: String::new(),
            size: 4096,
            img_meta: None,
            downloading: false,
            downloaded: false, verified: false, resident: false,
            webxdc_topic: None,
            group_id: None,
            original_hash: Some("b".repeat(64)),
            fallback_urls: Vec::new(),
        };
        let imeta = crate::community::attachments::attachment_to_imeta(&attachment);
        let member = Keys::generate();
        let rumor = chat::build_message_rumor(member.public_key(), &general, community.root_epoch, "here's a file", None, &[], vec![imeta], 5_000);
        let (wrap, _) = chat::seal_chat_rumor(&rumor, &group, &member, Timestamp::from_secs(5), false).unwrap();
        let ev = chat::open_chat_event(&wrap, &group, &general, community.root_epoch).unwrap();

        let outcome = persist_chat_event(&ev, &cid, &me.public_key()).await;
        let Some(ChatPersist::New(msg)) = outcome else {
            panic!("the file message persists as new");
        };
        assert_eq!(msg.attachments.len(), 1, "the imeta tag parsed into one attachment");
        let att = &msg.attachments[0];
        assert!(att.url.contains("blossom.example"), "attachment url carried through: {}", att.url);
        assert_eq!(att.extension, "png", "extension carried through");
    }

    #[tokio::test]
    async fn a_banned_members_every_chat_event_is_dropped_on_sight() {
        // CORD-04 §4: a banned npub vanishes — message, reaction, edit, delete,
        // typing, and presence alike. Severance only cuts their READ; this fold
        // gate is what makes the ban hold against old-epoch keys they still have.
        use nostr_sdk::prelude::Timestamp;
        let (_tmp, _guard, me) = init();
        let relay = MemoryRelay::new();
        let community = service::create_community(&relay, "BanGate", vec!["wss://r".into()], None).await.unwrap();
        let general = community.channels[0].id;
        let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);
        let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);
        let rogue = Keys::generate();

        // Pre-ban: the rogue's message folds like anyone's.
        let m1 = chat::build_message_rumor(rogue.public_key(), &general, community.root_epoch, "pre-ban", None, &[], vec![], 5_000);
        let m1_id = m1.id.unwrap().to_hex();
        let (w1, _) = chat::seal_chat_rumor(&m1, &group, &rogue, Timestamp::from_secs(5), false).unwrap();
        let ev = chat::open_chat_event(&w1, &group, &general, community.root_epoch).unwrap();
        assert!(matches!(persist_chat_event(&ev, &cid, &me.public_key()).await, Some(ChatPersist::New(_))));

        // The ban lands (the fold's persisted banlist).
        crate::db::community::set_community_banlist(&cid_hex, &[rogue.public_key().to_hex()], 1_000).unwrap();

        // Post-ban: every kind they author drops.
        let m2 = chat::build_message_rumor(rogue.public_key(), &general, community.root_epoch, "post-ban", None, &[], vec![], 6_000);
        let (w2, _) = chat::seal_chat_rumor(&m2, &group, &rogue, Timestamp::from_secs(6), false).unwrap();
        let ev = chat::open_chat_event(&w2, &group, &general, community.root_epoch).unwrap();
        assert!(persist_chat_event(&ev, &cid, &me.public_key()).await.is_none(), "a banned message is dropped");

        let edit = chat::build_edit_rumor(rogue.public_key(), &general, community.root_epoch, &m1_id, "rewritten", &[], None, 7_000);
        let (we, _) = chat::seal_chat_rumor(&edit, &group, &rogue, Timestamp::from_secs(7), false).unwrap();
        let ev = chat::open_chat_event(&we, &group, &general, community.root_epoch).unwrap();
        assert!(persist_chat_event(&ev, &cid, &me.public_key()).await.is_none(), "a banned edit is dropped");

        let del = chat::build_delete_rumor(rogue.public_key(), &general, community.root_epoch, &m1_id, super::super::kind::MESSAGE, 8_000, None);
        let (wd, _) = chat::seal_chat_rumor(&del, &group, &rogue, Timestamp::from_secs(8), false).unwrap();
        let ev = chat::open_chat_event(&wd, &group, &general, community.root_epoch).unwrap();
        assert!(persist_chat_event(&ev, &cid, &me.public_key()).await.is_none(), "a banned delete is dropped");
        assert!(
            crate::state::STATE.lock().await.find_message(&m1_id).is_some(),
            "their pre-ban message survives their own post-ban delete"
        );

        // Typing + presence fire inline — the dispatcher's own gate covers them.
        let rec = Recorder::default();
        let typ = chat::build_typing_rumor(rogue.public_key(), &general, community.root_epoch, 9_000);
        let (wt, _) = chat::seal_chat_rumor(&typ, &group, &rogue, Timestamp::from_secs(9), true).unwrap();
        assert!(matches!(dispatch_wrap(&wt, &community, &me.public_key(), &rec), DispatchedV2::Ignored));
        // A banned member's Join draws no presence line but still dispatches for
        // STORAGE: the fold subtracts the banlist reversibly, so an unban can
        // resurrect a Join that legally raced the ban window — a store-side drop
        // would eat it forever.
        let gb = super::super::derive::guestbook_group_key(&community.community_root, community.id(), community.root_epoch);
        let join = guestbook::build_join_rumor(rogue.public_key(), None, 10_000);
        let (wj, _) = guestbook::seal_guestbook_rumor(&join, &gb, &rogue, Timestamp::from_secs(10)).unwrap();
        assert!(matches!(dispatch_wrap(&wj, &community, &me.public_key(), &rec), DispatchedV2::Presence { joined: true, .. }));
        assert!(rec.presence.lock().unwrap().is_empty(), "no presence callback for a banned join");

        // An innocent author still folds normally.
        let innocent = Keys::generate();
        let m3 = chat::build_message_rumor(innocent.public_key(), &general, community.root_epoch, "innocent", None, &[], vec![], 11_000);
        let (w3, _) = chat::seal_chat_rumor(&m3, &group, &innocent, Timestamp::from_secs(11), false).unwrap();
        let ev = chat::open_chat_event(&w3, &group, &general, community.root_epoch).unwrap();
        assert!(matches!(persist_chat_event(&ev, &cid, &me.public_key()).await, Some(ChatPersist::New(_))));
    }

    #[tokio::test]
    async fn my_own_typing_from_another_client_never_paints_me_as_typing() {
        use nostr_sdk::prelude::Timestamp;
        let (_tmp, _guard, me) = init();
        let relay = MemoryRelay::new();
        let community = service::create_community(&relay, "Typing", vec!["wss://r".into()], None).await.unwrap();
        let general = community.channels[0].id;
        let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
        let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);
        let rec = Recorder::default();

        // A second client of OURS (same key, its own wrap id — so the send-side
        // wrap dedup can't catch it) signals typing.
        let mine = chat::build_typing_rumor(me.public_key(), &general, community.root_epoch, 5_000);
        let (wm, _) = chat::seal_chat_rumor(&mine, &group, &me, Timestamp::from_secs(5), true).unwrap();
        assert!(
            matches!(dispatch_wrap(&wm, &community, &me.public_key(), &rec), DispatchedV2::Ignored),
            "our own typing signal is not someone typing at us"
        );
        assert!(rec.typing.lock().unwrap().is_empty(), "no typing callback for our own signal");

        // Someone else typing still lands.
        let peer = Keys::generate();
        let theirs = chat::build_typing_rumor(peer.public_key(), &general, community.root_epoch, 6_000);
        let (wt, _) = chat::seal_chat_rumor(&theirs, &group, &peer, Timestamp::from_secs(6), true).unwrap();
        assert!(matches!(dispatch_wrap(&wt, &community, &me.public_key(), &rec), DispatchedV2::Typing { .. }));
        let got = rec.typing.lock().unwrap();
        assert_eq!(got.len(), 1, "exactly the peer's signal fired");
        assert_eq!(got[0].0, cid);
        assert_eq!(got[0].1, peer.public_key().to_bech32().unwrap());
    }

    #[tokio::test]
    async fn an_armada_threaded_reply_persists_and_fires_as_an_inline_reply() {
        use nostr_sdk::prelude::Timestamp;
        let (_tmp, _guard, me) = init();
        let relay = MemoryRelay::new();
        let community = service::create_community(&relay, "Thread", vec!["wss://r".into()], None).await.unwrap();
        let general = community.channels[0].id;
        let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
        let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);

        // A member posts a root message, then a kind-1111 threaded reply to it
        // (the shape Armada sends).
        let member = Keys::generate();
        let root = chat::build_message_rumor(member.public_key(), &general, community.root_epoch, "thread root", None, &[], vec![], 5_000);
        let root_id = root.id.unwrap().to_hex();
        let (rw, _) = chat::seal_chat_rumor(&root, &group, &member, Timestamp::from_secs(5), false).unwrap();
        let reply = chat::build_comment_rumor(
            member.public_key(),
            &general,
            community.root_epoch,
            "thread reply",
            &root_id,
            super::super::kind::MESSAGE,
            &member.public_key().to_hex(),
            None,
            &[],
            6_000,
        );
        let reply_id = reply.id.unwrap().to_hex();
        let (tw, _) = chat::seal_chat_rumor(&reply, &group, &member, Timestamp::from_secs(6), false).unwrap();

        for w in [&rw, &tw] {
            let ev = chat::open_chat_event(w, &group, &general, community.root_epoch).unwrap();
            let outcome = persist_chat_event(&ev, &cid, &me.public_key()).await;
            assert!(matches!(outcome, Some(ChatPersist::New(_))), "both persist as new messages");
        }
        // The reply row carries its parent as inline reply context, resolved
        // from the persisted root.
        let held = {
            let st = crate::state::STATE.lock().await;
            st.find_message(&reply_id).map(|(_, m)| m)
        }
        .expect("the threaded reply is resident");
        assert_eq!(held.replied_to, root_id, "the immediate parent is the reply context");
        assert_eq!(held.content, "thread reply");

        // Its author deletes it — target kind 1111 (the delete e/k grammar).
        let del = chat::build_delete_rumor(member.public_key(), &general, community.root_epoch, &reply_id, super::super::kind::COMMENT, 7_000, None);
        let (dw, _) = chat::seal_chat_rumor(&del, &group, &member, Timestamp::from_secs(7), false).unwrap();
        let ev = chat::open_chat_event(&dw, &group, &general, community.root_epoch).unwrap();
        let outcome = persist_chat_event(&ev, &cid, &me.public_key()).await;
        assert!(matches!(outcome, Some(ChatPersist::Removed { id, .. }) if id == reply_id), "the author's delete removes their thread reply");
    }

    #[tokio::test]
    async fn an_edit_replay_never_refires() {
        use nostr_sdk::prelude::Timestamp;
        let (_tmp, _guard, me) = init();
        let relay = MemoryRelay::new();
        let community = service::create_community(&relay, "EditReplay", vec!["wss://r".into()], None).await.unwrap();
        let general = community.channels[0].id;
        let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
        let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);

        // Another member posts, then edits their own message.
        let member = Keys::generate();
        let msg = chat::build_message_rumor(member.public_key(), &general, community.root_epoch, "v1 text", None, &[], vec![], 5_000);
        let msg_id = msg.id.unwrap().to_hex();
        let (mw, _) = chat::seal_chat_rumor(&msg, &group, &member, Timestamp::from_secs(5), false).unwrap();
        let edit = chat::build_edit_rumor(member.public_key(), &general, community.root_epoch, &msg_id, "v2 text", &[], None, 6_000);
        let (ew, _) = chat::seal_chat_rumor(&edit, &group, &member, Timestamp::from_secs(6), false).unwrap();
        for w in [&mw, &ew] {
            if let Ok(ev) = chat::open_chat_event(w, &group, &general, community.root_epoch) {
                let _ = persist_chat_event(&ev, &cid, &me.public_key()).await;
            }
        }

        // A RE-WRAP of the same signed EDIT (fresh outer id) must not re-fire: the
        // MESSAGE_EDIT row dedups it, exactly like the other three chat kinds.
        let (replay, _) = chat::seal_chat_rumor(&edit, &group, &member, Timestamp::from_secs(7), false).unwrap();
        assert_ne!(replay.id, ew.id, "a re-wrap is a distinct outer event");
        let ev = chat::open_chat_event(&replay, &group, &general, community.root_epoch).unwrap();
        assert!(
            persist_chat_event(&ev, &cid, &me.public_key()).await.is_none(),
            "a replayed edit yields no outcome (no handler re-fire)"
        );
    }

    #[tokio::test]
    async fn a_forged_edit_from_a_non_author_is_ignored() {
        // Author-scoping on edits (the counterpart to the forged-delete guard): a
        // member (holds the channel key) forges an EDIT of someone else's message.
        // It must not rewrite the content.
        use nostr_sdk::prelude::Timestamp;
        let (_tmp, _guard, me) = init();
        let relay = MemoryRelay::new();
        let community = service::create_community(&relay, "EditGuard", vec!["wss://r".into()], None).await.unwrap();
        let general = community.channels[0].id;
        let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
        let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);

        // The real author posts a message.
        let author = Keys::generate();
        let msg = chat::build_message_rumor(author.public_key(), &general, community.root_epoch, "original", None, &[], vec![], 5_000);
        let msg_id = msg.id.unwrap().to_hex();
        let (mw, _) = chat::seal_chat_rumor(&msg, &group, &author, Timestamp::from_secs(5), false).unwrap();
        let ev = chat::open_chat_event(&mw, &group, &general, community.root_epoch).unwrap();
        persist_chat_event(&ev, &cid, &me.public_key()).await;

        // A stranger (member, holds the key) forges an edit of the author's message.
        let stranger = Keys::generate();
        let edit = chat::build_edit_rumor(stranger.public_key(), &general, community.root_epoch, &msg_id, "TAMPERED", &[], None, 6_000);
        let (ew, _) = chat::seal_chat_rumor(&edit, &group, &stranger, Timestamp::from_secs(6), false).unwrap();
        let ev = chat::open_chat_event(&ew, &group, &general, community.root_epoch).unwrap();
        assert!(persist_chat_event(&ev, &cid, &me.public_key()).await.is_none(), "a forged edit yields no outcome");

        let content = {
            let st = crate::state::STATE.lock().await;
            st.find_message(&msg_id).map(|(_, m)| m.content)
        };
        assert_eq!(content.as_deref(), Some("original"), "the message content is unchanged by the forged edit");
    }

    #[tokio::test]
    async fn a_reaction_cannot_be_injected_across_channels() {
        // A member holds BOTH channels' keys, so they can seal a valid reaction in
        // channel A whose target is a message resident in channel B. The
        // cross-channel guard (a reaction lands only on a same-channel target) must
        // drop it — else reactions could be injected onto messages in channels the
        // reaction was never sealed under.
        use nostr_sdk::prelude::Timestamp;
        let (_tmp, _guard, me) = init();
        let relay = MemoryRelay::new();
        let mut community = service::create_community(&relay, "TwoChan", vec!["wss://r".into()], None).await.unwrap();
        let chan_a = community.channels[0].id;
        let chan_b = service::create_public_channel(&relay, &community, "b").await.unwrap();
        community = crate::db::community::load_community_v2(community.id()).unwrap().unwrap();
        let a_hex = crate::simd::hex::bytes_to_hex_32(&chan_a.0);

        // A message lives in channel B.
        let author = Keys::generate();
        let gb = super::super::derive::channel_group_key(&community.community_root, &chan_b, community.root_epoch);
        let msg = chat::build_message_rumor(author.public_key(), &chan_b, community.root_epoch, "in B", None, &[], vec![], 5_000);
        let msg_id = msg.id.unwrap().to_hex();
        let (mw, _) = chat::seal_chat_rumor(&msg, &gb, &author, Timestamp::from_secs(5), false).unwrap();
        let bev = chat::open_chat_event(&mw, &gb, &chan_b, community.root_epoch).unwrap();
        persist_chat_event(&bev, &crate::simd::hex::bytes_to_hex_32(&chan_b.0), &me.public_key()).await;

        // A reaction sealed in channel A, targeting the channel-B message.
        let ga = super::super::derive::channel_group_key(&community.community_root, &chan_a, community.root_epoch);
        let reaction = chat::build_reaction_rumor(author.public_key(), &chan_a, community.root_epoch, &msg_id, &author.public_key().to_hex(), super::super::kind::MESSAGE, "💥", None, 6_000);
        let (rw, _) = chat::seal_chat_rumor(&reaction, &ga, &author, Timestamp::from_secs(6), false).unwrap();
        let aev = chat::open_chat_event(&rw, &ga, &chan_a, community.root_epoch).unwrap();
        // Applied under channel A (where it was sealed) — the target is in B.
        let outcome = persist_chat_event(&aev, &a_hex, &me.public_key()).await;
        assert!(outcome.is_none(), "a cross-channel reaction is dropped");
        let reacted = {
            let st = crate::state::STATE.lock().await;
            st.find_message(&msg_id).map(|(_, m)| !m.reactions.is_empty()).unwrap_or(false)
        };
        assert!(!reacted, "the channel-B message gained no reaction from the channel-A injection");
    }

    #[tokio::test]
    async fn a_reaction_with_junk_content_is_dropped_and_a_clean_one_lands() {
        use nostr_sdk::prelude::Timestamp;
        let (_tmp, _guard, me) = init();
        let relay = MemoryRelay::new();
        let community = service::create_community(&relay, "Junk", vec!["wss://r".into()], None).await.unwrap();
        let general = community.channels[0].id;
        let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
        let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);

        let author = Keys::generate();
        let msg = chat::build_message_rumor(author.public_key(), &general, community.root_epoch, "hi", None, &[], vec![], 5_000);
        let msg_id = msg.id.unwrap().to_hex();
        let (mw, _) = chat::seal_chat_rumor(&msg, &group, &author, Timestamp::from_secs(5), false).unwrap();
        let ev = chat::open_chat_event(&mw, &group, &general, community.root_epoch).unwrap();
        persist_chat_event(&ev, &cid, &me.public_key()).await;

        let react = |content: &str, at: u64| {
            let r = chat::build_reaction_rumor(author.public_key(), &general, community.root_epoch, &msg_id, &author.public_key().to_hex(), super::super::kind::MESSAGE, content, None, at);
            let (w, _) = chat::seal_chat_rumor(&r, &group, &author, Timestamp::from_secs(at / 1000), false).unwrap();
            chat::open_chat_event(&w, &group, &general, community.root_epoch).unwrap()
        };
        let junk = react(":catclap:https://i.nostr.build/lLMrw.gif", 6_000);
        assert!(persist_chat_event(&junk, &cid, &me.public_key()).await.is_none(), "a shortcode+URL reaction is dropped");
        let clean = react(":catclap:", 7_000);
        assert!(persist_chat_event(&clean, &cid, &me.public_key()).await.is_some(), "a clean shortcode reaction lands");

        let emojis: Vec<String> = {
            let st = crate::state::STATE.lock().await;
            st.find_message(&msg_id).map(|(_, m)| m.reactions.iter().map(|r| r.emoji.clone()).collect()).unwrap_or_default()
        };
        assert_eq!(emojis, vec![":catclap:".to_string()]);
    }

    #[tokio::test]
    async fn a_forged_delete_from_a_non_author_is_ignored() {
        use nostr_sdk::prelude::Timestamp;
        let (_tmp, _guard, me) = init();
        let relay = MemoryRelay::new();
        let community = service::create_community(&relay, "Forge", vec!["wss://r".into()], None).await.unwrap();
        let general = community.channels[0].id;
        let cid = crate::simd::hex::bytes_to_hex_32(&general.0);
        let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);

        // `me` posts a message and it's persisted into STATE.
        let msg_id = service::send_message(&relay, &community, &general, "mine").await.unwrap();
        let q = crate::community::transport::Query { kinds: vec![stream::KIND_WRAP], authors: vec![group.pk_hex()], ..Default::default() };
        let wraps = relay.fetch(&q, &community.relays).await.unwrap();
        for w in &wraps {
            if let Ok(ev) = chat::open_chat_event(w, &group, &general, community.root_epoch) {
                let mut st = crate::state::STATE.lock().await;
                apply_chat_to_state(&mut st, &ev, &cid, &me.public_key());
            }
        }

        // A STRANGER (a member, so holds the channel key) forges a delete of `me`'s message.
        let stranger = nostr_sdk::prelude::Keys::generate();
        let del = chat::build_delete_rumor(stranger.public_key(), &general, community.root_epoch, &msg_id, super::super::kind::MESSAGE, 9_000, None);
        let (wrap, _) = chat::seal_chat_rumor(&del, &group, &stranger, Timestamp::from_secs(9), false).unwrap();
        let event = chat::open_chat_event(&wrap, &group, &general, community.root_epoch).unwrap();

        let outcome = {
            let mut st = crate::state::STATE.lock().await;
            apply_chat_to_state(&mut st, &event, &cid, &me.public_key())
        };
        assert!(outcome.is_none(), "a forged delete from a non-author yields no removal");
        let survives = {
            let st = crate::state::STATE.lock().await;
            st.find_message(&msg_id).is_some()
        };
        assert!(survives, "the message survives the forged delete (live view + DB stay consistent)");
    }

    /// Owner + a granted admin + two posted messages, with the roster and the
    /// admin's Grant head persisted the way `follow_control` leaves them. Returns
    /// the pieces a moderation-delete test needs to seal one and judge it.
    struct ModerationBed {
        community: super::super::community::CommunityV2,
        general: crate::community::ChannelId,
        chat_id: String,
        group: super::super::derive::GroupKey,
        admin: Keys,
        admin_citation: crate::community::edition::AuthorityCitation,
    }

    async fn moderation_bed(relay: &MemoryRelay, name: &str) -> ModerationBed {
        let community = service::create_community(relay, name, vec!["wss://r".into()], None).await.unwrap();
        let general = community.channels[0].id;
        let chat_id = crate::simd::hex::bytes_to_hex_32(&general.0);
        let group = super::super::derive::channel_group_key(&community.community_root, &general, community.root_epoch);
        let cid_hex = crate::simd::hex::bytes_to_hex_32(&community.id().0);

        let admin = Keys::generate();
        service::grant_admin(relay, &community, &admin.public_key()).await.unwrap();

        // What `follow_control` persists after folding: the authorized roster, so
        // the receive path resolves ranks without a fetch.
        let view = service::fetch_authority(relay, &community).await;
        crate::db::community::set_community_roles(&cid_hex, &view.roles, 1_000).unwrap();

        // The admin's `vac`: the Grant edition the owner just published for them.
        let entity_id = super::super::derive::grant_locator(community.id(), &admin.public_key().to_bytes());
        let entity_hex = crate::simd::hex::bytes_to_hex_32(&entity_id);
        let (version, edition_hash) = crate::db::community::get_edition_head(&cid_hex, &entity_hex)
            .unwrap()
            .expect("the owner's own grant publish stores its head");
        let admin_citation = crate::community::edition::AuthorityCitation { entity_id, version, edition_hash };

        ModerationBed { community, general, chat_id, group, admin, admin_citation }
    }

    /// Seal `author`'s message onto the chat plane and apply it, returning its rumor id.
    async fn post_as(bed: &ModerationBed, author: &Keys, body: &str, at: u64, me: &PublicKey) -> String {
        use nostr_sdk::prelude::Timestamp;
        let rumor = chat::build_message_rumor(author.public_key(), &bed.general, bed.community.root_epoch, body, None, &[], vec![], at);
        let (wrap, _) = chat::seal_chat_rumor(&rumor, &bed.group, author, Timestamp::from_secs(at / 1000), false).unwrap();
        let event = chat::open_chat_event(&wrap, &bed.group, &bed.general, bed.community.root_epoch).unwrap();
        let id = rumor.id.unwrap().to_hex();
        let mut st = crate::state::STATE.lock().await;
        apply_chat_to_state(&mut st, &event, &bed.chat_id, me);
        id
    }

    /// Seal `actor`'s kind-5 against `target` and run it through the receive path.
    async fn delete_as(
        bed: &ModerationBed,
        actor: &Keys,
        target: &str,
        citation: Option<&crate::community::edition::AuthorityCitation>,
        at: u64,
        me: &PublicKey,
    ) -> Option<ChatPersist> {
        use nostr_sdk::prelude::Timestamp;
        let del = chat::build_delete_rumor(actor.public_key(), &bed.general, bed.community.root_epoch, target, super::super::kind::MESSAGE, at, citation);
        let (wrap, _) = chat::seal_chat_rumor(&del, &bed.group, actor, Timestamp::from_secs(at / 1000), false).unwrap();
        let event = chat::open_chat_event(&wrap, &bed.group, &bed.general, bed.community.root_epoch).unwrap();
        let mut st = crate::state::STATE.lock().await;
        apply_chat_to_state(&mut st, &event, &bed.chat_id, me)
    }

    #[tokio::test]
    async fn an_admins_moderation_delete_removes_a_members_message() {
        let (_tmp, _guard, me) = init();
        let relay = MemoryRelay::new();
        let bed = moderation_bed(&relay, "Mod").await;
        let member = Keys::generate();

        let victim = post_as(&bed, &member, "spam", 1_000, &me.public_key()).await;
        let outcome = delete_as(&bed, &bed.admin, &victim, Some(&bed.admin_citation), 2_000, &me.public_key()).await;

        assert!(matches!(outcome, Some(ChatPersist::Removed { ref id, moderated: true }) if *id == victim), "MANAGE_MESSAGES + outrank removes it, as a moderator");
        assert!(crate::state::STATE.lock().await.find_message(&victim).is_none());
    }

    #[tokio::test]
    async fn an_admin_cannot_moderation_delete_the_owners_message() {
        // The owner is position 0, supreme and never a valid target. This holds
        // only while the owner RESOLVES — an owner who needs no Role ranks last
        // without one.
        let (_tmp, _guard, me) = init();
        let relay = MemoryRelay::new();
        let bed = moderation_bed(&relay, "Sacred").await;

        let owners_message = post_as(&bed, &me, "the owner speaks", 1_000, &me.public_key()).await;
        let outcome = delete_as(&bed, &bed.admin, &owners_message, Some(&bed.admin_citation), 2_000, &me.public_key()).await;

        assert!(outcome.is_none(), "an admin never outranks the owner");
        assert!(crate::state::STATE.lock().await.find_message(&owners_message).is_some());
    }

    #[tokio::test]
    async fn a_moderation_delete_without_a_synced_citation_is_refused() {
        // CORD-04 §5: a non-owner must name the Grant it acts under, and we must
        // hold it. Uncited, the actor's rank is unprovable — fail closed.
        let (_tmp, _guard, me) = init();
        let relay = MemoryRelay::new();
        let bed = moderation_bed(&relay, "Uncited").await;
        let member = Keys::generate();

        let victim = post_as(&bed, &member, "spam", 1_000, &me.public_key()).await;
        assert!(delete_as(&bed, &bed.admin, &victim, None, 2_000, &me.public_key()).await.is_none());
        assert!(crate::state::STATE.lock().await.find_message(&victim).is_some());

        // The same delete WITH its citation lands — proving the refusal above was
        // the citation and not the rank.
        assert!(delete_as(&bed, &bed.admin, &victim, Some(&bed.admin_citation), 3_000, &me.public_key()).await.is_some());
    }

    #[tokio::test]
    async fn a_roleless_member_cannot_moderation_delete_anyone() {
        let (_tmp, _guard, me) = init();
        let relay = MemoryRelay::new();
        let bed = moderation_bed(&relay, "Roleless").await;
        let (member, rando) = (Keys::generate(), Keys::generate());

        let victim = post_as(&bed, &member, "hello", 1_000, &me.public_key()).await;
        // A citation is no substitute for a grant: cite the ADMIN's entity while
        // holding nothing, and the roster check still refuses.
        let outcome = delete_as(&bed, &rando, &victim, Some(&bed.admin_citation), 2_000, &me.public_key()).await;

        assert!(outcome.is_none(), "no MANAGE_MESSAGES, no removal");
        assert!(crate::state::STATE.lock().await.find_message(&victim).is_some());
    }

    #[tokio::test]
    async fn a_member_still_deletes_their_own_message_uncited() {
        // The self-delete path must not acquire a citation requirement.
        let (_tmp, _guard, me) = init();
        let relay = MemoryRelay::new();
        let bed = moderation_bed(&relay, "Self").await;
        let member = Keys::generate();

        let mine = post_as(&bed, &member, "oops", 1_000, &me.public_key()).await;
        let outcome = delete_as(&bed, &member, &mine, None, 2_000, &me.public_key()).await;

        assert!(matches!(outcome, Some(ChatPersist::Removed { ref id, moderated: false }) if *id == mine));
    }

    #[tokio::test]
    async fn a_foreign_wrap_is_not_ours() {
        let (_tmp, _guard, me) = init();
        let relay = MemoryRelay::new();
        let community = service::create_community(&relay, "X", vec!["wss://r".into()], None).await.unwrap();

        // A wrap from an unrelated stream key (e.g. a DM giftwrap, or another
        // community) must not match any plane.
        let stranger = super::super::derive::channel_group_key(&[0x99u8; 32], &community.channels[0].id, community.root_epoch);
        let rumor = chat::build_message_rumor(me.public_key(), &community.channels[0].id, community.root_epoch, "not yours", None, &[], vec![], 1_000);
        let (wrap, _) = chat::seal_chat_rumor(&rumor, &stranger, &me, nostr_sdk::prelude::Timestamp::from_secs(1), false).unwrap();

        let rec = Recorder::default();
        assert!(matches!(dispatch_wrap(&wrap, &community, &me.public_key(), &rec), DispatchedV2::NotOurs));
        assert!(rec.messages.lock().unwrap().is_empty());
    }
}