vector-core 0.1.0

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

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

// === Foundation ===
pub mod error;
pub mod traits;

// Nostr SDK trait imports needed for bech32 operations
use nostr_sdk::prelude::ToBech32;

// === Core Types ===
pub mod types;
pub mod profile;
pub mod chat;
pub mod compact;

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

// === Debug Stats ===
#[cfg(debug_assertions)]
pub mod stats;

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

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

// === Database ===
pub mod db;

// === Network ===
pub mod net;
pub mod negentropy;
pub mod blossom;
pub mod blossom_servers;
pub mod blossom_capabilities;
pub mod inbox_relays;
pub mod emoji_packs;
pub mod badges;
pub mod webxdc;
#[cfg(feature = "tor")]
pub mod tor;

/// Build a `nostr_sdk::ClientOptions` with the embedded-Tor SOCKS proxy
/// applied if (and only if) the `tor` feature is on AND `tor::TorService` is
/// currently active. When Tor is off, returns the default options unchanged.
///
/// Note: nostr-sdk's `proxy()` lives on `Connection`, not `ClientOptions`
/// directly — we build a `Connection` with the proxy mode and pass it via
/// `ClientOptions::connection(...)`. The `connection()` method itself is
/// `#[cfg(not(target_arch = "wasm32"))]`, but Vector targets are all native.
///
/// Callers should use this rather than `ClientOptions::new()` directly so the
/// Tor toggle automatically covers their relay traffic.
pub fn nostr_client_options() -> nostr_sdk::ClientOptions {
    let opts = nostr_sdk::ClientOptions::new();
    #[cfg(all(feature = "tor", not(target_arch = "wasm32")))]
    {
        match tor::transport_state() {
            tor::TorTransportState::Active(addr) => {
                return opts.connection(nostr_sdk::client::Connection::new().proxy(addr));
            }
            tor::TorTransportState::RequiredButInactive => {
                // Tor failsafe: route to a blackhole so the relay socket can't
                // accidentally come up direct while Tor is mid-bootstrap.
                return opts.connection(
                    nostr_sdk::client::Connection::new().proxy(tor::blackhole_proxy_addr()),
                );
            }
            tor::TorTransportState::Disabled => {}
        }
    }
    opts
}

/// Augment a `RelayOptions` with the Tor connection mode when active. Used
/// by every site that adds a relay to the pool — default relays at boot,
/// custom user relays, community relays, NIP-17 inbox relays — so they all
/// come up through Tor when the toggle is on.
///
/// Without this, `RelayOptions::new()` (or the per-mode helper) defaults to
/// `ConnectionMode::Direct`, and relays added at boot would stay direct even
/// after Tor is bootstrapped — `switch_relay_transport()` covers existing
/// relays on toggle, but not freshly-added ones.
pub fn tor_aware_relay_options(opts: nostr_sdk::RelayOptions) -> nostr_sdk::RelayOptions {
    #[cfg(all(feature = "tor", not(target_arch = "wasm32")))]
    {
        match tor::transport_state() {
            tor::TorTransportState::Active(addr) => {
                return opts.connection_mode(nostr_sdk::pool::ConnectionMode::proxy(addr));
            }
            tor::TorTransportState::RequiredButInactive => {
                // Tor failsafe: pin to blackhole so this relay can never come
                // up direct while Tor isn't running.
                return opts.connection_mode(
                    nostr_sdk::pool::ConnectionMode::proxy(tor::blackhole_proxy_addr()),
                );
            }
            tor::TorTransportState::Disabled => {}
        }
    }
    opts
}

/// Relay options for a Community / "external" relay: the GOSSIP flag (+ PING for a 24/7 keepalive
/// connection). GOSSIP is read/write-capable when TARGETED — `can_read()` is `READ|GOSSIP|DISCOVERY`
/// and `can_write()` is `WRITE|GOSSIP`, so per-relay checks pass for `fetch_events_from` /
/// `send_event_to` / `subscribe_to`. But pool-wide ops select READ-only / WRITE-only relays, so the
/// DM/giftwrap subscription (`subscribe(None)`) and the user's outbox (`send_event`) skip GOSSIP
/// relays — the user's own traffic never touches relays they don't own. (A bare PING-only relay can
/// NOT be used: `can_write()`/`can_read()` are false → the relay layer returns WriteDisabled /
/// ReadDisabled.) An overlap relay that's ALSO a user relay keeps its existing READ+WRITE flags —
/// `add_relay` is a no-op (`Ok(false)`) for a url already pooled, reusing the one existing connection.
pub fn community_relay_options() -> nostr_sdk::RelayOptions {
    use nostr_sdk::RelayServiceFlags;
    tor_aware_relay_options(
        nostr_sdk::RelayOptions::new().flags(RelayServiceFlags::GOSSIP | RelayServiceFlags::PING),
    )
}

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

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

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

// === Per-DM Wallpapers ===
pub mod wallpaper;

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

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

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

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

// === Re-exports for convenience ===
pub use types::{Message, Attachment, Reaction, EditEntry, ImageMetadata, SiteMetadata, LoginResult, AttachmentFile, mention, extract_mentions};
pub use profile::{Profile, ProfileFlags, SlimProfile, Status};
pub use chat::{Chat, ChatType, ChatMetadata, SerializableChat};
pub use compact::{CompactMessage, CompactMessageVec, NpubInterner};
pub use state::{
    ChatState, NOSTR_CLIENT, MY_SECRET_KEY, MY_PUBLIC_KEY, STATE, ENCRYPTION_KEY,
    nostr_client, my_public_key, has_active_session,
    set_nostr_client, set_my_public_key,
    take_nostr_client, clear_my_public_key,
    set_pending_bunker_setup, pending_bunker_setup, clear_pending_bunker_setup,
};
pub use crypto::{GuardedKey, GuardedSigner};
pub use signer::{
    SignerKind, signer_kind, set_signer_kind, is_bunker,
    BUNKER_SIGNER, bunker_signer, set_bunker_signer, take_bunker_signer,
    build_bunker_signer, prewarm_bunker, drain_bunker_state,
    parse_bunker_remote_pubkey, parse_bunker_relays,
    BunkerConnectionState, bunker_state, set_bunker_state,
    VectorAuthUrlHandler, attempt_bunker_login, WatchedBunkerSigner,
    vector_metadata, build_nostrconnect_uri, build_nostrconnect_session,
    VECTOR_APP_NAME, VECTOR_APP_URL, VECTOR_APP_ICON,
};
pub use error::{VectorError, Result};
pub use traits::{EventEmitter, NoOpEmitter, set_event_emitter, emit_event};
pub use db::{set_app_data_dir, get_app_data_dir};
pub use sending::{SendCallback, NoOpSendCallback, SendConfig, SendResult};
pub use deletion::{delete_own_dm, DeleteOutcome};
pub use stored_event::{StoredEvent, StoredEventBuilder, SystemEventType};
pub use rumor::{RumorEvent, RumorContext, ConversationType, RumorProcessingResult, process_rumor};
pub use profile::{SyncPriority, ProfileSyncHandler, NoOpProfileSyncHandler};
pub use event_handler::{InboundEventHandler, NoOpEventHandler, PreparedEvent, process_event};

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

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

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

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

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

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

        // Install rustls ring provider
        let _ = rustls::crypto::ring::default_provider().install_default();

        Ok(VectorCore)
    }

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

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

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

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

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

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

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

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

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

        if has_encryption {
            if let Some(pwd) = password {
                let key = crate::crypto::hash_pass(pwd).await;
                state::ENCRYPTION_KEY.set(key, &[&state::MY_SECRET_KEY]);
            }
        }
        // Seed the atomic unconditionally — `is_encryption_enabled_fast()`
        // must agree with the DB regardless of branch.
        state::init_encryption_enabled();

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

        // Add trusted relays
        for relay in state::TRUSTED_RELAYS {
            let opts = tor_aware_relay_options(nostr_sdk::RelayOptions::default());
            client.pool().add_relay(*relay, opts).await.ok();
        }

        // Connect
        client.connect().await;

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

        Ok(LoginResult { npub, has_encryption })
    }

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

    /// Send a NIP-17 gift-wrapped text DM using the full pipeline.
    pub async fn send_dm(&self, to_npub: &str, content: &str) -> Result<sending::SendResult> {
        sending::send_dm(to_npub, content, None, &SendConfig::default(), Arc::new(NoOpSendCallback)).await
            .map_err(|e| VectorError::Other(e))
    }

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

    /// Download a received attachment and decrypt it to plaintext bytes. Fetches the encrypted blob
    /// from its Blossom URL (SSRF/Tor-aware client, size-capped) and AES-decrypts with the
    /// attachment's embedded key + nonce.
    pub async fn download_attachment(&self, attachment: &Attachment) -> Result<Vec<u8>> {
        use futures_util::StreamExt;
        const MAX_DOWNLOAD: usize = 256 * 1024 * 1024;
        if attachment.url.is_empty() {
            return Err(VectorError::Other("attachment has no URL".into()));
        }
        // SSRF guard: the URL is attacker-controlled (off an inbound message). build_http_client only
        // validates redirect HOPS, not the initial request — so validate it here (matches the native
        // download path). With Tor off this is the only egress guard.
        crate::net::validate_url_not_private(&attachment.url)
            .map_err(|e| VectorError::Other(e.to_string()))?;
        let client = crate::net::build_http_client(std::time::Duration::from_secs(120)).map_err(VectorError::Other)?;
        let resp = client.get(&attachment.url).send().await
            .map_err(|e| VectorError::Other(format!("download: {e}")))?;
        if !resp.status().is_success() {
            return Err(VectorError::Other(format!("download failed: HTTP {}", resp.status())));
        }
        // Stream with a cap so a hostile/oversized blob can't OOM the process.
        let mut encrypted: Vec<u8> = Vec::with_capacity(
            resp.content_length().map(|l| (l as usize).min(MAX_DOWNLOAD)).unwrap_or(64 * 1024),
        );
        let mut stream = resp.bytes_stream();
        while let Some(chunk) = stream.next().await {
            let chunk = chunk.map_err(|e| VectorError::Other(format!("read body: {e}")))?;
            if encrypted.len() + chunk.len() > MAX_DOWNLOAD {
                return Err(VectorError::Other("attachment exceeds 256 MiB cap".into()));
            }
            encrypted.extend_from_slice(&chunk);
        }
        crate::crypto::decrypt_data(&encrypted, &attachment.key, &attachment.nonce).map_err(VectorError::Other)
    }

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

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

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

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

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

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

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

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

        // Self-wrap for recovery; bail on account swap before signing.
        let self_wrap_client = client.clone();
        let self_wrap_session = state::SessionGuard::capture();
        tokio::spawn(async move {
            if !self_wrap_session.is_valid() { return; }
            let _ = self_wrap_client.gift_wrap(&my_public_key, rumor, []).await;
        });

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

        Ok(rumor_id)
    }

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

        let client = state::nostr_client().ok_or(VectorError::Other("Not connected".into()))?;
        let my_public_key = state::my_public_key().ok_or(VectorError::Other("Not logged in".into()))?;
        let pubkey = PublicKey::from_bech32(to_npub).map_err(|e| VectorError::Nostr(e.to_string()))?;

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

        client.gift_wrap_to(
            state::active_trusted_relays().await,
            &pubkey,
            rumor,
            [Tag::expiration(expiry)],
        ).await.map_err(|e| VectorError::Nostr(e.to_string()))?;
        Ok(())
    }

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

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

        // NIP-30: resolve `:shortcode:` so the edit carries emoji image tags.
        let emoji_tags = emoji_packs::resolve_outbound_emoji_tags(new_content);

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

        // Optimistic local echo + best-effort persistence.
        let msg_for_emit = {
            let mut st = state::STATE.lock().await;
            st.update_message_in_chat(to_npub, message_id, |msg| {
                msg.apply_edit(new_content.to_string(), edit_ts_ms, emoji_tags.clone());
                msg.preview_metadata = None;
            })
        };
        if let Some(msg) = msg_for_emit {
            traits::emit_event_json("message_update", serde_json::json!({
                "old_id": message_id, "message": &msg, "chat_id": to_npub
            }));
            if let Ok(db_chat_id) = db::id_cache::get_chat_id_by_identifier(to_npub) {
                let _ = db::events::save_edit_event(
                    &edit_id, message_id, new_content, &emoji_tags, db_chat_id, None, &my_npub,
                ).await;
            }
        }

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

        let self_wrap_client = client.clone();
        let self_wrap_session = state::SessionGuard::capture();
        tokio::spawn(async move {
            if !self_wrap_session.is_valid() { return; }
            let _ = self_wrap_client.gift_wrap(&my_public_key, rumor, []).await;
        });

        Ok(edit_id)
    }

    /// Delete a DM you sent (NIP-09 over the retained gift-wrap keys).
    pub async fn delete_dm(&self, message_id: &str) -> Result<deletion::DeleteOutcome> {
        use nostr_sdk::prelude::*;
        let rumor_id = EventId::from_hex(message_id).map_err(|e| VectorError::Nostr(e.to_string()))?;
        deletion::delete_own_dm(&rumor_id).await.map_err(VectorError::Other)
    }

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

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

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

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

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

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

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

    /// Upload an image file to Blossom **unencrypted** and return its public URL — for avatars,
    /// banners, and other images other clients must fetch directly. (The opposite of
    /// [`send_file`](Self::send_file)'s encrypted attachments.) Pass the URL to [`update_profile`].
    ///
    /// [`update_profile`]: Self::update_profile
    pub async fn upload_public_image(&self, file_path: &str) -> Result<String> {
        let path = std::path::Path::new(file_path);
        let bytes = std::fs::read(path).map_err(VectorError::Io)?;
        if bytes.is_empty() {
            return Err(VectorError::Other("Empty image file".into()));
        }
        let extension = path.extension().and_then(|e| e.to_str()).unwrap_or("bin").to_lowercase();
        let mime = crate::crypto::mime_from_extension(&extension);
        let client = state::nostr_client().ok_or_else(|| VectorError::Other("Not logged in".into()))?;
        let signer = client
            .signer()
            .await
            .map_err(|e| VectorError::Other(format!("Signer unavailable: {e}")))?;
        let servers = crate::blossom_servers::compute_enabled_servers();
        if servers.is_empty() {
            return Err(VectorError::Other("No Blossom servers configured".into()));
        }
        crate::blossom::upload_blob_with_failover(signer, servers, std::sync::Arc::new(bytes), Some(mime))
            .await
            .map_err(VectorError::Other)
    }

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

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

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

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

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

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

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

    /// List every Community held locally (owned or joined), each with its channels.
    pub async fn list_communities(&self) -> Vec<serde_json::Value> {
        let ids = crate::db::community::list_community_ids().unwrap_or_default();
        let mut out = Vec::new();
        for id in ids {
            if let Ok(Some(c)) = crate::db::community::load_community(&id) {
                out.push(serde_json::json!({
                    "community_id": c.id.to_hex(),
                    "name": c.name,
                    "description": c.description,
                    "is_owner": crate::community::service::is_proven_owner(&c),
                    "channels": c.channels.iter()
                        .map(|ch| serde_json::json!({ "channel_id": ch.id.to_hex(), "name": ch.name }))
                        .collect::<Vec<_>>(),
                }));
            }
        }
        out
    }

    /// Join a Community from a public invite URL (`vectorapp.io/invite#...`). Fetches the
    /// token-encrypted bundle, persists the member-view Community, and registers its channels
    /// as chats. Returns a JSON summary.
    pub async fn join_community(&self, invite_url: &str) -> Result<serde_json::Value> {
        use crate::community::{public_invite, service, transport::LiveTransport};
        let (relays, token) = public_invite::parse_invite_url(invite_url)
            .map_err(|e| VectorError::Other(e.to_string()))?;
        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
        let bundle = service::fetch_public_invite(&transport, &relays, &token)
            .await
            .map_err(VectorError::Other)?;
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_secs())
            .unwrap_or(0);
        let community = service::accept_public_invite(&bundle, now).map_err(VectorError::Other)?;
        // Attribute our join presence to the link we used (creator + label) so the owner's per-link
        // counter ticks. Mirrors the desktop public-join path.
        let attribution = bundle.creator_npub.clone().map(|by| (by, bundle.label.clone()));
        self.finalize_member_join(community, &transport, attribution).await
    }

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

    /// Accept a PARKED private invite by community id: rebuild the member-view Community from the stored
    /// bundle, finalize the join exactly like a public link, then drop the pending row. Mirrors the
    /// desktop's consent-then-join for an invite delivered over a gift wrap.
    pub async fn accept_pending_invite(&self, community_id: &str) -> Result<serde_json::Value> {
        use crate::community::{invite::{CommunityInvite, accept_invite}, transport::LiveTransport};
        let bundle_json = crate::db::community::get_pending_invite(community_id)
            .map_err(VectorError::Other)?
            .ok_or_else(|| VectorError::Other(format!("no pending invite for {community_id}")))?;
        let invite = CommunityInvite::from_json(&bundle_json).map_err(VectorError::Other)?;
        let community = accept_invite(&invite).map_err(VectorError::Other)?;
        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
        // Private invites carry no public-link label; the inviter attribution metric is link-only.
        let summary = self.finalize_member_join(community, &transport, None).await?;
        let _ = crate::db::community::delete_pending_invite(community_id);
        Ok(summary)
    }

    /// Shared finalization for joining a Community as a member — public link OR accepted private invite.
    /// Walks any base rekey, folds the LATEST control plane (so the joiner sees current metadata, not
    /// the bundle's genesis snapshot), refuses if banned, registers the channels as chats, and announces
    /// presence. Returns the JSON summary.
    pub(crate) async fn finalize_member_join<T: crate::community::transport::Transport + ?Sized>(
        &self,
        community: crate::community::Community,
        transport: &T,
        attribution: Option<(String, Option<String>)>,
    ) -> Result<serde_json::Value> {
        use crate::community::service;
        // Persist the member-view row up front: the catch-up, the control fold, and chat registration all
        // read it back from the DB. A private bundle (unlike a public one with a preview) arrives with no
        // display metadata, so nothing else would have saved it. UPSERT — re-saving a public join is a no-op.
        crate::db::community::save_community(&community).map_err(VectorError::Other)?;
        // The bundle's root can predate a base rotation, so walk any rekey first (no-op if none) — then
        // re-load so the control fold + registration happen at the CURRENT epoch.
        if let Ok(c) = service::catch_up_server_root(transport, &community).await {
            if c.removed {
                let _ = crate::db::community::delete_community(&community.id.to_hex());
                return Err(VectorError::Other("you have been removed from this community".into()));
            }
        }
        let community = crate::db::community::load_community(&community.id)
            .map_err(VectorError::Other)?
            .unwrap_or(community);
        // Fold the LATEST control plane before we register anything — the joiner should see the current
        // name/description/roster/mode immediately, not a stale snapshot. Banlist first: an honest client
        // REFUSES to join if this npub is banned (and the just-saved community is torn back down).
        let _ = service::fetch_and_apply_control(transport, &community).await;
        if service::am_i_banned(&community) {
            let _ = crate::db::community::delete_community(&community.id.to_hex());
            return Err(VectorError::Other("you are banned from this community".into()));
        }
        // Re-load so the chat we register + the summary we return carry the freshly-folded latest metadata.
        let community = crate::db::community::load_community(&community.id)
            .map_err(VectorError::Other)?
            .unwrap_or(community);
        let owner_npub = community
            .owner_attestation
            .as_ref()
            .and_then(|att| crate::community::owner::verify_owner_attestation(att, &community.id.to_hex()))
            .and_then(|pk| ToBech32::to_bech32(&pk).ok());
        {
            let created_at_ms = crate::db::community::community_created_at_ms(&community.id);
            let mut st = state::STATE.lock().await;
            for ch in &community.channels {
                st.upsert_community_chat(
                    &ch.id.to_hex(),
                    &community.name,
                    community.description.as_deref().unwrap_or(""),
                    &community.id.to_hex(),
                    crate::community::service::is_proven_owner(&community),
                    community.icon.is_some(),
                    owner_npub.as_deref(),
                    created_at_ms,
                    community.dissolved,
                );
            }
        }
        // Best-effort join announcement (kind 3306) into the primary channel so honest peers
        // see us in their member list even before we post. Failure must not fail the join.
        if let Some(primary) = community.channels.first() {
            let _ = service::publish_presence(transport, &community, primary, true, attribution).await;
        }
        Ok(serde_json::json!({
            "community_id": community.id.to_hex(),
            "name": community.name,
            "channels": community.channels.iter()
                .map(|c| serde_json::json!({ "channel_id": c.id.to_hex(), "name": c.name }))
                .collect::<Vec<_>>(),
        }))
    }

    /// Create a Community (single "general" channel) on the default trusted relays. Signs the
    /// owner attestation with this identity (so the creator is the proven owner), registers the
    /// channel as a chat, and returns a JSON summary.
    pub async fn create_community(&self, name: &str) -> Result<serde_json::Value> {
        use crate::community::{service, transport::LiveTransport};
        let relays: Vec<String> = crate::state::active_trusted_relays()
            .await
            .iter()
            .map(|s| s.to_string())
            .collect();
        if relays.is_empty() {
            return Err(VectorError::Other("no relays available to host the Community".into()));
        }
        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
        let community = service::create_community(&transport, name, "general", relays)
            .await
            .map_err(VectorError::Other)?;
        let owner_npub = community
            .owner_attestation
            .as_ref()
            .and_then(|att| crate::community::owner::verify_owner_attestation(att, &community.id.to_hex()))
            .and_then(|pk| ToBech32::to_bech32(&pk).ok());
        {
            let created_at_ms = crate::db::community::community_created_at_ms(&community.id);
            let mut st = state::STATE.lock().await;
            for ch in &community.channels {
                st.upsert_community_chat(
                    &ch.id.to_hex(),
                    &community.name,
                    community.description.as_deref().unwrap_or(""),
                    &community.id.to_hex(),
                    crate::community::service::is_proven_owner(&community),
                    community.icon.is_some(),
                    owner_npub.as_deref(),
                    created_at_ms,
                    community.dissolved,
                );
            }
        }
        Ok(serde_json::json!({
            "community_id": community.id.to_hex(),
            "name": community.name,
            "channels": community.channels.iter()
                .map(|c| serde_json::json!({ "channel_id": c.id.to_hex(), "name": c.name }))
                .collect::<Vec<_>>(),
        }))
    }

    /// Mint a public invite link for a Community this identity owns. Returns the shareable URL.
    pub async fn create_public_invite(&self, community_id: &str) -> Result<String> {
        use crate::community::{service, transport::LiveTransport, CommunityId};
        if community_id.len() != 64 {
            return Err(VectorError::Other("malformed community id".into()));
        }
        let community = crate::db::community::load_community(&CommunityId(
            crate::simd::hex::hex_to_bytes_32(community_id),
        ))
        .map_err(VectorError::Other)?
        .ok_or_else(|| VectorError::Other("community not found".into()))?;
        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
        let (_token, url) = service::create_public_invite(&transport, &community, None, None)
            .await
            .map_err(VectorError::Other)?;
        Ok(url)
    }

    /// Send a PRIVATE invite: gift-wrap this Community's invite bundle directly to an npub over a NIP-17
    /// DM (the same transport as a regular DM). The invitee parks it pending consent (accept_pending_invite).
    /// Requires CREATE_INVITE; a banned npub can't be re-invited. Returns the wrap's event id + relays.
    pub async fn invite_to_community(&self, community_id: &str, invitee_npub: &str) -> Result<serde_json::Value> {
        use crate::community::{service, CommunityId};
        use crate::sending::{send_rumor_dm, NoOpSendCallback, SendCallback, SendConfig};

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

        if community_id.len() != 64 {
            return Err(VectorError::Other("malformed community id".into()));
        }
        let community = crate::db::community::load_community(&CommunityId(
            crate::simd::hex::hex_to_bytes_32(community_id),
        ))
        .map_err(VectorError::Other)?
        .ok_or_else(|| VectorError::Other("community not found".into()))?;

        if !service::caller_has_permission(&community, crate::community::roles::Permissions::CREATE_INVITE) {
            return Err(VectorError::Other("You need the create-invite permission to invite someone".into()));
        }
        let invitee_hex = nostr_sdk::PublicKey::parse(invitee_npub)
            .map_err(|_| VectorError::Other("invalid npub".into()))?
            .to_hex();
        if crate::db::community::get_community_banlist(community_id)
            .map_err(VectorError::Other)?
            .iter()
            .any(|b| b == &invitee_hex)
        {
            return Err(VectorError::Other("That member is banned from this community and can't be invited".into()));
        }

        // The bundle is built from purely local state; bail if the account swapped before the gift-wrap.
        if !session.is_valid() {
            return Err(VectorError::Other("account changed during invite".into()));
        }

        let rumor = crate::community::invite::build_invite_rumor(&community, my_pk).map_err(VectorError::Other)?;
        let pending_id = format!("community-invite-{}", community_id);
        // self_send=false: the owner already holds the Community; the inbound guard would drop the echo.
        let config = SendConfig { self_send: false, ..SendConfig::gui() };
        let callback: Arc<dyn SendCallback> = Arc::new(NoOpSendCallback);

        let result = send_rumor_dm(invitee_npub, &pending_id, rumor, &config, callback)
            .await
            .map_err(VectorError::Other)?;

        Ok(serde_json::json!({
            "community_id": community_id,
            "invitee": invitee_npub,
            "wrap_event_id": result.event_id,
        }))
    }

    /// The public invite links this account holds for a Community (to list + revoke). Each carries the
    /// hex `token` (the link secret) needed by [`Self::revoke_public_invite`].
    pub fn list_public_invites(&self, community_id: &str) -> Result<Vec<crate::db::community::PublicInviteRecord>> {
        crate::db::community::list_public_invites(community_id).map_err(VectorError::Other)
    }

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

    /// Post a text message to a Community channel. Returns the message id (the inner id).
    pub async fn send_community_message(
        &self,
        channel_id: &str,
        content: &str,
        replied_to: Option<&str>,
    ) -> Result<String> {
        use crate::community::{envelope, inbound, service, transport::LiveTransport};
        let (community, channel) = self.resolve_channel(channel_id)?;
        let author_pk = state::my_public_key().ok_or_else(|| VectorError::Other("Not logged in".into()))?;
        let reply = replied_to.filter(|r| !r.is_empty());
        let ms = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_millis() as u64)
            .unwrap_or(0);
        let unsigned = envelope::build_inner_typed(
            author_pk,
            &channel.id,
            channel.epoch,
            crate::stored_event::event_kind::COMMUNITY_MESSAGE,
            content,
            ms,
            reply,
            &[],
        );
        let message_id = unsigned.id.ok_or_else(|| VectorError::Other("inner event has no id".into()))?.to_hex();
        let client = state::nostr_client().ok_or_else(|| VectorError::Other("Not logged in".into()))?;
        let signer = client.signer().await.map_err(|e| VectorError::Other(format!("Signer unavailable: {e}")))?;
        let inner = unsigned.sign(&signer).await.map_err(|e| VectorError::Other(format!("sign: {e}")))?;
        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
        let outer = service::send_signed_message(&transport, &community, &channel, &inner)
            .await
            .map_err(VectorError::Other)?;
        // Local echo so get_messages reflects the send (the relay echo dedups on inner id).
        let echoed = {
            let mut st = state::STATE.lock().await;
            inbound::process_incoming(&mut st, &outer, &channel, &author_pk)
        };
        if let Some(inbound::IncomingEvent::NewMessage(msg)) = echoed {
            let _ = crate::db::events::save_message(channel_id, &msg).await;
        }
        Ok(message_id)
    }

    /// Send a file to a Community channel as an encrypted attachment. Returns the message id.
    /// Mirrors the DM file pipeline (encrypt → Blossom upload → NIP-92 `imeta`) but publishes
    /// over the community transport.
    pub async fn send_community_file(&self, channel_id: &str, file_path: &str) -> Result<String> {
        use crate::community::{attachments, envelope, inbound, service, transport::LiveTransport};
        let path = std::path::Path::new(file_path);
        let bytes = std::fs::read(path).map_err(VectorError::Io)?;
        if bytes.is_empty() {
            return Err(VectorError::Other("Empty file".into()));
        }
        let filename = path.file_name().and_then(|n| n.to_str()).unwrap_or("file").to_string();
        let extension = path.extension().and_then(|e| e.to_str()).unwrap_or("bin").to_lowercase();

        let (community, channel) = self.resolve_channel(channel_id)?;
        let author_pk = state::my_public_key().ok_or_else(|| VectorError::Other("Not logged in".into()))?;

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

        // Save the plaintext locally (hash-keyed) so the sender previews it instantly.
        let download_dir = crate::db::get_download_dir();
        let _ = std::fs::create_dir_all(&download_dir);
        let local_name = if filename.is_empty() { format!("{}.{}", &file_hash, extension) } else { filename.clone() };
        let local_path = crate::crypto::resolve_unique_filename(&download_dir, &local_name);
        let _ = std::fs::write(&local_path, &bytes);

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

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

        let attachment = crate::types::Attachment {
            id: file_hash.clone(),
            key: params.key.clone(),
            nonce: params.nonce.clone(),
            extension: extension.clone(),
            name: filename.clone(),
            url,
            path: local_path.to_string_lossy().to_string(),
            size: encrypted_size,
            img_meta,
            downloading: false,
            downloaded: true,
            ..Default::default()
        };
        let imeta = vec![attachments::attachment_to_imeta(&attachment)];
        let ms = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_millis() as u64)
            .unwrap_or(0);
        let unsigned = envelope::build_inner_full(
            author_pk, &channel.id, channel.epoch,
            stored_event::event_kind::COMMUNITY_MESSAGE, "", ms, None, &[], &imeta,
        );
        let message_id = unsigned.id.ok_or_else(|| VectorError::Other("inner event has no id".into()))?.to_hex();
        let inner = unsigned.sign(&signer).await.map_err(|e| VectorError::Other(format!("sign: {e}")))?;
        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(30));
        let outer = service::send_signed_message(&transport, &community, &channel, &inner)
            .await.map_err(VectorError::Other)?;
        // Local echo so get_messages reflects the send.
        let echoed = {
            let mut st = state::STATE.lock().await;
            inbound::process_incoming(&mut st, &outer, &channel, &author_pk)
        };
        if let Some(inbound::IncomingEvent::NewMessage(m)) = echoed {
            let _ = crate::db::events::save_message(channel_id, &m).await;
        }
        Ok(message_id)
    }

    /// Send an ephemeral typing indicator to a Community channel.
    pub async fn send_community_typing(&self, channel_id: &str) -> Result<()> {
        use crate::community::{service, transport::LiveTransport};
        let (community, channel) = self.resolve_channel(channel_id)?;
        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(8));
        service::publish_typing_signal(&transport, &community, &channel)
            .await
            .map_err(VectorError::Other)
    }

    /// React to a Community message. `emoji_url` carries the NIP-30 image URL for a custom
    /// `:shortcode:` reaction (parity with DMs).
    pub async fn send_community_reaction(
        &self,
        channel_id: &str,
        message_id: &str,
        emoji: &str,
        emoji_url: Option<&str>,
    ) -> Result<()> {
        let emoji_tags: Vec<crate::types::EmojiTag> = match emoji_url {
            Some(url) if emoji.starts_with(':') && emoji.ends_with(':') && emoji.len() >= 3 && !url.is_empty() => {
                vec![crate::types::EmojiTag { shortcode: emoji[1..emoji.len() - 1].to_string(), url: url.to_string() }]
            }
            _ => Vec::new(),
        };
        self.publish_community_control(
            channel_id, stored_event::event_kind::COMMUNITY_REACTION, emoji, message_id, &emoji_tags,
        ).await
    }

    /// Edit one of your own Community messages.
    pub async fn edit_community_message(&self, channel_id: &str, message_id: &str, new_content: &str) -> Result<()> {
        let emoji_tags = emoji_packs::resolve_outbound_emoji_tags(new_content);
        self.publish_community_control(
            channel_id, stored_event::event_kind::COMMUNITY_EDIT, new_content, message_id, &emoji_tags,
        ).await
    }

    /// Delete one of your own Community messages: a NIP-09 relay nuke when the per-message key is
    /// held, plus a cooperative tombstone so peers hide it, plus best-effort attachment cleanup.
    pub async fn delete_community_message(&self, message_id: &str) -> Result<()> {
        use crate::community::{service, transport::LiveTransport};
        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));

        let (channel_id, attachment_urls) = {
            let st = state::STATE.lock().await;
            match st.find_message(message_id) {
                Some((chat, msg)) => (
                    chat.id.clone(),
                    msg.attachments.iter().filter(|a| !a.url.is_empty()).map(|a| a.url.clone()).collect::<Vec<_>>(),
                ),
                None => return Err(VectorError::Other("message not found (already deleted?)".into())),
            }
        };

        // Layer 1 — relay nuke against the retained per-message key (best-effort).
        if crate::db::community::get_message_key(message_id).map(|k| k.is_some()).unwrap_or(false) {
            let _ = service::delete_message(&transport, message_id).await;
        }
        // Layer 2 — cooperative tombstone so peers hide it.
        self.publish_community_control(
            &channel_id, stored_event::event_kind::COMMUNITY_DELETE, "", message_id, &[],
        ).await?;
        // Layer 3 — best-effort attachment blob delete.
        if !attachment_urls.is_empty() {
            if let Some(client) = state::nostr_client() {
                if let Ok(signer) = client.signer().await {
                    crate::blossom::delete_blobs_best_effort(signer, attachment_urls);
                }
            }
        }
        // Local removal.
        let removed_chat = {
            let mut st = state::STATE.lock().await;
            st.remove_message(message_id).map(|(cid, _)| cid)
        };
        let _ = crate::db::events::delete_event(message_id).await;
        traits::emit_event_json("message_removed", serde_json::json!({
            "id": message_id, "chat_id": removed_chat.as_deref().unwrap_or(&channel_id), "reason": "deleted",
        }));
        Ok(())
    }

    /// Shared community control-event publish (reaction / edit / delete tombstone): build the
    /// inner-typed envelope, sign, send over the community transport, then locally echo + persist + emit.
    async fn publish_community_control(
        &self,
        channel_id: &str,
        kind: u16,
        content: &str,
        target: &str,
        emoji_tags: &[crate::types::EmojiTag],
    ) -> Result<()> {
        use crate::community::{envelope, inbound, service, transport::LiveTransport};
        let (community, channel) = self.resolve_channel(channel_id)?;
        let author_pk = state::my_public_key().ok_or_else(|| VectorError::Other("Not logged in".into()))?;
        let ms = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_millis() as u64)
            .unwrap_or(0);
        let unsigned = envelope::build_inner_typed(
            author_pk, &channel.id, channel.epoch, kind, content, ms, Some(target), emoji_tags,
        );
        let client = state::nostr_client().ok_or_else(|| VectorError::Other("Not logged in".into()))?;
        let signer = client.signer().await.map_err(|e| VectorError::Other(format!("Signer unavailable: {e}")))?;
        let inner = unsigned.sign(&signer).await.map_err(|e| VectorError::Other(format!("sign: {e}")))?;
        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
        let outer = service::send_signed_message(&transport, &community, &channel, &inner)
            .await.map_err(VectorError::Other)?;
        // Local echo + persist + emit (relay echo dedups on inner id).
        let outcome = {
            let mut st = state::STATE.lock().await;
            inbound::process_incoming(&mut st, &outer, &channel, &author_pk)
        };
        if let Some(inbound::IncomingEvent::Updated { target_id, message, edit_event }) = outcome {
            if let Some(ev) = edit_event {
                let mut ev = (*ev).clone();
                if let Ok(cid) = crate::db::id_cache::get_chat_id_by_identifier(channel_id) { ev.chat_id = cid; }
                let _ = crate::db::events::save_event(&ev).await;
            } else {
                let _ = crate::db::events::save_message(channel_id, &message).await;
            }
            traits::emit_event_json("message_update", serde_json::json!({
                "old_id": target_id, "message": &message, "chat_id": channel_id,
            }));
        }
        Ok(())
    }

    /// Fetch the latest page of a Community channel from relays, ingesting messages,
    /// reactions, edits, and deletes. Returns the count of brand-new messages applied.
    /// Returns `(new_message_count, warnings)`. `warnings` are NON-FATAL errors hit during the sync
    /// (catch-up, control fold, read-cut resume) — surfaced rather than swallowed so a headless caller is
    /// never blind to "the sync ran but a re-founding couldn't be resumed."
    pub async fn sync_community_channel(&self, channel_id: &str, limit: usize) -> Result<(usize, Vec<String>)> {
        use crate::community::{inbound, send, service, transport::LiveTransport};
        let my_pk = state::my_public_key().ok_or_else(|| VectorError::Other("Not logged in".into()))?;
        let (community, _) = self.resolve_channel(channel_id)?;
        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
        let mut warnings: Vec<String> = Vec::new();

        // FIRST: walk any base (server-root) rotation — a privatize / private-ban rekey advances the
        // epoch and re-anchors the control plane under the NEW root, so we must follow it BEFORE reading
        // control/messages or we'd look at stale-epoch pseudonyms and silently fall off. No-op (one cheap
        // probe) when there's been no rotation. Re-resolve after: the base epoch + root may have advanced.
        // An AUTHORIZED base rotation that excluded us (private ban / read-cut) is a removal: erase local
        // community data, exactly like an observed banlist/kick. This is the catch-all for a cut member who
        // can no longer decrypt the new control plane to read the banlist the normal way (`am_i_banned`).
        match service::catch_up_server_root(&transport, &community).await {
            Ok(c) if c.removed => {
                // ban-rekey exclusion is a self-removal → retain the held epoch keys for later self-scrub.
                let _ = crate::db::community::delete_community_retain_keys(&community.id.to_hex());
                return Ok((0, warnings));
            }
            Ok(_) => {}
            Err(e) => warnings.push(format!("base catch-up failed: {e}")),
        }
        let (community, _) = self.resolve_channel(channel_id)?;

        // Headless clients have no realtime control-plane subscription, so fold the latest control editions
        // here (the desktop does the same on its own latest-page sync). Banlist FIRST: a ban that landed on
        // us self-removes like a kick (drop keys + local data, no rejoin). Then roles, the per-creator invite
        // links (Public/Private mode), and metadata (name/description/icon/channel-name) — so a rename, role,
        // ban, or mode change reaches this member on sync, not just in a realtime client.
        if let Err(e) = service::fetch_and_apply_control(&transport, &community).await {
            warnings.push(format!("control fold failed: {e}"));
        }
        if service::am_i_banned(&community) {
            // ban self-removal → retain the held epoch keys for later self-scrub.
            let _ = crate::db::community::delete_community_retain_keys(&community.id.to_hex());
            return Ok((0, warnings));
        }
        // Walk any CHANNEL rekey so we hold the current channel key before paging it, then re-resolve so the
        // batch below carries the fresh channel epoch/key + the freshly-folded banned set + metadata.
        let (community, channel) = self.resolve_channel(channel_id)?;
        if let Err(e) = service::catch_up_channel_rekeys(&transport, &community, &channel.id).await {
            warnings.push(format!("channel catch-up failed: {e}"));
        }
        // Resume any interrupted re-founding (a privatize/ban whose rotation aborted mid-way — e.g. a
        // transient relay miss on the re-anchor). The GUI's sync did this; the agent's path did NOT, so an
        // interrupted re-founding stayed `read_cut_pending` forever (channel frozen). Best-effort + surfaced.
        let (community, _) = self.resolve_channel(channel_id)?;
        if let Err(e) = service::retry_pending_read_cut(&transport, &community).await {
            warnings.push(format!("read-cut resume failed: {e}"));
        }
        let (community, channel) = self.resolve_channel(channel_id)?;

        let events = send::fetch_channel_page(&transport, &community, &channel, None, None, limit.max(1))
            .await
            .map_err(VectorError::Other)?;
        let outcomes = {
            let mut st = state::STATE.lock().await;
            inbound::process_channel_batch(&mut st, &events, &channel, &my_pk)
        };
        let mut new = 0usize;
        for o in &outcomes {
            match o {
                inbound::IncomingEvent::NewMessage(m) => {
                    let _ = crate::db::events::save_message(channel_id, m).await;
                    new += 1;
                }
                inbound::IncomingEvent::Updated { message, .. } => {
                    let _ = crate::db::events::save_message(channel_id, message).await;
                }
                inbound::IncomingEvent::Removed { target_id } => {
                    let _ = crate::db::events::delete_event(target_id).await;
                }
                inbound::IncomingEvent::Presence { npub, joined, event_id, created_at, invited_by, invited_label } => {
                    let et = if *joined {
                        crate::stored_event::SystemEventType::MemberJoined
                    } else {
                        crate::stored_event::SystemEventType::MemberLeft
                    };
                    // attribution persisted in the note: "invited_by[|label]".
                    let note = invited_by.as_ref().map(|by| match invited_label {
                        Some(l) if !l.is_empty() => format!("{by}|{l}"),
                        _ => by.clone(),
                    });
                    let _ = crate::db::events::save_system_event_at(event_id, channel_id, et, npub, note.as_deref(), *created_at, invited_by.as_deref(), invited_label.as_deref()).await;
                }
                inbound::IncomingEvent::WebxdcPeer { npub, topic_id, node_addr, event_id, created_at } => {
                    // Persist only (DM-parity row) — the miniapp layer bootstraps from the DB at
                    // game-open. Live gossip-feed pokes are the realtime subscription's job.
                    community::service::persist_webxdc_signal(
                        channel_id, npub, topic_id, node_addr.as_deref(), event_id, *created_at,
                    ).await;
                }
                inbound::IncomingEvent::Kicked { community_id }
                | inbound::IncomingEvent::SelfLeft { community_id } => {
                    // self-removal (kick of me, or a leave I/another device authored): drop the
                    // community's local state but RETAIN the held epoch keys (later self-scrub). The core-level
                    // half of leaving; a client shell layers on subscription-refresh + chat-row teardown + UI.
                    // Stop the batch — the community is gone, so later same-batch writes would orphan rows.
                    let _ = crate::db::community::delete_community_retain_keys(community_id);
                    break;
                }
                inbound::IncomingEvent::Typing { .. } => {
                    // Realtime-only ephemeral signal; never fetched in a sync batch. No-op.
                }
            }
        }
        Ok((new, warnings))
    }

    /// Observed members of a Community (best-effort: those who've posted or announced a join,
    /// minus anyone who's left or is banned). Each entry is `{npub, last_active}`.
    pub async fn get_community_members(&self, community_id: &str) -> Vec<serde_json::Value> {
        crate::db::community::community_member_activity(community_id)
            .unwrap_or_default()
            .into_iter()
            .map(|(npub, last_active)| serde_json::json!({ "npub": npub, "last_active": last_active }))
            .collect()
    }

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

    fn load_community_hex(community_id: &str) -> Result<crate::community::Community> {
        use crate::community::CommunityId;
        if community_id.len() != 64 {
            return Err(VectorError::Other("malformed community id".into()));
        }
        crate::db::community::load_community(&CommunityId(crate::simd::hex::hex_to_bytes_32(community_id)))
            .map_err(VectorError::Other)?
            .ok_or_else(|| VectorError::Other("community not found".into()))
    }

    fn admin_role_id_of(community_id: &str) -> Result<String> {
        let roles = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
        roles.roles.iter()
            .find(|r| matches!(r.scope, crate::community::roles::RoleScope::Server)
                && r.permissions.contains(crate::community::roles::Permissions::ADMIN_ALL))
            .map(|r| r.role_id.clone())
            .ok_or_else(|| VectorError::Other("admin role not found (roster not synced?)".into()))
    }

    /// My effective management capabilities in a community (role engine — owner is just position 0). Use to
    /// confirm a promotion/demotion landed.
    pub fn community_capabilities(&self, community_id: &str) -> Result<serde_json::Value> {
        use crate::community::service;
        let community = Self::load_community_hex(community_id)?;
        let caps = service::caller_capabilities(&community);
        let manage_admin_role = Self::admin_role_id_of(community_id).ok()
            .map(|rid| service::caller_can_manage_role_id(&community, &rid))
            .unwrap_or(false);
        Ok(serde_json::json!({
            "manage_metadata": caps.manage_metadata, "manage_channels": caps.manage_channels,
            "create_invite": caps.create_invite, "kick": caps.kick, "ban": caps.ban,
            "manage_messages": caps.manage_messages, "manage_roles": caps.manage_roles,
            "manage_admin_role": manage_admin_role,
        }))
    }

    /// The community's owner npub + the admin npubs (role overview).
    pub fn community_roles(&self, community_id: &str) -> Result<serde_json::Value> {
        use nostr_sdk::prelude::{PublicKey, ToBech32};
        let community = Self::load_community_hex(community_id)?;
        let owner = community.owner_attestation.as_ref()
            .and_then(|att| crate::community::owner::verify_owner_attestation(att, &community.id.to_hex()))
            .and_then(|pk| ToBech32::to_bech32(&pk).ok());
        let roles = crate::db::community::get_community_roles(community_id).map_err(VectorError::Other)?;
        let admins: Vec<String> = roles.grants.iter().filter(|g| roles.is_admin(&g.member))
            .filter_map(|g| PublicKey::from_hex(&g.member).ok().and_then(|pk| pk.to_bech32().ok()))
            .collect();
        Ok(serde_json::json!({ "owner": owner, "admins": admins }))
    }

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

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

    /// Cooperatively kick a member (3309) — they self-remove but can rejoin. Requires KICK + outrank.
    pub async fn kick_member(&self, community_id: &str, npub: &str) -> Result<()> {
        use crate::community::{service, transport::LiveTransport};
        let hex = nostr_sdk::prelude::PublicKey::parse(npub).map_err(|_| VectorError::Other("invalid npub".into()))?.to_hex();
        let community = Self::load_community_hex(community_id)?;
        let channel = community.channels.first().ok_or_else(|| VectorError::Other("community has no channel".into()))?;
        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
        service::publish_kick(&transport, &community, channel, &hex).await.map(|_| ()).map_err(VectorError::Other)
    }

    /// Ban (`true`) or unban (`false`) a member. Ban is terminal (no rejoin); in a private community it also
    /// fires the read-cut rekey (needs a local key). Requires BAN + outrank.
    pub async fn set_member_banned(&self, community_id: &str, npub: &str, banned: bool) -> Result<()> {
        use crate::community::{service, transport::LiveTransport};
        let hex = nostr_sdk::prelude::PublicKey::parse(npub).map_err(|_| VectorError::Other("invalid npub".into()))?.to_hex();
        let community = Self::load_community_hex(community_id)?;
        // Recompute the full list (latest-wins): drop any existing entry, then add if banning.
        let mut list = crate::db::community::get_community_banlist(community_id).map_err(VectorError::Other)?;
        list.retain(|h| h != &hex);
        if banned { list.push(hex); }
        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
        service::publish_banlist(&transport, &community, &list).await.map_err(VectorError::Other)
    }

    /// Owner dissolution / "Delete Community": publish the terminal GroupDissolved tombstone (and
    /// retire the owner's own invite links, no rekey), sealing the community permanently. Owner-only
    /// (re-verified cryptographically in `service::dissolve_community`); irreversible.
    pub async fn dissolve_community(&self, community_id: &str) -> Result<()> {
        use crate::community::{service, transport::LiveTransport};
        let community = Self::load_community_hex(community_id)?;
        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
        service::dissolve_community(&transport, &community).await.map_err(VectorError::Other)
    }

    /// Edit community metadata (name / description) as an authorized member (MANAGE_METADATA). `None` leaves
    /// a field unchanged; an empty description clears it.
    pub async fn edit_community_metadata(&self, community_id: &str, name: Option<&str>, description: Option<&str>) -> Result<()> {
        use crate::community::{service, transport::LiveTransport};
        let mut community = Self::load_community_hex(community_id)?;
        if let Some(n) = name { community.name = n.to_string(); }
        if let Some(d) = description { community.description = if d.is_empty() { None } else { Some(d.to_string()) }; }
        let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
        service::republish_community_metadata(&transport, &community).await.map_err(VectorError::Other)
    }

    /// Leave a Community: announce a best-effort "left" presence (before dropping keys), then
    /// drop the held keys + local channel chats. You need a fresh invite to rejoin.
    pub async fn leave_community(&self, community_id: &str) -> Result<()> {
        use crate::community::{transport::LiveTransport, CommunityId};
        if community_id.len() != 64 {
            return Err(VectorError::Other("malformed community id".into()));
        }
        let id = CommunityId(crate::simd::hex::hex_to_bytes_32(community_id));
        let community = crate::db::community::load_community(&id).map_err(VectorError::Other)?;
        let channel_ids: Vec<String> = community
            .as_ref()
            .map(|c| c.channels.iter().map(|ch| ch.id.to_hex()).collect())
            .unwrap_or_default();
        // "Left" announcement BEFORE dropping keys (afterward we can't sign/seal into the channel).
        if let Some(ref c) = community {
            if let Some(primary) = c.channels.first() {
                let transport = LiveTransport::with_timeout(std::time::Duration::from_secs(12));
                let _ = crate::community::service::publish_presence(&transport, c, primary, false, None).await;
            }
        }
        // voluntary leave is a self-removal → retain the held epoch keys for later self-scrub.
        crate::db::community::delete_community_retain_keys(community_id).map_err(VectorError::Other)?;
        {
            let mut st = state::STATE.lock().await;
            st.chats.retain(|c| !channel_ids.contains(&c.id));
        }
        Ok(())
    }

    /// Resolve a channel id to its owning Community + the Channel (with its secret key).
    fn resolve_channel(
        &self,
        channel_id: &str,
    ) -> Result<(crate::community::Community, crate::community::Channel)> {
        use crate::community::CommunityId;
        let community_id = crate::db::community::community_id_for_channel(channel_id)
            .map_err(VectorError::Other)?
            .ok_or_else(|| VectorError::Other("Unknown Community channel".into()))?;
        if community_id.len() != 64 {
            return Err(VectorError::Other("malformed community id".into()));
        }
        let community = crate::db::community::load_community(&CommunityId(
            crate::simd::hex::hex_to_bytes_32(&community_id),
        ))
        .map_err(VectorError::Other)?
        .ok_or_else(|| VectorError::Other("Community not found".into()))?;
        let channel = community
            .channels
            .iter()
            .find(|c| c.id.to_hex() == channel_id)
            .cloned()
            .ok_or_else(|| VectorError::Other("Channel not found in Community".into()))?;
        Ok((community, channel))
    }


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

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

        // Load known wrapper IDs + timestamps for negentropy fingerprinting
        let all_items = db::wrappers::load_negentropy_items().unwrap_or_default();

        // Filter items to time window (or use all for full sync)
        let (items, filter) = if let Some(days) = since_days {
            let since_ts = Timestamp::now().as_secs().saturating_sub(days * 24 * 3600);
            let items: Vec<(EventId, Timestamp)> = all_items.iter()
                .filter(|(_, ts)| ts.as_secs() >= since_ts)
                .cloned()
                .collect();
            let filter = Filter::new()
                .pubkey(my_pk)
                .kind(Kind::GiftWrap)
                .since(Timestamp::from_secs(since_ts));
            (items, filter)
        } else {
            let filter = Filter::new()
                .pubkey(my_pk)
                .kind(Kind::GiftWrap);
            (all_items, filter)
        };

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

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

        // Race all relays — first to reconcile drives the fetch
        let relay_map = client.relays().await;
        let all_relays: Vec<(RelayUrl, Relay)> = relay_map.iter()
            .map(|(url, relay)| (url.clone(), relay.clone()))
            .collect();
        drop(relay_map);

        let mut relay_futs = futures_util::stream::FuturesUnordered::new();
        for (url, relay) in &all_relays {
            let url = url.clone();
            let relay = relay.clone();
            let f = filter.clone();
            let i = items.clone();
            let o = sync_opts.clone();
            relay_futs.push(async move {
                let result = tokio::time::timeout(
                    std::time::Duration::from_secs(10),
                    relay.sync_with_items(f, i, &o),
                ).await;
                (url, result)
            });
        }

        // Collect missing IDs from all relays
        let mut all_missing: std::collections::HashSet<EventId> = std::collections::HashSet::new();
        while let Some((url, result)) = relay_futs.next().await {
            match result {
                Ok(Ok(recon)) => {
                    let count = recon.remote.len();
                    all_missing.extend(recon.remote);
                    log_info!("[SyncDMs] {} reconciled: {} missing", url, count);
                }
                Ok(Err(e)) => log_warn!("[SyncDMs] {} failed: {}", url, e),
                Err(_) => log_warn!("[SyncDMs] {} timed out (10s)", url),
            }
        }

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

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

        let mut total_events = 0u32;
        let mut new_messages = 0u32;
        const BATCH_SIZE: usize = 500;

        for batch in ids.chunks(BATCH_SIZE) {
            let f = Filter::new().ids(batch.to_vec()).kind(Kind::GiftWrap);
            match client.stream_events_from(
                relay_strs.clone(), f,
                std::time::Duration::from_secs(30),
            ).await {
                Ok(stream) => {
                    let client_clone = client.clone();
                    let prepared_stream = stream
                        .map(move |event| {
                            let c = client_clone.clone();
                            tokio::spawn(async move {
                                event_handler::prepare_event(event, &c, my_pk).await
                            })
                        })
                        .buffer_unordered(8);
                    tokio::pin!(prepared_stream);

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

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

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

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

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

        let output = client.subscribe(filter, None).await
            .map_err(|e| VectorError::Nostr(e.to_string()))?;
        Ok(output.val)
    }

    /// Catch up every locally-held Community: fold control / re-foundings / rekeys / banlist and
    /// fetch recent messages into local state for each channel. State-only (does not replay to an
    /// [`InboundEventHandler`]). Called at `listen()` start and periodically for outage resilience;
    /// also safe to call manually after a known disconnect.
    pub async fn sync_communities(&self) -> Result<()> {
        let ids = db::community::list_community_ids().map_err(VectorError::from)?;
        for id in ids {
            if let Ok(Some(community)) = db::community::load_community(&id) {
                for ch in &community.channels {
                    let _ = self.sync_community_channel(&ch.id.to_hex(), 50).await;
                }
            }
        }
        Ok(())
    }

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

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

        // Outage resilience — catch up on connect, then re-sync periodically.
        //
        // Catch up BEFORE going realtime so a bot that was offline folds any missed re-foundings /
        // metadata / banlist changes (and recent messages) into local state, and subscribes at the
        // CURRENT epoch pseudonyms. This is state-only: historical messages are not replayed to the
        // handler (matches the gateway model) — query them via `get_messages`.
        let _ = self.sync_communities().await;
        let _ = self.sync_dms(None, &NoOpEventHandler).await;

        // Subscribe to DMs (GiftWraps) AND Community channel events — one loop dispatches both
        // through the same handler, so `on_dm_received`/`on_community_message` share a sink.
        let dm_sub_id = self.subscribe_dms().await?;
        community::realtime::refresh_subscription(&client).await;

        // Outage resilience via the relay Monitor — event-driven, not polling.
        //
        // (1) Reconnect-driven catch-up: a `limit(0)` realtime sub never replays what was published
        // while we were down, so a relay (re)connecting is exactly when we must catch up. On each
        // Connected transition we refold consensus + reconcile DMs (NIP-77 negentropy → only the
        // diff) and re-track the realtime sub at the current epochs. Idle when healthy. Stops on swap.
        if let Some(monitor) = client.monitor() {
            let mut rx = monitor.subscribe();
            let session = state::SessionGuard::capture();
            tokio::spawn(async move {
                // Debounce reconnect bursts: StatusChanged is per-relay, but one catch-up queries the
                // whole pool — so coalesce Connected transitions within a short window into one resync.
                let mut last_resync: Option<std::time::Instant> = None;
                while let Ok(notification) = rx.recv().await {
                    if !session.is_valid() {
                        return;
                    }
                    let MonitorNotification::StatusChanged { status, .. } = notification;
                    if status == RelayStatus::Connected {
                        if last_resync.is_some_and(|t| t.elapsed() < std::time::Duration::from_secs(3)) {
                            continue;
                        }
                        let _ = VectorCore.sync_communities().await;
                        let _ = VectorCore.sync_dms(None, &NoOpEventHandler).await;
                        if let Some(c) = state::nostr_client() {
                            community::realtime::refresh_subscription(&c).await;
                        }
                        last_resync = Some(std::time::Instant::now());
                    }
                }
            });
        }

        // (2) Health probe: a relay can report Connected while silently dead. Every 60s probe each
        // with a tiny query + timeout; a zombie is force-reconnected (which fires the monitor above
        // → catch-up), and Disconnected/Terminated relays are reconnected directly.
        {
            let client_health = client.clone();
            let session = state::SessionGuard::capture();
            tokio::spawn(async move {
                tokio::time::sleep(std::time::Duration::from_secs(30)).await; // warm-up
                loop {
                    if !session.is_valid() {
                        return;
                    }
                    for (url, relay) in client_health.relays().await {
                        match relay.status() {
                            RelayStatus::Connected => {
                                let probe = tokio::time::timeout(
                                    std::time::Duration::from_secs(10),
                                    client_health.fetch_events_from(
                                        vec![url.to_string()],
                                        Filter::new().kind(Kind::Metadata).limit(1),
                                        std::time::Duration::from_secs(8),
                                    ),
                                )
                                .await;
                                if !matches!(probe, Ok(Ok(_))) {
                                    let _ = relay.disconnect();
                                    tokio::time::sleep(std::time::Duration::from_millis(500)).await;
                                    let _ = relay.try_connect(std::time::Duration::from_secs(10)).await;
                                }
                            }
                            RelayStatus::Terminated | RelayStatus::Disconnected => {
                                let _ = relay.try_connect(std::time::Duration::from_secs(10)).await;
                            }
                            _ => {}
                        }
                    }
                    tokio::time::sleep(std::time::Duration::from_secs(60)).await;
                }
            });
        }

        let client_for_closure = client.clone();

        client.handle_notifications(move |notification| {
            let handler = handler.clone();
            let c = client_for_closure.clone();
            let dm_sid = dm_sub_id.clone();
            async move {
                if let RelayPoolNotification::Event { event, subscription_id, .. } = notification {
                    if subscription_id == dm_sid {
                        // DMs, files, reactions
                        let prepared = event_handler::prepare_event(*event, &c, my_pk).await;
                        event_handler::commit_prepared_event(prepared, true, &*handler).await;
                    } else if community::realtime::subscription_id().await.as_ref() == Some(&subscription_id) {
                        // Community channel messages / reactions / edits / control editions
                        let session = state::SessionGuard::capture();
                        community::realtime::dispatch_event(&session, *event, handler.clone()).await;
                    }
                }
                Ok(false)
            }
        }).await.map_err(|e| VectorError::Nostr(e.to_string()))?;

        Ok(())
    }

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

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

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

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

        // In-memory per-account state owned by vector-core's globals.
        {
            let mut st = state::STATE.lock().await;
            st.profiles.clear();
            st.chats.clear();
            st.db_loaded = false;
            st.is_syncing = false;
        }
        state::WRAPPER_ID_CACHE.lock().await.clear();
        state::PENDING_EVENTS.lock().await.clear();
        state::set_active_chat(None);
        crate::profile::sync::clear_profile_sync_queue();
        crate::inbox_relays::clear_inbox_relay_cache();
        crate::emoji_packs::clear_nip65_cache();
        // Chat/user row-id caches are PER-ACCOUNT (row ids belong to the prior account's DB). Not clearing
        // them here let a swapped-in account resolve a channel/npub to the WRONG (prior-account) row id →
        // saves FK-failed silently + reads hit the wrong row (e.g. a community member vanished post-swap).
        crate::db::clear_id_caches();
        // Community sync RAM cache (page cursors, history-start, in-flight, invite preload) is
        // account-scoped — drop it so the next account can't read A's cursors/warmed pages. The
        // generation stamp self-invalidates too, but clear explicitly for parity with the GUI swap.
        crate::community::cache::clear();
        // Community realtime route/subscription state is account-scoped (channel keys + banned sets);
        // drop it so a swapped-in account can't listen on the prior account's pseudonyms.
        crate::community::realtime::clear().await;
        // Theme-pack emoji tags are account-scoped; leaving the prior account's set active would tag the
        // next account's outbound messages with A's theme shortcodes (leaking A's pack Blossom URLs). The
        // frontend re-registers the new account's theme, but only if it HAS one — clear to be safe.
        crate::emoji_packs::set_theme_emoji_tags(Vec::new());
    }
}

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

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

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