vector-core 0.12.0

Core library for Vector: the single source of truth for all Vector clients, SDKs and interfaces.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
//! Event handler — gift wrap receive, unwrap, process, commit pipeline.
//!
//! Two-phase architecture:
//! - **Phase 1** (`prepare_event`): Parallel-safe — dedup, unwrap, process_rumor
//! - **Phase 2** (`commit_prepared_event`): Sequential — save DB, update STATE, emit
//!
//! Platform-specific behavior (notifications) handled by `InboundEventHandler` trait.

use nostr_sdk::prelude::*;

use crate::rumor::{RumorProcessingResult, RumorEvent, RumorContext, ConversationType, process_rumor};
use crate::types::Message;
use crate::state::WRAPPER_ID_CACHE;

/// Platform-specific callbacks for inbound event processing.
///
/// Same pattern as SendCallback/ProfileSyncHandler — trait with default no-ops.
/// Platforms implement only the hooks they need.
pub trait InboundEventHandler: Send + Sync {
    /// A DM text message was received and committed to STATE + DB.
    fn on_dm_received(&self, _chat_id: &str, _msg: &Message, _is_new: bool) {}

    /// A DM file attachment was received and committed to STATE + DB.
    fn on_file_received(&self, _chat_id: &str, _msg: &Message, _is_new: bool) {}

    /// A reaction was received and applied to a message.
    fn on_reaction_received(&self, _chat_id: &str, _msg: &Message) {}

    /// A previously-stored message was deleted by its sender (Layer 2
    /// cooperative hide via NIP-09 over NIP-17). Frontend drops the row.
    fn on_message_deleted(&self, _chat_id: &str, _message_id: &str) {}

    /// A Community invite was received over a gift wrap and the local user was
    /// joined (member-view Community persisted). Platform refreshes the Community
    /// subscription so messages start flowing, and surfaces the new Community in the UI.
    fn on_community_invite(&self, _community_id: &str) {}

    // --- Community realtime (Concord channel events; `chat_id` is the channel id hex) ---

    /// A new Community channel message was received, ingested into STATE, and persisted.
    fn on_community_message(&self, _chat_id: &str, _msg: &Message, _is_new: bool) {}

    /// A reaction or edit was applied to an existing Community message. `target_id` is the
    /// affected message; `msg` is the live-updated view.
    fn on_community_update(&self, _chat_id: &str, _target_id: &str, _msg: &Message) {}

    /// A Community message was removed (cooperative delete / moderation tombstone).
    fn on_community_removed(&self, _chat_id: &str, _target_id: &str) {}

    /// A join/leave presence announcement. `created_at` is the authenticated inner timestamp;
    /// `invited_by`/`invited_label` carry invite attribution when present.
    #[allow(clippy::too_many_arguments)]
    fn on_community_presence(
        &self,
        _chat_id: &str,
        _npub: &str,
        _joined: bool,
        _event_id: &str,
        _created_at: u64,
        _invited_by: Option<&str>,
        _invited_label: Option<&str>,
    ) {}

    /// A Community typing indicator (ephemeral). `until` is the unix-secs the typer stops being active.
    fn on_community_typing(&self, _chat_id: &str, _npub: &str, _until: u64) {}

    /// Someone joined or left a voice Channel's call, or went stale (`community::v2::voice`).
    fn on_voice_presence(&self, _channel_id: &str) {}

    /// A WebXDC realtime peer signal. `node_addr` = `Some` advertises an Iroh node, `None` = peer-left.
    #[allow(clippy::too_many_arguments)]
    fn on_community_webxdc(
        &self,
        _chat_id: &str,
        _npub: &str,
        _topic_id: &str,
        _node_addr: Option<&str>,
        _event_id: &str,
        _created_at: u64,
    ) {}

    /// A WebXDC realtime peer signal in a DM. `contact` is the DM's npub; `node_addr` =
    /// `Some` advertises an Iroh node, `None` = peer-left. Clients without Iroh ignore it.
    #[allow(clippy::too_many_arguments)]
    fn on_webxdc_signal(
        &self,
        _contact: &str,
        _npub: &str,
        _topic_id: &str,
        _node_addr: Option<&str>,
        _event_id: &str,
        _created_at: u64,
    ) {}

    /// The local user was removed from a Community (kick / ban / a leave authored on another device).
    /// Local data is torn down (epoch keys retained); the platform surfaces it + refreshes subs.
    fn on_community_self_removed(&self, _community_id: &str) {}

    /// A Private channel is now readable — its key arrived, by rekey delivery or
    /// by a grant's key vend. `channel_id` is the 32-byte hex id.
    ///
    /// The inverse of the silent-mute failure: a bot granted access can act the
    /// moment it can actually read, rather than polling for a channel it has no
    /// way to know it is waiting on.
    ///
    /// `backfilled` counts the messages that predate the grant and were pulled
    /// into LOCAL STATE before this fired. A listener is told of those sent since it
    /// began listening; older ones are history: read them explicitly
    /// (`get_messages_before`) and decide what deserves acting on.
    fn on_channel_keyed(&self, _community_id: &str, _channel_id: &str, _backfilled: usize) {}

    /// The realtime Community subscription REGISTERED: healthy relays deliver
    /// live channel events from this moment (AUTH-gating relays join as their
    /// stream auth completes in the background). Fires once per
    /// [`listen`](crate::VectorCore::listen), after the startup refresh commits —
    /// even when `communities` is 0, so "subscribed to nothing" and "still
    /// connecting" are distinguishable. With [`CatchUp::Inline`](crate::CatchUp::Inline),
    /// whatever was sent since `listen` began reaches the handler however it arrives,
    /// before this or after ([`crate::news`]).
    fn on_subscription_ready(&self, _communities: usize) {}

    /// A Community's control plane was refreshed in realtime (banlist/roles/metadata/mode change,
    /// or a re-founding followed). The platform re-reads display state.
    fn on_community_refreshed(&self, _community_id: &str) {}

    /// A Community was DISSOLVED by its owner (CORD-02 §9): sealed read-only, held keys still open
    /// history but nothing new is honored. The platform surfaces the grave.
    fn on_community_dissolved(&self, _community_id: &str) {}

    // --- Typed changes. DM and Community alike: `chat_id` is the contact's npub or the channel
    // id. The coarse hooks above still fire; these say what happened.

    /// A reaction landed. `msg` is the message with it applied. `at` (unix ms, here and below)
    /// is when it was sent, as its sender dated it.
    fn on_reaction_added(&self, _chat_id: &str, _msg: &Message, _reaction: &crate::types::Reaction, _at: u64) {}

    /// A reaction was withdrawn by its reactor, `by` (an npub). `msg` is the message without it.
    fn on_reaction_removed(&self, _chat_id: &str, _msg: &Message, _reaction_id: &str, _by: &str, _at: u64) {}

    /// A message was edited by its author. `msg` carries the new content.
    fn on_message_edited(&self, _chat_id: &str, _msg: &Message, _at: u64) {}

    /// A message was removed by `by` (an npub): its author, or a moderator when `moderated`.
    /// `by` is `None` when the Community's own rules took it back (a post held for review
    /// that no longer stands), which reads as `moderated`; `at` is then when this device judged it.
    fn on_message_removed(&self, _chat_id: &str, _message_id: &str, _by: Option<&str>, _moderated: bool, _at: u64) {}

    /// A DM typing indicator. `until` is the unix-secs the typer stops being active.
    fn on_dm_typing(&self, _chat_id: &str, _npub: &str, _until: u64) {}

    /// Opt in to [`on_community_change`](Self::on_community_change): each refresh is then
    /// compared with the last, which costs a few local reads per Community refresh.
    fn wants_community_changes(&self) -> bool { false }

    /// One change to a Community's settings, Roles, Channels or members, with who made it.
    /// Fires only when [`wants_community_changes`](Self::wants_community_changes) says so.
    fn on_community_change(&self, _community_id: &str, _change: &crate::community::v2::changes::CommunityChange) {}

    /// Bulk-sync persist intercept: return `true` to take ownership of persisting a committed
    /// DM/file message — the commit then SKIPS its per-message save AND its wrapper-ledger
    /// write (`wrapper` = the gift-wrap's `(id_bytes, created_at)`; the owner MUST commit it
    /// in the same transaction as the message row, or the message loses crash/drop
    /// recoverability). Streaming sync loops (see [`BatchingPersist`]) buffer here and drain
    /// many messages into one transaction. Default `false` keeps the per-message save.
    fn buffer_persist(&self, _chat_id: &str, _msg: &Message, _wrapper: Option<([u8; 32], u64)>) -> bool { false }
}

/// No-op handler for CLI/tests.
pub struct NoOpEventHandler;
impl InboundEventHandler for NoOpEventHandler {}

/// For catch-up syncs: forwards to `inner` only what is live rather than
/// history. Mini App peer signals and Community invites always: each is live state, and a
/// sync that opens one ledgers its wrapper, so the live subscription will never
/// deliver it again. With [`from`](Self::from), also messages, reactions, edits and
/// deletions sent since that moment: a sync may be the only path that carries them.
pub struct LiveOnly<'a> {
    inner: &'a dyn InboundEventHandler,
    live_from_ms: Option<u64>,
}

impl<'a> LiveOnly<'a> {
    /// Signals only.
    pub fn signals(inner: &'a dyn InboundEventHandler) -> Self {
        LiveOnly { inner, live_from_ms: None }
    }

    /// Signals, and messages sent at or after `ms` (unix milliseconds).
    pub fn from(inner: &'a dyn InboundEventHandler, ms: u64) -> Self {
        LiveOnly { inner, live_from_ms: Some(ms) }
    }

    fn is_live(&self, msg: &Message) -> bool {
        self.is_live_at(msg.at)
    }

    fn is_live_at(&self, at_ms: u64) -> bool {
        self.live_from_ms.is_some_and(|from| at_ms >= from)
    }
}

impl InboundEventHandler for LiveOnly<'_> {
    /// An invite a sync parks is waiting on a decision now, however old its wrap.
    fn on_community_invite(&self, community_id: &str) {
        self.inner.on_community_invite(community_id)
    }

    fn on_community_webxdc(&self, chat_id: &str, npub: &str, topic_id: &str, node_addr: Option<&str>, event_id: &str, created_at: u64) {
        self.inner.on_community_webxdc(chat_id, npub, topic_id, node_addr, event_id, created_at)
    }

    fn on_webxdc_signal(&self, contact: &str, npub: &str, topic_id: &str, node_addr: Option<&str>, event_id: &str, created_at: u64) {
        self.inner.on_webxdc_signal(contact, npub, topic_id, node_addr, event_id, created_at)
    }

    fn on_dm_received(&self, chat_id: &str, msg: &Message, is_new: bool) {
        if self.is_live(msg) {
            self.inner.on_dm_received(chat_id, msg, is_new)
        }
    }

    fn on_file_received(&self, chat_id: &str, msg: &Message, is_new: bool) {
        if self.is_live(msg) {
            self.inner.on_file_received(chat_id, msg, is_new)
        }
    }

    fn on_reaction_added(&self, chat_id: &str, msg: &Message, reaction: &crate::types::Reaction, at: u64) {
        if self.is_live_at(at) {
            self.inner.on_reaction_added(chat_id, msg, reaction, at)
        }
    }

    fn on_reaction_removed(&self, chat_id: &str, msg: &Message, reaction_id: &str, by: &str, at: u64) {
        if self.is_live_at(at) {
            self.inner.on_reaction_removed(chat_id, msg, reaction_id, by, at)
        }
    }

    fn on_message_edited(&self, chat_id: &str, msg: &Message, at: u64) {
        if self.is_live_at(at) {
            self.inner.on_message_edited(chat_id, msg, at)
        }
    }

    fn on_message_removed(&self, chat_id: &str, message_id: &str, by: Option<&str>, moderated: bool, at: u64) {
        if self.is_live_at(at) {
            self.inner.on_message_removed(chat_id, message_id, by, moderated, at)
        }
    }
}

/// One deferred DM persist: the message, its chat, and its gift-wrap ledger entry — the
/// ledger row commits in the same flush transaction as the message row (see
/// `save_messages_batch_multi`), so a lost batch leaves the wrapper unledgered.
struct BufferedDm {
    chat_id: String,
    msg: Message,
    wrapper: Option<([u8; 32], u64)>,
}

/// Wraps any handler for a bulk-sync drain loop: every callback delegates to the inner
/// handler, but committed messages BUFFER here instead of saving one transaction each —
/// the loop calls [`BatchingPersist::flush`] periodically and at stream end to land them
/// in batched transactions (`save_messages_batch_multi`).
///
/// Deferral is recoverable because the wrapper ledger (the negentropy fingerprint set)
/// rides the flush transaction: a message lost to a crash, a stale-session drop, or a
/// failed flush leaves its wrapper unledgered, so the next reconciliation re-delivers it.
pub struct BatchingPersist<'a> {
    inner: &'a dyn InboundEventHandler,
    buf: std::sync::Mutex<Vec<BufferedDm>>,
    /// The account whose messages are in the buffer.
    ///
    /// Held rather than resolved at flush time: this outlives the calls that
    /// fill it, and a flush reached after a swap would otherwise write one
    /// account's inbox into another's. Holding it means the buffer always
    /// drains where it was filled, from any caller, bound or not.
    session: std::sync::Arc<crate::db::Session>,
}

impl<'a> BatchingPersist<'a> {
    pub fn new(inner: &'a dyn InboundEventHandler) -> Self {
        Self {
            inner,
            buf: std::sync::Mutex::new(Vec::new()),
            session: crate::db::current_session(),
        }
    }

    /// How many messages are waiting — the loop's flush-threshold probe.
    pub fn buffered(&self) -> usize {
        self.buf.lock().map(|b| b.len()).unwrap_or(0)
    }

    /// Drain the buffer into batched transactions (grouped by chat, arrival order kept),
    /// against the account that filled it.
    pub async fn flush(&self) -> usize {
        self.try_flush().await.unwrap_or(0)
    }

    /// [`Self::flush`], but a persist failure is distinguishable from "nothing
    /// to write" — callers that gate follow-on effects on the ledger actually
    /// holding the batch (reconcile-cursor births) need the difference: an
    /// advance over an unledgered batch skips those events forever.
    pub async fn try_flush(&self) -> Result<usize, String> {
        crate::db::with_session(self.session.clone(), async move {
            let mut drained: Vec<BufferedDm> = match self.buf.lock() {
                Ok(mut b) => b.drain(..).collect(),
                Err(_) => return Ok(0),
            };
            if drained.is_empty() {
                return Ok(0);
            }
            // A deletion may have landed (live subscription or this stream) while an entry sat
            // buffered: its delete_event no-ops on the not-yet-written row, so persisting the
            // buffered copy would resurrect a deleted message. Keyed on the POSITIVE deletion
            // tombstone, never STATE absence — the LRU evicts old messages from STATE, and
            // archive-synced history is exactly that tail (an evicted message must still
            // persist). A dropped entry's wrapper stays unledgered and re-delivers next sync,
            // where the DB dedup sees the (still-deleted) state cleanly.
            drained.retain(|e| !crate::state::was_message_deleted(&e.msg.id));
            if drained.is_empty() {
                return Ok(0);
            }
            // Group by chat preserving first-seen chat order + per-chat arrival order.
            let mut groups: Vec<crate::db::events::ChatBatch<'_>> = Vec::new();
            for e in &drained {
                match groups.iter_mut().find(|(c, _)| c == &e.chat_id) {
                    Some((_, v)) => v.push((&e.msg, e.wrapper)),
                    None => groups.push((e.chat_id.clone(), vec![(&e.msg, e.wrapper)])),
                }
            }
            match crate::db::events::save_messages_batch_multi(&groups).await {
                Ok(n) => {
                    // The arrivals were announced as they were processed, before this commit, so
                    // any unread count read meanwhile missed them: have it read again now.
                    let chats: Vec<&str> = groups.iter().map(|(c, _)| c.as_str()).collect();
                    crate::emit_event("unread_counts_stale", &serde_json::json!({ "chats": chats }));
                    Ok(n)
                }
                Err(e) => {
                    crate::log_warn!("[Sync] batched persist failed ({} msgs): {}", drained.len(), e);
                    Err(e)
                }
            }
        })
        .await
    }
}

impl InboundEventHandler for BatchingPersist<'_> {
    fn buffer_persist(&self, chat_id: &str, msg: &Message, wrapper: Option<([u8; 32], u64)>) -> bool {
        match self.buf.lock() {
            Ok(mut b) => {
                b.push(BufferedDm { chat_id: chat_id.to_string(), msg: msg.clone(), wrapper });
                true
            }
            // Poisoned lock: fall back to the commit's own per-message save.
            Err(_) => false,
        }
    }

    fn on_dm_received(&self, chat_id: &str, msg: &Message, is_new: bool) {
        self.inner.on_dm_received(chat_id, msg, is_new)
    }
    fn on_file_received(&self, chat_id: &str, msg: &Message, is_new: bool) {
        self.inner.on_file_received(chat_id, msg, is_new)
    }
    fn on_reaction_received(&self, chat_id: &str, msg: &Message) {
        self.inner.on_reaction_received(chat_id, msg)
    }
    fn on_message_deleted(&self, chat_id: &str, message_id: &str) {
        // The deletion's delete_event no-ops when the target is still buffered here —
        // purge it (unledgered wrapper → re-delivers → dedups against the deleted state)
        // so the flush can't resurrect a deleted message.
        if let Ok(mut b) = self.buf.lock() {
            b.retain(|e| e.msg.id != message_id);
        }
        self.inner.on_message_deleted(chat_id, message_id)
    }
    fn on_community_invite(&self, community_id: &str) {
        self.inner.on_community_invite(community_id)
    }
    fn on_community_message(&self, chat_id: &str, msg: &Message, is_new: bool) {
        self.inner.on_community_message(chat_id, msg, is_new)
    }
    fn on_community_update(&self, chat_id: &str, target_id: &str, msg: &Message) {
        self.inner.on_community_update(chat_id, target_id, msg)
    }
    fn on_community_removed(&self, chat_id: &str, target_id: &str) {
        self.inner.on_community_removed(chat_id, target_id)
    }
    fn on_community_presence(
        &self,
        chat_id: &str,
        npub: &str,
        joined: bool,
        event_id: &str,
        created_at: u64,
        invited_by: Option<&str>,
        invited_label: Option<&str>,
    ) {
        self.inner.on_community_presence(chat_id, npub, joined, event_id, created_at, invited_by, invited_label)
    }
    fn on_community_typing(&self, chat_id: &str, npub: &str, until: u64) {
        self.inner.on_community_typing(chat_id, npub, until)
    }
    fn on_community_webxdc(
        &self,
        chat_id: &str,
        npub: &str,
        topic_id: &str,
        node_addr: Option<&str>,
        event_id: &str,
        created_at: u64,
    ) {
        self.inner.on_community_webxdc(chat_id, npub, topic_id, node_addr, event_id, created_at)
    }
    fn on_webxdc_signal(
        &self,
        contact: &str,
        npub: &str,
        topic_id: &str,
        node_addr: Option<&str>,
        event_id: &str,
        created_at: u64,
    ) {
        self.inner.on_webxdc_signal(contact, npub, topic_id, node_addr, event_id, created_at)
    }
    fn on_community_self_removed(&self, community_id: &str) {
        self.inner.on_community_self_removed(community_id)
    }
    fn on_community_refreshed(&self, community_id: &str) {
        self.inner.on_community_refreshed(community_id)
    }
    fn on_community_dissolved(&self, community_id: &str) {
        self.inner.on_community_dissolved(community_id)
    }
    fn on_reaction_added(&self, chat_id: &str, msg: &Message, reaction: &crate::types::Reaction, at: u64) {
        self.inner.on_reaction_added(chat_id, msg, reaction, at)
    }
    fn on_reaction_removed(&self, chat_id: &str, msg: &Message, reaction_id: &str, by: &str, at: u64) {
        self.inner.on_reaction_removed(chat_id, msg, reaction_id, by, at)
    }
    fn on_message_edited(&self, chat_id: &str, msg: &Message, at: u64) {
        self.inner.on_message_edited(chat_id, msg, at)
    }
    fn on_message_removed(&self, chat_id: &str, message_id: &str, by: Option<&str>, moderated: bool, at: u64) {
        if let Ok(mut b) = self.buf.lock() {
            b.retain(|e| e.msg.id != message_id);
        }
        self.inner.on_message_removed(chat_id, message_id, by, moderated, at)
    }
    fn on_dm_typing(&self, chat_id: &str, npub: &str, until: u64) {
        self.inner.on_dm_typing(chat_id, npub, until)
    }
    fn wants_community_changes(&self) -> bool {
        self.inner.wants_community_changes()
    }
    fn on_community_change(&self, community_id: &str, change: &crate::community::v2::changes::CommunityChange) {
        self.inner.on_community_change(community_id, change)
    }
}

/// Result of Phase 1 (prepare_event) — everything needed for sequential commit.
#[allow(clippy::large_enum_variant)] // boxing a public variant's payload is an API break
pub enum PreparedEvent {
    /// A contact's push tickets (`vector-push`): kept so our DMs can wake their devices.
    PushTickets {
        contact: String,
        is_mine: bool,
        content: String,
        wrapper_event_id_bytes: [u8; 32],
        wrapper_created_at: u64,
    },
    /// Fully processed DM rumor — ready for state commit.
    Processed {
        result: RumorProcessingResult,
        contact: String,
        sender: PublicKey,
        is_mine: bool,
        wrapper_event_id: String,
        wrapper_event_id_bytes: [u8; 32],
        wrapper_created_at: u64,
        /// The rumor's own send time (unix ms): the wrap's is randomised.
        rumor_at_ms: u64,
        /// Time spent on ECDH + ChaCha20Poly1305 decryption (nanoseconds)
        unwrap_ns: u64,
        /// Time spent on rumor parsing (nanoseconds)
        parse_ns: u64,
    },
    /// Concord v2 Direct Invite (inner kind 3313) — parked for explicit consent.
    /// Carries the raw bundle JSON (parked verbatim; the accept path re-parses it).
    CommunityInviteV2 {
        bundle_json: String,
        community_id: String,
        /// Inviter's npub (hex) — the proven seal signer.
        inviter: String,
        is_mine: bool,
        wrapper_event_id_bytes: [u8; 32],
        wrapper_created_at: u64,
        /// Inner rumor `created_at` (seconds) — the real send time; NIP-59 backdates the
        /// outer wrapper up to 2 days.
        rumor_created_at: u64,
        /// Sender-declared NIP-40 expiry (unix secs); 0 = none, so permanent.
        expires_at: u64,
    },
    /// A message dated ahead of this device's clock: its wrap waits for its time
    /// ([`crate::early`]), unmarked, so it comes back if this session ends first.
    Early {
        wrap: Event,
        at_ms: u64,
    },
    /// Duplicate event — just persist wrapper for negentropy.
    DedupSkip {
        wrapper_id_bytes: [u8; 32],
        wrapper_created_at: u64,
    },
    /// Error during unwrap/processing — persist wrapper for negentropy.
    ErrorSkip {
        wrapper_id_bytes: [u8; 32],
        wrapper_created_at: u64,
    },
}

/// Phase 1: Prepare an event for commit (parallel-safe, no state mutation).
///
/// Performs dedup check, gift wrap decryption, and rumor parsing.
/// Safe to call from multiple tokio tasks concurrently.
pub async fn prepare_event(
    event: Event,
    _client: &Client,
    my_public_key: PublicKey,
) -> PreparedEvent {
    if let Some(skip) = dedup_skip(&event).await {
        return skip;
    }
    let unwrap_start = web_time::Instant::now();
    let unwrapped = crate::signer::unwrap_gift_wrap(&event).await;
    finish_prepare(&event, unwrapped, unwrap_start.elapsed().as_nanos() as u64, my_public_key)
}

/// Wraps per [`prepare_events`] call on bulk paths (syncs, catch-up). Their seal signatures
/// are checked in one batch, so a bigger batch checks each for less; the vault still opens
/// them [`crate::crypto::WRAPS_PER_VAULT_READ`] at a time. A chunk holds whatever has
/// arrived, up to this many: nothing waits to fill one.
pub const UNWRAP_BATCH: usize = 64;

/// [`prepare_event`] for many events, one result per event in order. The wraps that pass
/// dedup are opened together, under one vault read for a local key.
pub async fn prepare_events(events: &[Event], my_public_key: PublicKey) -> Vec<PreparedEvent> {
    let mut out: Vec<Option<PreparedEvent>> = Vec::with_capacity(events.len());
    for event in events {
        out.push(dedup_skip(event).await);
    }
    let todo: Vec<&Event> = events.iter().zip(&out).filter(|(_, o)| o.is_none()).map(|(e, _)| e).collect();
    if !todo.is_empty() {
        let unwrap_start = web_time::Instant::now();
        let unwrapped = crate::signer::unwrap_gift_wraps(&todo).await;
        let unwrap_ns = unwrap_start.elapsed().as_nanos() as u64 / todo.len() as u64;
        let mut unwrapped = unwrapped.into_iter();
        for (event, slot) in events.iter().zip(out.iter_mut()) {
            if slot.is_none() {
                let u = unwrapped.next().unwrap_or_else(|| Err("missing unwrap result".into()));
                *slot = Some(finish_prepare(event, u, unwrap_ns, my_public_key));
            }
        }
    }
    out.into_iter().flatten().collect()
}

/// `Some(DedupSkip)` when this wrap has been seen before.
async fn dedup_skip(event: &Event) -> Option<PreparedEvent> {
    let wrapper_created_at = event.created_at.as_secs();
    let wrapper_event_id_bytes: [u8; 32] = event.id.to_bytes();
    let skip = || Some(PreparedEvent::DedupSkip { wrapper_id_bytes: wrapper_event_id_bytes, wrapper_created_at });

    // Dedup: in-memory cache first, then DB fallback
    {
        let cache = WRAPPER_ID_CACHE.lock().await;
        if cache.contains(&wrapper_event_id_bytes) {
            return skip();
        }
    }

    // The ledger, not the events table: it holds every DM wrap (migration 96 backfilled the
    // pre-ledger rows), including a DELETED message's, which no longer has an events row.
    if crate::db::wrappers::processed_wrapper_exists(&wrapper_event_id_bytes) {
        return skip();
    }
    None
}

/// Everything after the unwrap: classify the rumor and parse it.
fn finish_prepare(
    event: &Event,
    unwrapped: Result<UnwrappedGift, String>,
    unwrap_ns: u64,
    my_public_key: PublicKey,
) -> PreparedEvent {
    let wrapper_created_at = event.created_at.as_secs();
    let wrapper_event_id_bytes: [u8; 32] = event.id.to_bytes();
    let wrapper_event_id = event.id.to_hex();

    let (rumor, sender) = match unwrapped {
        Ok(UnwrappedGift { rumor, sender }) => (rumor, sender),
        Err(_) => return PreparedEvent::ErrorSkip {
            wrapper_id_bytes: wrapper_event_id_bytes, wrapper_created_at,
        },
    };

    // Inner rumor send time (seconds). The outer wrapper's `created_at` is NIP-59
    // backdated up to 2 days, so it can't order an invite against a decline tombstone.
    let rumor_created_at = rumor.created_at.as_secs();

    let is_mine = sender == my_public_key;
    let contact = if is_mine {
        rumor.tags.public_keys().next()
            .and_then(|pk| pk.to_bech32().ok())
            .unwrap_or_else(|| sender.to_bech32().unwrap_or_default())
    } else {
        sender.to_bech32().unwrap_or_default()
    };

    // Skip NIP-17 group messages (multiple p-tags) — Vector DMs are 1:1
    if rumor.tags.public_keys().count() > 1 {
        return PreparedEvent::ErrorSkip {
            wrapper_id_bytes: wrapper_event_id_bytes, wrapper_created_at,
        };
    }

    if rumor.kind == Kind::ApplicationSpecificData
        && crate::tags::TagsExt::find_kind(&rumor.tags, "d").and_then(|t| t.content()) == Some(vector_push::TICKET_RUMOR_D)
    {
        return PreparedEvent::PushTickets {
            contact,
            is_mine,
            content: rumor.content,
            wrapper_event_id_bytes,
            wrapper_created_at,
        };
    }

    // A retired Concord v1 invite (kind 3304), still reachable through DM history: skipped,
    // never processed as an unknown rumor, which would open a DM thread holding its keys.
    if rumor.kind == Kind::Custom(3304) {
        return PreparedEvent::ErrorSkip { wrapper_id_bytes: wrapper_event_id_bytes, wrapper_created_at };
    }

    // Concord v2 Direct Invite (inner kind 3313) — the v2 join carrier. `from_bundle_json`
    // validates the owner commitment + bounds; we park the canonical re-serialized bundle.
    if rumor.kind == Kind::Custom(crate::community::v2::kind::DIRECT_INVITE) {
        return match crate::community::v2::invite::CommunityInvite::from_bundle_json(&rumor.content)
            .ok()
            .and_then(|b| serde_json::to_string(&b).ok().map(|j| (b.community_id, j)))
        {
            Some((community_id, bundle_json)) => PreparedEvent::CommunityInviteV2 {
                community_id,
                bundle_json,
                inviter: contact.clone(), // the seal signer's npub (bech32)
                is_mine,
                wrapper_event_id_bytes,
                wrapper_created_at,
                rumor_created_at,
                expires_at: crate::community::v2::invite::expiration_secs(&rumor.tags).unwrap_or(0),
            },
            None => PreparedEvent::ErrorSkip { wrapper_id_bytes: wrapper_event_id_bytes, wrapper_created_at },
        };
    }

    // Build RumorEvent for processing
    let Some(rumor_id) = rumor.id else {
        return PreparedEvent::ErrorSkip {
            wrapper_id_bytes: wrapper_event_id_bytes, wrapper_created_at,
        };
    };

    let rumor_at_ms = rumor.created_at.as_secs().saturating_mul(1000);
    let rumor_event = RumorEvent {
        id: rumor_id,
        kind: rumor.kind,
        content: rumor.content,
        tags: rumor.tags,
        created_at: rumor.created_at,
        pubkey: rumor.pubkey,
    };
    let rumor_context = RumorContext {
        sender,
        is_mine,
        conversation_id: contact.clone(),
        conversation_type: ConversationType::DirectMessage,
    };

    let parse_start = web_time::Instant::now();
    let download_dir = crate::db::get_download_dir();
    match process_rumor(rumor_event, rumor_context, &download_dir) {
        Ok(RumorProcessingResult::TextMessage(msg) | RumorProcessingResult::FileAttachment(msg)) if crate::early::is_early(msg.at) => {
            PreparedEvent::Early { wrap: event.clone(), at_ms: msg.at }
        }
        Ok(result) => {
            let parse_ns = parse_start.elapsed().as_nanos() as u64;
            PreparedEvent::Processed {
                result, contact, sender, is_mine,
                wrapper_event_id, wrapper_event_id_bytes, wrapper_created_at,
                rumor_at_ms, unwrap_ns, parse_ns,
            }
        }
        Err(e) => {
            log_warn!("[EventHandler] Failed to process rumor: {}", e);
            PreparedEvent::ErrorSkip {
                wrapper_id_bytes: wrapper_event_id_bytes, wrapper_created_at,
            }
        }
    }
}

// ============================================================================
// Phase 2: Commit — sequential state mutation, DB save, emit
// ============================================================================

/// Phase 2: commit a prepared event (sequential — not parallel-safe).
/// Saves to DB, updates STATE, emits to frontend, calls handler hooks.
/// Returns true if a new displayable message was committed.
///
/// Session-safety: captures the generation at the first line. If a swap
/// occurred between `prepare_event()` and here (e.g. long-running
/// negentropy fetch queued events for commit), bail before any STATE /
/// DB write. Centralized so individual spawn sites (sync.rs fetch_messages,
/// archive task, sync_dms, subscription_handler) don't have to wrap.
/// Direct Invites live 24 hours BY DESIGN, and the RECIPIENT enforces it: a
/// sender that omits the NIP-40 tag (older clients, other implementations)
/// must not mint a permanent invite, and an archive sync that resurrects a
/// months-old wrap must not park a ghost (a re-founded community's stale
/// invite has no held id for the exists-guard to match). The sender's
/// declared deadline is honored when EARLIER; the rumor-age lifetime is the
/// ceiling either way. One hour of slack absorbs sender clock skew.
pub const DIRECT_INVITE_LIFETIME_SECS: u64 = 24 * 3600 + 3600;

/// Park the Private-Channel keys a CATCH-UP bundle carries that we don't hold.
///
/// This is delivery, never authority: nothing is adopted here. The bundle's
/// self-certification is checked (a forged community binding never parks), the
/// keys are stashed, and [`judge_channel_key_vend`] rules on them against our own
/// fold after the next control follow. A vend that races its Grant therefore
/// parks quietly instead of being dropped, which is what makes an admin's grant
/// actually reach a member who is already in the community.
///
/// `inviter` is the seal author's npub (bech32) — recorded so the judge can
/// require an entitled vendor.
fn park_catch_up_channel_keys(
    community_id: &str,
    bundle_json: &str,
    inviter: &str,
) {
    use crate::community::v2::invite::CommunityInvite;
    let Ok(bundle) = CommunityInvite::from_bundle_json(bundle_json) else { return };
    // (1) Self-cert: the bundle cannot claim to be this community while naming a
    // different owner. Cheap, and it keeps garbage out of the park table.
    let (Some(cid), Some(owner), Some(salt)) = (
        crate::simd::hex::hex_to_bytes_32_checked(&bundle.community_id),
        crate::simd::hex::hex_to_bytes_32_checked(&bundle.owner),
        crate::simd::hex::hex_to_bytes_32_checked(&bundle.owner_salt),
    ) else {
        return;
    };
    if !crate::community::v2::derive::verify_community_id(&crate::community::CommunityId(cid), &owner, &salt) {
        log_warn!("[community] catch-up bundle failed self-certification — dropped");
        return;
    }
    let Ok(sender) = PublicKey::parse(inviter) else { return };
    let sender_hex = sender.to_hex();
    // The commit path's guard was captured before an await; re-check before the
    // writes below or a swap mid-commit parks account A's channel key into
    // account B's database.
    let held = crate::db::community::load_community_v2(&crate::community::CommunityId(cid)).ok().flatten();
    let mut parked_any = false;
    for grant in &bundle.channels {
        let Some(chan) = crate::simd::hex::hex_to_bytes_32_checked(&grant.id) else { continue };
        let Some(key) = crate::simd::hex::hex_to_bytes_32_checked(&grant.key) else { continue };
        // Only park what we LACK: a key at or below the held epoch is already
        // superseded, and a public channel's "key" is just the root.
        if let Some(c) = held.as_ref().and_then(|h| h.channel(&crate::community::ChannelId(chan))) {
            if !c.private || (c.key.is_some() && grant.epoch <= c.epoch.0) {
                continue;
            }
        }
        if let Err(e) = crate::db::community::park_channel_key(community_id, &grant.id, grant.epoch, &key, &sender_hex) {
            log_warn!("[community] parking a vended channel key failed: {e}");
            continue;
        }
        parked_any = true;
    }
    // Judge it now rather than whenever the next edition happens by. A vend that
    // lands AFTER its Grant folded changes no control state, so without a nudge
    // there is nothing left to trigger the re-judge.
    if parked_any {
        crate::community::v2::realtime::enqueue_follow(&crate::community::CommunityId(cid));
    }
}

fn expired_invite(expires_at: u64, rumor_created_at: u64) -> bool {
    let now = crate::clock::timestamp().as_secs();
    if expires_at != 0 && expires_at <= now {
        return true;
    }
    rumor_created_at.saturating_add(DIRECT_INVITE_LIFETIME_SECS) <= now
}

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

    #[tokio::test]
    async fn a_revoked_reaction_is_refused_under_any_wrapper() {
        // The deleted set lives on the session, which a test switching accounts would move.
        let _guard = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
        let id = "7".repeat(64);
        let reaction = crate::types::Reaction {
            id: id.clone(),
            reference_id: "message".into(),
            author_id: "author".into(),
            emoji: "+".into(),
            emoji_url: None,
        };
        crate::state::note_message_deleted(&id);
        let wrap = EventId::from_byte_array([8; 32]);
        assert!(!commit_reaction(reaction, "contact", false, &wrap.to_hex(), 0, &NoOpEventHandler).await);
        assert!(crate::deletion::pending_received_wrap_deletions().contains(&wrap), "and that wrap leaves the relays");
    }
}

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

    fn fresh_account() -> std::sync::MutexGuard<'static, ()> {
        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 account = Keys::generate().public_key().to_bech32().unwrap();
        crate::db::set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());
        std::fs::create_dir_all(crate::db::shared_test_data_dir().join(&account)).unwrap();
        crate::db::set_current_account(account.clone()).unwrap();
        crate::db::init_database(&account).unwrap();
        guard
    }

    #[tokio::test]
    async fn a_contact_cannot_edit_what_we_sent() {
        let _guard = fresh_account();
        let contact = Keys::generate().public_key().to_bech32().unwrap();
        let ours = crate::types::Message { id: "c".repeat(64), content: "ours".into(), at: 1_700_000_000_000, mine: true, ..Default::default() };
        crate::db::events::save_message(&contact, &ours).await.unwrap();
        crate::state::STATE.lock().await.add_message_to_participant(&contact, &ours);
        let edit = |id: &str| crate::stored_event::StoredEventBuilder::new().id(id.to_string()).kind(crate::stored_event::event_kind::MESSAGE_EDIT).content("forged".to_string()).build();
        let forged = commit_edit(&mut edit(&"d".repeat(64)), &contact, &ours.id, "forged", 1_700_000_001_000, vec![], vec![], &"e".repeat(64), false, &NoOpEventHandler).await;
        assert!(!forged, "the contact's edit of our message is refused");
        let content = crate::state::STATE.lock().await.find_message(&ours.id).map(|(_, m)| m.content);
        assert_eq!(content.as_deref(), Some("ours"));
        let own = commit_edit(&mut edit(&"f".repeat(64)), &contact, &ours.id, "ours, edited", 1_700_000_002_000, vec![], vec![], &"e".repeat(64), true, &NoOpEventHandler).await;
        assert!(own, "our own edit applies");
    }

    #[tokio::test]
    async fn an_honoured_hide_request_deletes_the_wrap_that_brought_the_message() {
        let _guard = fresh_account();
        let (peer, stranger) = (Keys::generate().public_key(), Keys::generate().public_key());
        let contact = peer.to_bech32().unwrap();
        let wrap = EventId::from_byte_array([5; 32]);
        let msg = crate::types::Message {
            id: "a".repeat(64),
            content: "hi".into(),
            at: 1_700_000_000_000,
            wrapper_event_id: Some(wrap.to_hex()),
            ..Default::default()
        };
        crate::db::events::save_message(&contact, &msg).await.unwrap();
        crate::state::STATE.lock().await.add_message_to_participant(&contact, &msg);
        assert!(!commit_deletion(&msg.id, &contact, &stranger, 0, &NoOpEventHandler).await, "only its author asks");
        assert!(!crate::deletion::pending_received_wrap_deletions().contains(&wrap));
        assert!(commit_deletion(&msg.id, &contact, &peer, 0, &NoOpEventHandler).await);
        assert!(crate::deletion::pending_received_wrap_deletions().contains(&wrap), "our copy leaves the relays too");
        crate::db::close_database();
    }

    #[tokio::test]
    async fn our_own_hide_request_takes_a_received_message_off_our_other_devices() {
        let _guard = fresh_account();
        let (me, peer) = (Keys::generate().public_key(), Keys::generate().public_key());
        crate::state::set_my_public_key(me);
        let contact = peer.to_bech32().unwrap();
        let (wrap, ours_wrap) = (EventId::from_byte_array([8; 32]), EventId::from_byte_array([9; 32]));
        let theirs = crate::types::Message { id: "c".repeat(64), content: "from them".into(), at: 1_700_000_000_000, wrapper_event_id: Some(wrap.to_hex()), ..Default::default() };
        let ours = crate::types::Message { id: "d".repeat(64), content: "from us".into(), at: 1_700_000_000_000, mine: true, wrapper_event_id: Some(ours_wrap.to_hex()), ..Default::default() };
        for msg in [&theirs, &ours] {
            crate::db::events::save_message(&contact, msg).await.unwrap();
        }
        assert!(!commit_deletion(&ours.id, &contact, &peer, 0, &NoOpEventHandler).await, "what we sent is never theirs to take down");
        assert!(commit_deletion(&theirs.id, &contact, &me, 0, &NoOpEventHandler).await);
        assert!(!crate::db::events::event_exists(&theirs.id).unwrap() && crate::state::was_message_deleted(&theirs.id));
        assert!(crate::deletion::pending_received_wrap_deletions().contains(&wrap), "this device's copy leaves the relays too");
        crate::db::close_database();
    }

    #[tokio::test]
    async fn our_own_early_hide_request_waits_for_a_message_we_received() {
        let _guard = fresh_account();
        let (me, peer) = (Keys::generate().public_key(), Keys::generate().public_key());
        crate::state::set_my_public_key(me);
        let contact = peer.to_bech32().unwrap();
        let early = "3".repeat(64);
        hold_deletion_until_met(&early, &me).await;
        let wrap = [6u8; 32];
        let msg = crate::types::Message { id: early.clone(), content: "x".into(), at: 1_700_000_000_000, ..Default::default() };
        assert!(!commit_dm_message(msg, &contact, false, true, &crate::simd::hex::bytes_to_hex_32(&wrap), wrap, 1_700_000_000, &NoOpEventHandler, false).await, "we asked first, on another device");
        assert!(crate::state::was_message_deleted(&early));
        assert!(crate::deletion::pending_received_wrap_deletions().contains(&EventId::from_byte_array(wrap)));
        crate::db::close_database();
    }

    #[tokio::test]
    async fn an_honoured_reaction_revocation_deletes_the_wrap_that_brought_it() {
        let _guard = fresh_account();
        let peer = Keys::generate().public_key();
        let contact = peer.to_bech32().unwrap();
        let msg = crate::types::Message { id: "c".repeat(64), content: "hi".into(), at: 1_700_000_000_000, mine: true, ..Default::default() };
        crate::db::events::save_message(&contact, &msg).await.unwrap();
        let reaction = crate::types::Reaction { id: "d".repeat(64), reference_id: msg.id.clone(), author_id: contact.clone(), emoji: "+".into(), emoji_url: None };
        let wrap = EventId::from_byte_array([4; 32]);
        let chat_id = crate::db::id_cache::get_or_create_chat_id(&contact).unwrap();
        crate::db::events::save_reaction_event(&reaction, chat_id, None, false, Some(wrap.to_hex())).await.unwrap();
        {
            let mut state = crate::state::STATE.lock().await;
            state.add_message_to_participant(&contact, &msg);
            state.add_reaction_to_message(&msg.id, reaction.clone());
        }
        assert!(commit_reaction_deletion(&reaction.id, &peer, 0, &NoOpEventHandler).await);
        assert!(crate::deletion::pending_received_wrap_deletions().contains(&wrap));
        crate::db::close_database();
    }

    #[tokio::test]
    async fn a_hide_request_reaches_a_message_no_longer_in_memory() {
        let _guard = fresh_account();
        let peer = Keys::generate().public_key();
        let contact = peer.to_bech32().unwrap();
        let wrap = EventId::from_byte_array([2; 32]);
        let msg = crate::types::Message { id: "e".repeat(64), content: "old".into(), at: 1_600_000_000_000, wrapper_event_id: Some(wrap.to_hex()), ..Default::default() };
        crate::db::events::save_message(&contact, &msg).await.unwrap();
        assert!(commit_deletion(&msg.id, &contact, &peer, 0, &NoOpEventHandler).await, "stored, if not in memory");
        assert!(!crate::db::events::event_exists(&msg.id).unwrap());
        assert!(crate::state::was_message_deleted(&msg.id));
        assert!(crate::deletion::pending_received_wrap_deletions().contains(&wrap));
        crate::db::close_database();
    }

    #[tokio::test]
    async fn a_hide_request_that_comes_first_waits_for_its_message() {
        let _guard = fresh_account();
        let (peer, stranger) = (Keys::generate().public_key(), Keys::generate().public_key());
        let contact = peer.to_bech32().unwrap();
        let (early, forged) = ("1".repeat(64), "2".repeat(64));
        hold_deletion_until_met(&early, &peer).await;
        hold_deletion_until_met(&forged, &stranger).await;
        let wrap = [3u8; 32];
        let msg = |id: &str| crate::types::Message { id: id.into(), content: "x".into(), at: 1_700_000_000_000, ..Default::default() };
        assert!(!commit_dm_message(msg(&early), &contact, false, true, &crate::simd::hex::bytes_to_hex_32(&wrap), wrap, 1_700_000_000, &NoOpEventHandler, false).await, "its author asked first");
        assert!(crate::state::was_message_deleted(&early));
        assert!(crate::deletion::pending_received_wrap_deletions().contains(&EventId::from_byte_array(wrap)));
        let other = [4u8; 32];
        assert!(commit_dm_message(msg(&forged), &contact, false, true, &crate::simd::hex::bytes_to_hex_32(&other), other, 1_700_000_000, &NoOpEventHandler, false).await, "nobody else's request takes it down");
        // One left waiting past its hide request's life is let go.
        crate::db::get_write_connection_guard_static().unwrap()
            .execute("INSERT INTO pending_deletions (target, requester, expires_at) VALUES (?1, ?2, 1)", rusqlite::params!["7".repeat(64), peer.to_hex()])
            .unwrap();
        assert!(crate::db::events::take_pending_deletion(&"7".repeat(64)).is_none());
        // A target already here is the live path's, never held.
        let held = "5".repeat(64);
        crate::db::events::save_message(&contact, &msg(&held)).await.unwrap();
        hold_deletion_until_met(&held, &stranger).await;
        assert!(crate::db::events::take_pending_deletion(&held).is_none());
        crate::db::close_database();
    }

    #[tokio::test]
    async fn a_reaction_revoked_before_it_arrived_never_lands() {
        let _guard = fresh_account();
        let author = Keys::generate().public_key();
        let reaction = crate::types::Reaction { id: "6".repeat(64), reference_id: "m".into(), author_id: author.to_bech32().unwrap(), emoji: "+".into(), emoji_url: None };
        hold_deletion_until_met(&reaction.id, &author).await;
        let wrap = EventId::from_byte_array([1; 32]);
        assert!(!commit_reaction(reaction.clone(), "contact", false, &wrap.to_hex(), 0, &NoOpEventHandler).await);
        assert!(crate::state::was_message_deleted(&reaction.id));
        assert!(crate::deletion::pending_received_wrap_deletions().contains(&wrap));
        crate::db::close_database();
    }

    #[tokio::test]
    async fn a_deleted_message_met_again_takes_that_wrap_down_too() {
        let _guard = fresh_account();
        let contact = Keys::generate().public_key().to_bech32().unwrap();
        let msg = crate::types::Message { id: "b".repeat(64), content: "gone".into(), at: 1_700_000_000_000, ..Default::default() };
        crate::state::note_message_deleted(&msg.id);
        let another = [6u8; 32];
        assert!(!commit_dm_message(msg, &contact, false, true, &crate::simd::hex::bytes_to_hex_32(&another), another, 1_700_000_000, &NoOpEventHandler, false).await);
        assert!(crate::deletion::pending_received_wrap_deletions().contains(&EventId::from_byte_array(another)));
        crate::db::close_database();
    }
}

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

    fn now() -> u64 {
        crate::clock::timestamp().as_secs()
    }

    #[test]
    fn declared_deadline_is_honored() {
        assert!(expired_invite(now() - 10, now()));
        assert!(!expired_invite(now() + 3600, now()));
    }

    #[test]
    fn tagless_invites_die_at_the_recipient_lifetime() {
        // Fresh, no tag: parks.
        assert!(!expired_invite(0, now() - 3600));
        // A day-and-slack old, no tag: never parks — the class the archive
        // recovery resurrected (months-old invite to a re-founded community).
        assert!(expired_invite(0, now() - DIRECT_INVITE_LIFETIME_SECS));
        assert!(expired_invite(0, now() - 90 * 24 * 3600));
    }

    #[test]
    fn lifetime_caps_a_generous_declared_deadline() {
        // Sender promised a week — the recipient's 24h ceiling still wins.
        assert!(expired_invite(now() + 7 * 24 * 3600, now() - DIRECT_INVITE_LIFETIME_SECS));
    }
}

pub async fn commit_prepared_event(
    prepared: PreparedEvent,
    is_new: bool,
    handler: &dyn InboundEventHandler,
) -> bool {
    let session = crate::db::current_session();
    if !session.is_live() {
        return false;
    }
    match prepared {
        PreparedEvent::Processed { result, contact, sender, is_mine, wrapper_event_id, wrapper_event_id_bytes, wrapper_created_at, rumor_at_ms, .. } => {
            // Cache wrapper for session dedup
            {
                let mut cache = WRAPPER_ID_CACHE.lock().await;
                cache.insert(wrapper_event_id_bytes);
            }

            // Blocked check — drop content from blocked contacts (wrapper still ledgered so
            // the dropped content never re-syncs)
            if !is_mine {
                let blocked = {
                    let state = crate::state::STATE.lock().await;
                    state.get_profile(&contact).is_some_and(|p| p.flags.is_blocked())
                };
                if blocked {
                    let _ = crate::db::wrappers::save_processed_wrapper(&wrapper_event_id_bytes, wrapper_created_at, crate::db::wrappers::TRANSPORT_NIP17);
                    return false;
                }
            }

            // Persist for cross-session dedup + negentropy — EXCEPT message rumors: the
            // ledger IS the negentropy fingerprint set, and a batching handler may defer the
            // message's save, so its wrapper must never be ledgered before its row lands (a
            // ledgered-but-unpersisted message reads as "have" and is never re-delivered).
            // Message wrappers ledger inside commit_dm_message / the batch-flush transaction.
            if !matches!(result, RumorProcessingResult::TextMessage(_) | RumorProcessingResult::FileAttachment(_)) {
                let _ = crate::db::wrappers::save_processed_wrapper(&wrapper_event_id_bytes, wrapper_created_at, crate::db::wrappers::TRANSPORT_NIP17);
            }

            match result {
                RumorProcessingResult::TextMessage(mut msg) => {
                    msg.wrapper_event_id = Some(wrapper_event_id.clone());
                    commit_dm_message(msg, &contact, is_mine, is_new, &wrapper_event_id, wrapper_event_id_bytes, wrapper_created_at, handler, false).await
                }
                RumorProcessingResult::FileAttachment(mut msg) => {
                    msg.wrapper_event_id = Some(wrapper_event_id.clone());
                    // If the sender's client (e.g. 0xChat) didn't ship `size` in
                    // the imeta tag, probe the URL via Content-Length so the
                    // frontend's auto-download gate has accurate metadata to
                    // decide on.
                    //
                    // Skip for self-echoes (is_mine): we just uploaded these
                    // files, the local Attachment.size is authoritative, and
                    // probing our own blossom URL right after upload is a
                    // correlation-fingerprint privacy regression.
                    //
                    // Each probe is bounded by a 3s outer timeout so a slow or
                    // dead server can't stall the inbound rumor pipeline. If
                    // the probe times out, we ship size=0 and the frontend
                    // falls back to a manual "Click to Download" affordance.
                    // Nor for someone whose request waits: the probe would reach a server
                    // they chose before we've said yes to anything.
                    let probe = !is_mine
                        && !(crate::requests::shielded() && crate::state::STATE.lock().await.dm_unanswered(&contact));
                    if probe {
                        for att in &mut msg.attachments {
                            if att.size == 0
                                && (att.url.starts_with("https://") || att.url.starts_with("http://"))
                            {
                                if let Ok(Some(size)) = crate::rt::time::timeout(
                                    crate::net::tor_http_timeout(std::time::Duration::from_secs(3)),
                                    crate::net::get_remote_file_size(&att.url),
                                ).await {
                                    att.size = size;
                                }
                            }
                        }
                    }
                    // A claim whose bytes are already on disk verifies at ARRIVAL,
                    // not at tap: the box renders downloaded from its first paint and
                    // no bytes are re-fetched. The ledger probe is an indexed lookup;
                    // the content hash only runs when a plausible candidate exists.
                    crate::db::attachments::verify_message_attachments(&mut msg, None).await;
                    commit_dm_message(msg, &contact, is_mine, is_new, &wrapper_event_id, wrapper_event_id_bytes, wrapper_created_at, handler, true).await
                }
                RumorProcessingResult::Reaction(reaction) => {
                    commit_reaction(reaction, &contact, is_mine, &wrapper_event_id, rumor_at_ms, handler).await
                }
                RumorProcessingResult::Edit { message_id, new_content, edited_at, emoji_tags, text_spans, mut event } => {
                    commit_edit(&mut event, &contact, &message_id, &new_content, edited_at, emoji_tags, text_spans, &wrapper_event_id, is_mine, handler).await
                }
                RumorProcessingResult::TypingIndicator { profile_id, until } => {
                    let active_typers = {
                        let mut state = crate::state::STATE.lock().await;
                        state.update_typing_and_get_active(&contact, &profile_id, until)
                    };
                    crate::traits::emit_event("typing-update", &serde_json::json!({
                        "conversation_id": contact,
                        "typers": active_typers,
                    }));
                    handler.on_dm_typing(&contact, &profile_id, until);
                    false
                }
                RumorProcessingResult::PivxPayment { gift_code, amount_piv, address, message_id, mut event } => {
                    if crate::db::events::event_exists(&event.id).unwrap_or(false) {
                        return false;
                    }
                    event.wrapper_event_id = Some(wrapper_event_id.clone());
                    let ts = event.created_at;
                    let _ = crate::db::events::save_pivx_payment_event(&contact, event).await;
                    crate::traits::emit_event("pivx_payment_received", &serde_json::json!({
                        "conversation_id": contact,
                        "gift_code": gift_code, "amount_piv": amount_piv,
                        "address": address, "message_id": message_id,
                        "sender": sender.to_hex(), "is_mine": is_mine,
                        "at": ts * 1000,
                    }));
                    true
                }
                RumorProcessingResult::UnknownEvent(mut event) => {
                    event.wrapper_event_id = Some(wrapper_event_id.clone());
                    // Store unknown events for forward compatibility
                    if let Ok(chat_id) = crate::db::id_cache::get_or_create_chat_id(&contact) {
                        event.chat_id = chat_id;
                    }
                    let _ = crate::db::events::save_event(&event).await;
                    false
                }
                RumorProcessingResult::LeaveRequest { .. } => false,
                RumorProcessingResult::WebxdcPeerAdvertisement { event_id, topic_id, node_addr, sender_npub, created_at } => {
                    handler.on_webxdc_signal(&contact, &sender_npub, &topic_id, Some(&node_addr), &event_id, created_at);
                    false
                }
                RumorProcessingResult::WebxdcPeerLeft { event_id, topic_id, sender_npub, created_at } => {
                    handler.on_webxdc_signal(&contact, &sender_npub, &topic_id, None, &event_id, created_at);
                    false
                }
                #[cfg(feature = "calls")]
                RumorProcessingResult::CallSignal { call_id, signal, node_addr, sender_npub, created_at, video, media, .. } => {
                    // Only the DM's other party may signal; a group member cannot ring us through a channel.
                    if contact == sender_npub {
                        crate::calls::session::on_signal(&sender_npub, &call_id, &signal, node_addr.as_deref(), created_at, video.as_deref(), media.as_deref()).await;
                    }
                    false
                }
                #[cfg(not(feature = "calls"))]
                RumorProcessingResult::CallSignal { .. } => false,
                RumorProcessingResult::WallpaperChanged {
                    sender_npub, created_at, url, decryption_key, decryption_nonce,
                    plaintext_hash, mime, blur, dim, event_id,
                } => {
                    let _ = crate::wallpaper::apply_received_wallpaper(
                        &contact, &sender_npub, created_at, &url,
                        &decryption_key, &decryption_nonce,
                        plaintext_hash.as_deref(), mime.as_deref(),
                        blur, dim,
                        &event_id,
                    ).await;
                    // System event is saved inside apply_received_wallpaper.
                    // Return true so the caller treats this as a stored event.
                    true
                }
                RumorProcessingResult::DeletionRequest { target_event_id } => {
                    // A deletion targets a message OR a reaction (both event ids,
                    // never colliding). Try the message path; if it's not a known
                    // message, treat it as a reaction revocation.
                    if commit_deletion(&target_event_id, &contact, &sender, rumor_at_ms, handler).await
                        || commit_reaction_deletion(&target_event_id, &sender, rumor_at_ms, handler).await
                    {
                        true
                    } else {
                        hold_deletion_until_met(&target_event_id, &sender).await;
                        false
                    }
                }
                RumorProcessingResult::Ignored => false,
            }
        }
        PreparedEvent::CommunityInviteV2 { bundle_json, community_id, inviter, is_mine, wrapper_event_id_bytes, wrapper_created_at, rumor_created_at, expires_at } => {
            {
                let mut cache = WRAPPER_ID_CACHE.lock().await;
                cache.insert(wrapper_event_id_bytes);
            }
            let _ = crate::db::wrappers::save_processed_wrapper(&wrapper_event_id_bytes, wrapper_created_at, crate::db::wrappers::TRANSPORT_NIP17);

            // Never park our own echoed invite.
            if is_mine {
                return false;
            }
            // Past the sender's deadline or the 24h lifetime (a stale wrap from a
            // catch-up sync, a relay that ignores expiry): never park it.
            if expired_invite(expires_at, rumor_created_at) {
                return false;
            }
            // Idempotency on the INNER community_id (already validated hex), not the
            // attacker-controlled wrapper id: already held, or already parked → drop.
            let held = match crate::simd::hex::hex_to_bytes_32_checked(&community_id) {
                Some(b) => crate::community::CommunityId(b),
                None => return false,
            };
            // Already a member? Then this is not an invitation but a CATCH-UP: a
            // grant's Private-Channel key vend (CORD-03 "delivered on grant"), or
            // an admin healing us forward. Park the keys we lack for the judge to
            // rule on after the next control fold — dropping it here is why a
            // granted member (or bot) stayed silently keyless.
            if crate::db::community::community_exists(&held).unwrap_or(false) {
                park_catch_up_channel_keys(&community_id, &bundle_json, &inviter);
                return false;
            }
            let wrap_hex = crate::simd::hex::bytes_to_hex_32(&wrapper_event_id_bytes);
            if crate::db::community::pending_invite_exists(&community_id).unwrap_or(false) {
                let _ = crate::db::community::note_pending_invite_wrap(&community_id, &wrap_hex);
                return false;
            }
            // From someone we blocked: declined on arrival, never shown or announced.
            if crate::requests::shielded()
                && crate::state::STATE.lock().await.get_profile(&inviter).is_some_and(|p| p.flags.is_blocked())
            {
                return false;
            }
            // Supersession: a decline/leave tombstone suppresses a re-wrapped invite no newer
            // than the decision, so a declined/left community can't be re-nagged by a fresh
            // ephemeral wrap. Ordered on the inner rumor time, not the NIP-59-backdated wrapper.
            // Its copy on our relays goes too, as the decision's own invite did.
            if crate::community::v2::service::tombstone_suppresses(&community_id, rumor_created_at) {
                crate::deletion::delete_received_wrap(EventId::from_byte_array(wrapper_event_id_bytes));
                return false;
            }
            // Park for explicit consent — do NOT join/subscribe here. Accept via the command layer.
            match crate::db::community::save_pending_invite(&community_id, &bundle_json, &inviter, expires_at as i64) {
                Ok(true) => {
                    let _ = crate::db::community::set_pending_invite_sent(&community_id, rumor_created_at as i64);
                    let _ = crate::db::community::note_pending_invite_wrap(&community_id, &wrap_hex);
                    handler.on_community_invite(&community_id)
                }
                Ok(false) => {} // raced — already parked
                Err(e) => log_warn!("[community] v2 invite park failed: {}", e),
            }
            false
        }
        PreparedEvent::PushTickets { contact, is_mine, content, wrapper_event_id_bytes, wrapper_created_at } => {
            if !is_mine {
                crate::push::store_tickets(&contact, &content).await;
            }
            let _ = crate::db::wrappers::save_processed_wrapper(&wrapper_event_id_bytes, wrapper_created_at, crate::db::wrappers::TRANSPORT_NIP17);
            false
        }
        PreparedEvent::Early { wrap, at_ms } => {
            crate::early::hold(wrap, crate::early::Via::Dm, at_ms);
            false
        }
        PreparedEvent::DedupSkip { wrapper_id_bytes, wrapper_created_at } => {
            // Persist wrapper timestamp for negentropy backfill (skip no-op writes).
            // Guarded: a cache-hit skip can name a wrapper whose message is still sitting in
            // a batch buffer (deferred ledger) — inserting it here would mark the message
            // "have" before its row exists. Only touch the ledger when the wrapper is
            // already ledgered (timestamp backfill) or its row is verifiably persisted
            // (legacy pre-ledger events, whose wrapper lives only on the events row).
            if wrapper_created_at > 0 {
                if crate::db::wrappers::processed_wrapper_exists(&wrapper_id_bytes) {
                    let _ = crate::db::wrappers::update_wrapper_timestamp(&wrapper_id_bytes, wrapper_created_at);
                } else {
                    let wrapper_hex = crate::simd::hex::bytes_to_hex_32(&wrapper_id_bytes);
                    if crate::db::events::wrapper_event_exists(&wrapper_hex).unwrap_or(false) {
                        let _ = crate::db::wrappers::save_processed_wrapper(&wrapper_id_bytes, wrapper_created_at, crate::db::wrappers::TRANSPORT_NIP17);
                    }
                }
            }
            false
        }
        PreparedEvent::ErrorSkip { wrapper_id_bytes, wrapper_created_at } => {
            let _ = crate::db::wrappers::save_processed_wrapper(&wrapper_id_bytes, wrapper_created_at, crate::db::wrappers::TRANSPORT_NIP17);
            false
        }
    }
}

/// Commit a DM text or file message (shared logic for both).
///
/// Owns this message's wrapper-ledger write (`processed_wrappers` = the negentropy
/// fingerprint set): the wrapper is ledgered only once the message row is durably handled —
/// immediately after a successful save, inside the batch-flush transaction when a handler
/// defers, or right away when the message is a known duplicate. An unledgered wrapper is
/// re-delivered by the next reconciliation, which is what makes a dropped batch recoverable.
#[allow(clippy::too_many_arguments)]
async fn commit_dm_message(
    mut msg: Message,
    contact: &str,
    _is_mine: bool,
    is_new: bool,
    wrapper_event_id: &str,
    wrapper_event_id_bytes: [u8; 32],
    wrapper_created_at: u64,
    handler: &dyn InboundEventHandler,
    is_file: bool,
) -> bool {
    let ledger_wrapper = || {
        let _ = crate::db::wrappers::save_processed_wrapper(
            &wrapper_event_id_bytes, wrapper_created_at, crate::db::wrappers::TRANSPORT_NIP17,
        );
    };
    // A tombstoned (user-deleted) message must never re-commit, whatever wrap
    // carried it — a retry wrap this device never ledgered can still deliver
    // the deleted rumor. Ledger the wrap so it stops re-delivering.
    if crate::state::was_message_deleted(&msg.id) {
        ledger_wrapper();
        crate::deletion::delete_received_wrap(nostr_sdk::prelude::EventId::from_byte_array(wrapper_event_id_bytes));
        return false;
    }
    // Its author, or we from another device, asked for it gone before it got here: it lands deleted.
    if let Some(requester) = crate::db::events::take_pending_deletion(&msg.id) {
        let me = crate::state::my_public_key();
        let author = if msg.mine { me } else { PublicKey::from_bech32(contact).ok() };
        if author.is_some_and(|a| a.to_hex() == requester) || me.is_some_and(|m| m.to_hex() == requester) {
            crate::state::note_message_deleted(&msg.id);
            if let Err(e) = crate::db::events::add_message_tombstone(&msg.id) {
                crate::log_warn!("[NIP-17 cooperative-delete] tombstone write failed: {}", e);
            }
            ledger_wrapper();
            crate::deletion::delete_received_wrap(nostr_sdk::prelude::EventId::from_byte_array(wrapper_event_id_bytes));
            return false;
        }
    }

    // Dedup: check if message already in DB
    if let Ok(true) = crate::db::events::message_exists_in_db(&msg.id) {
        // Already in DB — try to backfill wrapper_event_id
        if let Ok(updated) = crate::db::events::update_wrapper_event_id(&msg.id, wrapper_event_id) {
            if !updated {
                let mut cache = WRAPPER_ID_CACHE.lock().await;
                cache.insert(wrapper_event_id_bytes);
            }
        }
        ledger_wrapper();
        return false;
    }

    // Populate reply context
    if !msg.replied_to.is_empty() {
        let _ = crate::db::events::populate_reply_context(&mut msg).await;
    }

    // Add to STATE (+ clear typing indicator for file senders)
    let added = {
        let mut state = crate::state::STATE.lock().await;
        let added = state.add_message_to_participant(contact, &msg);
        if is_file && added {
            state.update_typing_and_get_active(contact, contact, 0);
        }
        added
    };

    // A banned author's message is stored but never SHOWN: the queries that build a
    // page already drop it, and painting it live was the one way it still reached the
    // screen. Gated at emission rather than at persist so an unban restores their
    // history — the row is still there, the filter simply stops matching.
    // A DM's contact is an npub, never a (hex) channel id: skip the community lookup.
    let hidden_author = added && !contact.starts_with("npub1") && msg
        .npub
        .as_deref()
        .and_then(|author| {
            let community = crate::db::community::community_id_for_channel(contact).ok().flatten()?;
            nostr_sdk::prelude::PublicKey::parse(author)
                .ok()
                .map(|pk| crate::db::community::is_author_banned(&community, &pk))
        })
        .unwrap_or(false);

    if added && !hidden_author {
        // Emit to frontend
        crate::traits::emit_message_new(contact, &msg);

        // Platform callback (notifications, badge, etc.)
        if is_file {
            handler.on_file_received(contact, &msg, is_new);
        } else {
            handler.on_dm_received(contact, &msg, is_new);
        }

        // Save to DB — unless a bulk-sync handler owns batched persistence (the handler then
        // also owns the wrapper-ledger write, inside its flush transaction). On the immediate
        // path the wrapper ledgers only after a successful save: a failed save left unledgered
        // re-delivers on the next reconciliation instead of being lost.
        if !handler.buffer_persist(contact, &msg, Some((wrapper_event_id_bytes, wrapper_created_at)))
            && crate::db::events::save_message(contact, &msg).await.is_ok()
        {
            ledger_wrapper();
        }
    } else {
        // STATE-level duplicate: a same-session twin owns the row; this wrapper carried
        // nothing new, so ledger it now (parity with the old eager ledger).
        ledger_wrapper();
    }

    added
}

/// Bring the DM a reaction or edit aims at into STATE from the database when it isn't resident:
/// STATE holds a window, and the change must land on older messages too.
async fn hydrate_dm_target(contact: &str, message_id: &str) {
    if crate::state::STATE.lock().await.find_message(message_id).is_some() {
        return;
    }
    if let Ok(Some((chat, msg))) = crate::db::events::get_message_by_id(message_id).await {
        if chat == contact {
            crate::state::STATE.lock().await.add_message_to_participant(contact, &msg);
        }
    }
}

/// Commit a reaction event.
async fn commit_reaction(
    reaction: crate::types::Reaction,
    contact: &str,
    is_mine: bool,
    wrapper_event_id: &str,
    at: u64,
    handler: &dyn InboundEventHandler,
) -> bool {
    // A revoked reaction can come back under a new wrapper id; its own id is the stable key.
    let revoked_early = || {
        let requester = crate::db::events::take_pending_deletion(&reaction.id)?;
        let author = PublicKey::parse(&reaction.author_id).ok()?;
        (author.to_hex() == requester).then_some(())
    };
    if crate::state::was_message_deleted(&reaction.id) || revoked_early().is_some() {
        crate::state::note_message_deleted(&reaction.id);
        if let Err(e) = crate::db::events::add_message_tombstone(&reaction.id) {
            crate::log_warn!("[reaction-delete] tombstone write failed: {}", e);
        }
        if let Ok(wrap) = nostr_sdk::prelude::EventId::from_hex(wrapper_event_id) {
            crate::deletion::delete_received_wrap(wrap);
        }
        return false;
    }

    hydrate_dm_target(contact, &reaction.reference_id).await;
    // Add to STATE
    let msg_for_emit = {
        let mut state = crate::state::STATE.lock().await;
        if let Some((chat_id, was_added)) = state.add_reaction_to_message(&reaction.reference_id, reaction.clone()) {
            if was_added {
                state.find_message(&reaction.reference_id)
                    .map(|(_, msg)| (chat_id, msg))
            } else { None }
        } else { None }
    };

    if let Some((chat_id, mut msg)) = msg_for_emit {
        crate::traits::emit_message_update(&chat_id, &reaction.reference_id, &mut msg).await;
        handler.on_reaction_received(&chat_id, &msg);
        handler.on_reaction_added(&chat_id, &msg, &reaction, at);
    }

    // The kind-7 row is the reaction's only storage: the parent row never carries it.
    if let Ok(chat_id) = crate::db::id_cache::get_chat_id_by_identifier(contact) {
        let user_id = crate::db::id_cache::get_or_create_user_id(&reaction.author_id).ok().flatten();
        let _ = crate::db::events::save_reaction_event(
            &reaction, chat_id, user_id, is_mine, Some(wrapper_event_id.to_string())
        ).await;
    }

    true
}

/// Commit a message edit.
#[allow(clippy::too_many_arguments)]
async fn commit_edit(
    event: &mut crate::stored_event::StoredEvent,
    contact: &str,
    message_id: &str,
    new_content: &str,
    edited_at: u64,
    emoji_tags: Vec<crate::types::EmojiTag>,
    text_spans: Vec<crate::text_spans::TextSpan>,
    wrapper_event_id: &str,
    is_mine: bool,
    handler: &dyn InboundEventHandler,
) -> bool {
    if crate::db::events::event_exists(&event.id).unwrap_or(false) {
        return false;
    }
    // Only a message's author edits it: in a DM, the other side can't rewrite what we sent.
    let resident = crate::state::STATE.lock().await.find_message(message_id).map(|(_, m)| m.mine);
    let target_mine = match resident {
        Some(mine) => Some(mine),
        None => crate::db::events::get_message_by_id(message_id).await.ok().flatten().map(|(_, m)| m.mine),
    };
    if target_mine.is_some_and(|mine| mine != is_mine) {
        return false;
    }
    if let Ok(chat_id) = crate::db::id_cache::get_chat_id_by_identifier(contact) {
        event.chat_id = chat_id;
    }
    event.wrapper_event_id = Some(wrapper_event_id.to_string());
    let _ = crate::db::events::save_event(event).await;

    hydrate_dm_target(contact, message_id).await;
    let msg_for_emit = {
        let mut state = crate::state::STATE.lock().await;
        state.update_message_in_chat_with(contact, message_id, |msg, i| {
            msg.apply_edit(new_content.to_string(), edited_at, emoji_tags.clone(), text_spans.clone(), i);
        })
    };
    if let Some(mut msg) = msg_for_emit {
        crate::traits::emit_message_update(contact, message_id, &mut msg).await;
        if crate::news::first_telling_hex(&event.id) {
            handler.on_message_edited(contact, &msg, edited_at);
        }
    }
    true
}

/// Commit a NIP-09 cooperative deletion request.
///
/// Authorization: only the original message's author can delete it
/// (matches NIP-09's `event.pubkey == deletion.pubkey` rule applied to
/// the inner rumor). For DMs, that means either the sender is `MY` (we
/// deleted from another device) or the sender is the chat counterpart
/// who originally sent that message. Anyone else's deletion is silently
/// ignored.
///
/// On success: drops the message from in-memory STATE, removes the row
/// from the events table, and emits `message_removed` so the frontend
/// can fade the row out — same code path as failed-message cleanup.
async fn commit_deletion(
    target_event_id: &str,
    contact: &str,
    sender: &PublicKey,
    at: u64,
    handler: &dyn InboundEventHandler,
) -> bool {
    // Not held here: the caller parks the request until its message arrives
    // ([`hold_deletion_until_met`]). A DM row stores no author: it is us when `mine`,
    // else the counterpart, whose npub is the chat id.
    let in_memory = {
        let state = crate::state::STATE.lock().await;
        state.find_message(target_event_id).map(|(chat, msg)| (msg.mine, chat.id.clone()))
    };
    // Memory holds only recent messages; an older one is still ours to drop.
    let (mine, chat_id, stored) = match in_memory {
        Some((mine, chat_id)) => (mine, chat_id, None),
        None => match crate::db::events::get_message_by_id(target_event_id).await.ok().flatten() {
            Some((chat_id, msg)) => (msg.mine, chat_id, Some(msg)),
            None => return false,
        },
    };

    // Its author may take it down, and so may we, from another of our devices: we may delete
    // anything we hold, so a message we received goes from all of them.
    let authorized = crate::state::my_public_key() == Some(*sender)
        || (!mine && nostr_sdk::prelude::PublicKey::from_bech32(&chat_id).is_ok_and(|counterpart| *sender == counterpart));
    if !authorized {
        eprintln!(
            "[NIP-17 cooperative-delete] unauthorized: sender {} not the author of target {} (mine={}, chat={})",
            sender.to_hex(), target_event_id, mine, chat_id
        );
        return false;
    }

    // The wrap that brought it here is ours to delete: it is addressed to us.
    let carried = crate::db::events::wrapper_event_id_of(target_event_id);

    // Drop from in-memory state.
    let removed = {
        let mut state = crate::state::STATE.lock().await;
        state.remove_message(target_event_id)
    };
    let removed_msg = match (removed, stored) {
        (Some((_, msg)), _) | (None, Some(msg)) => msg,
        (None, None) => return false,
    };
    // Tombstone BEFORE the row delete: the target may sit unflushed in a sync batch buffer
    // (delete_event below would no-op) — the flush consults this and drops it. The durable
    // row keeps the refusal across restarts: the sender's NIP-09 may never land on every
    // relay, and this side must not resurrect what it already agreed to drop.
    crate::state::note_message_deleted(target_event_id);
    if let Err(e) = crate::db::events::add_message_tombstone(target_event_id) {
        crate::log_warn!("[NIP-17 cooperative-delete] tombstone write failed: {}", e);
    }

    // Nuke any cached attachment files for this message — sender asked
    // for the message to disappear, and a downloaded file the receiver
    // never moved out of Vector's cache should go with it.
    //
    // Refcount filter: drop attachments still referenced by sibling
    // messages so we don't yank a cached file from messages that
    // still need it (Vector dedupes by SHA-256, so the same file
    // can back multiple messages). User-managed paths are also left
    // alone (canonicalize + starts_with check).
    let unique = crate::deletion::filter_unreferenced_attachments(
        target_event_id,
        removed_msg.attachments,
    ).await;
    crate::deletion::delete_cached_attachment_files_pub(&unique);

    // Drop from the events table.
    if let Err(e) = crate::db::events::delete_event(target_event_id).await {
        eprintln!(
            "[NIP-17 cooperative-delete] DB delete failed for {}: {}",
            target_event_id, e
        );
    }
    if let Some(wrap) = carried {
        crate::deletion::delete_received_wrap(wrap);
    }

    // Tell the frontend to fade the row out. Reuses the existing
    // message_removed event handled in main.js, so no new wiring.
    crate::traits::emit_event(
        "message_removed",
        &serde_json::json!({
            "id": target_event_id,
            "chat_id": &chat_id,
            "reason": if crate::state::my_public_key() == Some(*sender) { "deleted" } else { "deleted-by-sender" },
        }),
    );

    handler.on_message_deleted(&chat_id, target_event_id);
    if crate::news::first_telling_hex(&format!("deleted {target_event_id}")) {
        handler.on_message_removed(&chat_id, target_event_id, Some(&sender.to_bech32().unwrap_or_else(|_| sender.to_hex())), false, at);
    }
    let _ = contact;
    true
}

/// Hold a hide request for a target this device hasn't met: wraps are backdated, so a sync
/// can bring it before what it names. It only ever takes down something `sender` wrote.
async fn hold_deletion_until_met(target: &str, sender: &PublicKey) {
    if deletion_target_known(target).await {
        return;
    }
    let expires = crate::clock::now_secs()
        .saturating_add(crate::deletion::COOPERATIVE_HIDE_EXPIRY_SECS);
    if let Err(e) = crate::db::events::park_pending_deletion(target, &sender.to_hex(), expires) {
        crate::log_warn!("[NIP-17 cooperative-delete] {}", e);
    }
}

/// Whether this device holds `target`, as a message or a reaction, in memory or stored.
async fn deletion_target_known(target: &str) -> bool {
    {
        let state = crate::state::STATE.lock().await;
        if state.find_message(target).is_some() || state.find_reaction(target).is_some() {
            return true;
        }
    }
    crate::db::events::event_exists(target).unwrap_or(true)
}

/// Apply a cooperative reaction revocation (NIP-09 k=7) from the reaction's
/// author. Removes the reaction from its parent message and drops the kind-7
/// row, then live-refreshes the parent's chips. Returns false if we don't hold
/// the reaction or the sender isn't its author.
async fn commit_reaction_deletion(target_reaction_id: &str, sender: &PublicKey, at: u64, handler: &dyn InboundEventHandler) -> bool {
    let found = {
        let state = crate::state::STATE.lock().await;
        state.find_reaction(target_reaction_id)
    };
    let (chat_id, message_id, author_npub, _is_community) = match found {
        Some(v) => v,
        None => return false,
    };

    // Authorization: only the reaction's own author may revoke it.
    let authorized = nostr_sdk::prelude::PublicKey::parse(&author_npub)
        .map(|pk| pk == *sender)
        .unwrap_or(false);
    if !authorized {
        eprintln!(
            "[reaction-delete] unauthorized: sender {} is not the author of reaction {}",
            sender.to_hex(), target_reaction_id
        );
        return false;
    }

    crate::state::note_message_deleted(target_reaction_id);
    if let Err(e) = crate::db::events::add_message_tombstone(target_reaction_id) {
        crate::log_warn!("[reaction-delete] tombstone write failed: {}", e);
    }

    let updated = {
        let mut state = crate::state::STATE.lock().await;
        state.remove_reaction_from_message(&message_id, target_reaction_id)
    };
    let mut message = match updated {
        Some((_cid, msg)) => msg,
        None => return false,
    };

    // save_message is additive for reactions, so the kind-7 row must be
    // dropped explicitly or it resurrects on reload.
    let carried = crate::db::events::wrapper_event_id_of(target_reaction_id);
    if let Err(e) = crate::db::events::delete_event(target_reaction_id).await {
        eprintln!("[reaction-delete] DB delete failed for {}: {}", target_reaction_id, e);
    }
    if let Some(wrap) = carried {
        crate::deletion::delete_received_wrap(wrap);
    }

    crate::traits::emit_message_update(&chat_id, &message_id, &mut message).await;
    if crate::news::first_telling_hex(&format!("deleted {target_reaction_id}")) {
        handler.on_reaction_removed(&chat_id, &message, target_reaction_id, &sender.to_bech32().unwrap_or_else(|_| sender.to_hex()), at);
    }
    true
}

// ============================================================================
// Convenience: single-call event processing
// ============================================================================

/// Process a single event through the full pipeline (prepare + commit).
///
/// Gets client and public key from globals. For callers that manage their
/// own notification loop but want the full vector-core processing pipeline.
pub async fn process_event(
    event: Event,
    is_new: bool,
    handler: &dyn InboundEventHandler,
) -> std::result::Result<bool, String> {
    let client = crate::state::nostr_client()
        .ok_or_else(|| "Nostr client not initialized".to_string())?;
    let my_pk = crate::state::my_public_key()
        .ok_or_else(|| "Public key not initialized".to_string())?;
    let prepared = prepare_event(event, &client, my_pk).await;
    Ok(commit_prepared_event(prepared, is_new, handler).await)
}

#[cfg(test)]
mod early_dm_tests {
    use super::*;
    use crate::event_ext::FinalizeUnsignedWithId;

    #[test]
    fn a_dm_dated_ahead_of_this_device_waits_for_its_time() {
        let (me, them) = (Keys::generate(), Keys::generate());
        let wrap = EventBuilder::new(Kind::GiftWrap, "").finalize(&Keys::generate()).unwrap();
        let prepared = |ahead_secs: u64| {
            let rumor = EventBuilder::new(Kind::PrivateDirectMessage, "hi")
                .tag(Tag::public_key(me.public_key()))
                .custom_created_at(Timestamp::from_secs(crate::clock::now_secs() + ahead_secs))
                .finalize_unsigned_with_id(them.public_key());
            finish_prepare(&wrap, Ok(UnwrappedGift { rumor, sender: them.public_key() }), 0, me.public_key())
        };
        assert!(matches!(prepared(120), PreparedEvent::Early { .. }), "two minutes ahead waits");
        assert!(matches!(prepared(0), PreparedEvent::Processed { .. }), "on time shows at once");
        assert!(matches!(prepared(3), PreparedEvent::Processed { .. }), "a few seconds fast too");
    }
}

#[cfg(test)]
mod signals_only_tests {
    use super::*;
    use std::sync::atomic::{AtomicUsize, Ordering};

    #[derive(Default)]
    struct Counts {
        signals: AtomicUsize,
        messages: AtomicUsize,
    }

    impl InboundEventHandler for Counts {
        fn on_webxdc_signal(&self, _: &str, _: &str, _: &str, _: Option<&str>, _: &str, _: u64) {
            self.signals.fetch_add(1, Ordering::Relaxed);
        }
        fn on_community_webxdc(&self, _: &str, _: &str, _: &str, _: Option<&str>, _: &str, _: u64) {
            self.signals.fetch_add(1, Ordering::Relaxed);
        }
        fn on_dm_received(&self, _: &str, _: &Message, _: bool) {
            self.messages.fetch_add(1, Ordering::Relaxed);
        }
        fn on_file_received(&self, _: &str, _: &Message, _: bool) {
            self.messages.fetch_add(1, Ordering::Relaxed);
        }
    }

    #[test]
    fn a_catch_up_sync_passes_on_signals_and_nothing_else() {
        let inner = Counts::default();
        let sync = LiveOnly::signals(&inner);
        sync.on_webxdc_signal("npub1a", "npub1a", "T", Some("addr"), "e1", 1);
        sync.on_community_webxdc("chan", "npub1a", "T", None, "e2", 1);
        sync.on_dm_received("npub1a", &Message { at: u64::MAX, ..Default::default() }, true);
        assert_eq!(inner.signals.load(Ordering::Relaxed), 2);
        assert_eq!(inner.messages.load(Ordering::Relaxed), 0, "messages from a sync are history");
    }

    #[test]
    fn a_startup_sync_passes_on_messages_sent_since_listening_began() {
        let inner = Counts::default();
        let sync = LiveOnly::from(&inner, 5_000);
        sync.on_dm_received("npub1a", &Message { at: 4_999, ..Default::default() }, true);
        assert_eq!(inner.messages.load(Ordering::Relaxed), 0, "before: history");
        sync.on_dm_received("npub1a", &Message { at: 5_000, ..Default::default() }, true);
        sync.on_file_received("npub1a", &Message { at: 6_000, ..Default::default() }, true);
        assert_eq!(inner.messages.load(Ordering::Relaxed), 2, "since: live");
    }
}

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

    fn wrap() -> Event {
        EventBuilder::new(Kind::GiftWrap, "").finalize(&Keys::generate()).unwrap()
    }

    /// A wrap held only on a pre-ledger events row: unseen until migration 96 ledgers it,
    /// then skipped by the ledger lookup before any unwrap.
    #[tokio::test]
    async fn a_pre_ledger_dm_wrap_is_skipped_once_backfilled() {
        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 account = Keys::generate().public_key().to_bech32().unwrap();
        crate::db::set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());
        std::fs::create_dir_all(crate::db::shared_test_data_dir().join(&account)).unwrap();
        crate::db::set_current_account(account.clone()).unwrap();
        crate::db::init_database(&account).unwrap();
        WRAPPER_ID_CACHE.lock().await.clear();

        let legacy = wrap();
        let peer = Keys::generate().public_key().to_bech32().unwrap();
        let id = legacy.id.to_bytes();
        let msg = crate::types::Message {
            id: "f".repeat(64),
            content: "legacy".into(),
            at: 1_700_000_000_000,
            npub: Some(peer.clone()),
            wrapper_event_id: Some(crate::simd::hex::bytes_to_hex_32(&id)),
            ..Default::default()
        };
        crate::db::events::save_message(&peer, &msg).await.unwrap();
        assert!(dedup_skip(&legacy).await.is_none(), "the events column alone no longer dedups");

        {
            let conn = crate::db::get_write_connection_guard_static().unwrap();
            assert_eq!(crate::db::schema::backfill_dm_wrapper_ledger(&conn).unwrap(), 1);
        }
        assert!(matches!(dedup_skip(&legacy).await, Some(PreparedEvent::DedupSkip { .. })));
        assert!(dedup_skip(&wrap()).await.is_none(), "an unseen wrap still processes");
        crate::db::close_database();
    }
}

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

    fn init_test_db() -> (tempfile::TempDir, std::sync::MutexGuard<'static, ()>) {
        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();
        let account = Keys::generate().public_key().to_bech32().unwrap();
        std::fs::create_dir_all(tmp.path().join(&account)).unwrap();
        crate::db::set_app_data_dir(crate::db::shared_test_data_dir().to_path_buf());
        crate::db::set_current_account(account.clone()).unwrap();
        crate::db::init_database(&account).unwrap();
        (tmp, guard)
    }

    fn invite(community_id: &str, wrap: u8, rumor_created_at: u64) -> PreparedEvent {
        PreparedEvent::CommunityInviteV2 {
            bundle_json: "{}".into(),
            community_id: community_id.into(),
            inviter: Keys::generate().public_key().to_hex(),
            is_mine: false,
            wrapper_event_id_bytes: [wrap; 32],
            wrapper_created_at: rumor_created_at,
            rumor_created_at,
            expires_at: 0,
        }
    }

    #[tokio::test]
    async fn every_wrap_that_delivers_an_invite_is_kept_and_a_decline_deletes_them_all() {
        let (_tmp, _guard) = init_test_db();
        let cid = "ab".repeat(32);
        let now = crate::clock::timestamp().as_secs();
        commit_prepared_event(invite(&cid, 0x11, now), true, &NoOpEventHandler).await;
        commit_prepared_event(invite(&cid, 0x22, now), true, &NoOpEventHandler).await;
        assert_eq!(crate::db::community::pending_invite_wraps(&cid).unwrap(), ["11".repeat(32), "22".repeat(32)]);
        assert_eq!(crate::db::community::list_pending_invites().unwrap()[0].sent_at, now as i64, "parked with its send time");

        crate::VectorCore.decline_community_invite(&cid).await.unwrap();
        assert!(crate::db::community::get_pending_invite(&cid).unwrap().is_none());
        let queued = crate::deletion::queued_received_wrap_deletions();
        assert_eq!(queued, [EventId::from_byte_array([0x11; 32]), EventId::from_byte_array([0x22; 32])]);
    }

    #[tokio::test]
    async fn an_invite_met_again_after_its_decline_is_deleted_not_parked() {
        let (_tmp, _guard) = init_test_db();
        let cid = "cd".repeat(32);
        let now = crate::clock::timestamp().as_secs();
        crate::community::v2::service::note_local_removal(&cid, now * 1000);
        commit_prepared_event(invite(&cid, 0x33, now - 60), true, &NoOpEventHandler).await;
        assert!(crate::db::community::get_pending_invite(&cid).unwrap().is_none());
        assert_eq!(crate::deletion::queued_received_wrap_deletions(), [EventId::from_byte_array([0x33; 32])]);
    }
}

#[cfg(test)]
mod live_only_tests {
    #[test]
    fn a_sync_forwards_reactions_edits_and_deletions_sent_since_its_cutoff() {
        #[derive(Default)]
        struct Seen(std::sync::Mutex<Vec<&'static str>>);
        impl InboundEventHandler for Seen {
            fn on_reaction_added(&self, _: &str, _: &Message, _: &crate::types::Reaction, _: u64) {
                self.0.lock().unwrap().push("react");
            }
            fn on_reaction_removed(&self, _: &str, _: &Message, _: &str, _: &str, _: u64) {
                self.0.lock().unwrap().push("unreact");
            }
            fn on_message_edited(&self, _: &str, _: &Message, _: u64) {
                self.0.lock().unwrap().push("edit");
            }
            fn on_message_removed(&self, _: &str, _: &str, _: Option<&str>, _: bool, _: u64) {
                self.0.lock().unwrap().push("remove");
            }
        }
        let seen = Seen::default();
        let live = LiveOnly::from(&seen, 1_000);
        let msg = Message::default();
        let reaction = crate::types::Reaction { id: String::new(), reference_id: String::new(), author_id: String::new(), emoji: "+".into(), emoji_url: None };
        for at in [999, 1_000] {
            live.on_reaction_added("c", &msg, &reaction, at);
            live.on_reaction_removed("c", &msg, "r", "b", at);
            live.on_message_edited("c", &msg, at);
            live.on_message_removed("c", "m", None, false, at);
        }
        assert_eq!(*seen.0.lock().unwrap(), vec!["react", "unreact", "edit", "remove"], "only what was sent from the cutoff on");
    }

    use super::*;

    #[derive(Default)]
    struct Invites(std::sync::Mutex<Vec<String>>);
    impl InboundEventHandler for Invites {
        fn on_community_invite(&self, community_id: &str) {
            self.0.lock().unwrap().push(community_id.to_string());
        }
    }

    #[test]
    fn an_invite_a_sync_parks_reaches_the_handler() {
        let inner = Invites::default();
        LiveOnly::from(&inner, u64::MAX).on_community_invite("ab");
        LiveOnly::signals(&inner).on_community_invite("cd");
        assert_eq!(*inner.0.lock().unwrap(), vec!["ab", "cd"]);
    }
}