eidetica 0.2.0

Decentralized DB. Remember Everything. Everywhere. All At Once.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
//! Synchronization module for Eidetica database.
//!
//! The Sync module manages synchronization settings and state for the database,
//! storing its configuration in a dedicated tree within the database.

use handle_trait::Handle;
use std::sync::{
    OnceLock,
    atomic::{AtomicBool, Ordering},
};
use tracing::{debug, info};

use crate::{
    Database, Entry, Instance, Result, WeakInstance,
    auth::{crypto::format_public_key, types::AuthKey},
    crdt::Doc,
    entry::ID,
    instance::backend::Backend,
    store::{DocStore, SettingsStore},
};

pub mod background;
mod bootstrap_request_manager;
pub mod error;
pub mod handler;
pub mod peer_manager;
pub mod peer_types;
pub mod protocol;
pub mod state;
pub mod transports;
mod user_sync_manager;
pub mod utils;

use background::{BackgroundSync, SyncCommand};
use bootstrap_request_manager::BootstrapRequestManager;
pub use bootstrap_request_manager::{BootstrapRequest, RequestStatus};
pub use error::SyncError;
use peer_manager::PeerManager;
pub use peer_types::{Address, ConnectionState, PeerInfo, PeerStatus};
use protocol::{SyncRequest, SyncResponse, SyncTreeRequest};
use std::time::SystemTime;
use tokio::sync::{mpsc, oneshot};
use transports::{SyncTransport, http::HttpTransport, iroh::IrohTransport};
use user_sync_manager::UserSyncManager;

/// Private constant for the sync settings subtree name
const SETTINGS_SUBTREE: &str = "settings_map";

/// Constant for the device identity key name
/// This is the name of the Device Key used as the shared identifier for this Device.
pub(crate) const DEVICE_KEY_NAME: &str = "_device_key";

/// Authentication parameters for sync operations.
#[derive(Debug, Clone)]
pub struct AuthParams {
    /// The public key making the request
    pub requesting_key: String,
    /// The name/ID of the requesting key
    pub requesting_key_name: String,
    /// The permission level being requested
    pub requested_permission: crate::auth::Permission,
}

/// Information needed to register a peer for syncing.
///
/// This is used with [`Sync::register_sync_peer()`] to declare sync intent.
#[derive(Debug, Clone)]
pub struct SyncPeerInfo {
    /// The peer's public key
    pub peer_pubkey: String,
    /// The tree/database to sync
    pub tree_id: ID,
    /// Initial address hints where the peer might be found
    pub addresses: Vec<Address>,
    /// Optional authentication parameters for bootstrap
    pub auth: Option<AuthParams>,
    /// Optional display name for the peer
    pub display_name: Option<String>,
}

/// Handle for tracking sync status with a specific peer.
///
/// Returned by [`Sync::register_sync_peer()`].
#[derive(Debug, Clone)]
pub struct SyncHandle {
    tree_id: ID,
    peer_pubkey: String,
    sync: Sync,
}

impl SyncHandle {
    /// Get the current sync status.
    pub fn status(&self) -> Result<SyncStatus> {
        self.sync.get_sync_status(&self.tree_id, &self.peer_pubkey)
    }

    /// Add another address hint for this peer.
    pub fn add_address(&self, address: Address) -> Result<()> {
        self.sync.add_peer_address(&self.peer_pubkey, address)
    }

    /// Block until initial sync completes (has local data).
    ///
    /// This is a convenience method for backwards compatibility.
    /// The sync happens in the background, this just polls until data arrives.
    pub async fn wait_for_initial_sync(&self) -> Result<()> {
        loop {
            let status = self.status()?;
            if status.has_local_data {
                return Ok(());
            }
            tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
        }
    }

    /// Get the tree ID being synced.
    pub fn tree_id(&self) -> &ID {
        &self.tree_id
    }

    /// Get the peer public key.
    pub fn peer_pubkey(&self) -> &str {
        &self.peer_pubkey
    }
}

/// Current sync status for a tree/peer pair.
#[derive(Debug, Clone)]
pub struct SyncStatus {
    /// Whether we have local data for this tree
    pub has_local_data: bool,
    /// Last time sync succeeded (if ever)
    pub last_sync: Option<SystemTime>,
    /// Last error encountered (if any)
    pub last_error: Option<String>,
}

/// Synchronization manager for the database.
///
/// The Sync module is a thin frontend that communicates with a background
/// sync engine thread via command channels. All actual sync operations, transport
/// communication, and state management happen in the background thread.
#[derive(Debug)]
pub struct Sync {
    /// Communication channel to the background sync engine (initialized once when transport is enabled)
    command_tx: OnceLock<mpsc::Sender<SyncCommand>>,
    /// The instance for read operations and tree management
    instance: WeakInstance,
    /// The tree containing synchronization settings
    sync_tree: Database,
    /// Track if transport has been enabled
    transport_enabled: AtomicBool,
}

impl Clone for Sync {
    fn clone(&self) -> Self {
        let command_tx = OnceLock::new();
        if let Some(tx) = self.command_tx.get() {
            let _ = command_tx.set(tx.clone());
        }
        Self {
            command_tx,
            instance: self.instance.clone(),
            sync_tree: self.sync_tree.clone(),
            transport_enabled: AtomicBool::new(self.transport_enabled.load(Ordering::Acquire)),
        }
    }
}

impl Sync {
    /// Create a new Sync instance with a dedicated settings tree.
    ///
    /// # Arguments
    /// * `instance` - The database instance for tree operations
    ///
    /// # Returns
    /// A new Sync instance with its own settings tree.
    pub fn new(instance: Instance) -> Result<Self> {
        // Ensure device key exists in the backend
        // If no device key exists, generate one automatically
        let signing_key = match instance.backend().get_private_key(DEVICE_KEY_NAME)? {
            Some(key) => key,
            None => {
                let (signing_key, _) = crate::auth::crypto::generate_keypair();
                instance
                    .backend()
                    .store_private_key(DEVICE_KEY_NAME, signing_key.clone())?;
                signing_key
            }
        };

        let mut sync_settings = Doc::new();
        sync_settings.set_string("name", "_sync");
        sync_settings.set_string("type", "sync_settings");

        let sync_tree = Database::create(
            sync_settings,
            &instance,
            signing_key,
            DEVICE_KEY_NAME.to_string(),
        )?;

        let sync = Self {
            command_tx: OnceLock::new(),
            instance: instance.downgrade(),
            sync_tree,
            transport_enabled: AtomicBool::new(false),
        };

        // Initialize combined settings for all tracked users
        sync.initialize_user_settings()?;

        Ok(sync)
    }

    /// Load an existing Sync instance from a sync tree root ID.
    ///
    /// # Arguments
    /// * `instance` - The database instance
    /// * `sync_tree_root_id` - The root ID of the existing sync tree
    ///
    /// # Returns
    /// A Sync instance loaded from the existing tree.
    pub fn load(instance: Instance, sync_tree_root_id: &ID) -> Result<Self> {
        let device_key = instance
            .backend()
            .get_private_key(DEVICE_KEY_NAME)?
            .ok_or_else(|| SyncError::DeviceKeyNotFound {
                key_name: DEVICE_KEY_NAME.to_string(),
            })?;

        let sync_tree = Database::open(
            instance.handle(),
            sync_tree_root_id,
            device_key,
            DEVICE_KEY_NAME.to_string(),
        )?;

        let sync = Self {
            command_tx: OnceLock::new(),
            instance: instance.downgrade(),
            sync_tree,
            transport_enabled: AtomicBool::new(false),
        };

        // Initialize combined settings for all tracked users
        sync.initialize_user_settings()?;

        Ok(sync)
    }

    /// Get the root ID of the sync settings tree.
    pub fn sync_tree_root_id(&self) -> &crate::entry::ID {
        self.sync_tree.root_id()
    }

    /// Store a setting in the sync_settings subtree.
    ///
    /// # Arguments
    /// * `key` - The setting key
    /// * `value` - The setting value
    pub fn set_setting(&self, key: impl Into<String>, value: impl Into<String>) -> Result<()> {
        let op = self.sync_tree.new_transaction()?;
        let sync_settings = op.get_store::<DocStore>(SETTINGS_SUBTREE)?;
        sync_settings.set_string(key, value)?;
        op.commit()?;
        Ok(())
    }

    /// Retrieve a setting from the settings_map subtree.
    ///
    /// # Arguments
    /// * `key` - The setting key to retrieve
    ///
    /// # Returns
    /// The setting value if found, None otherwise.
    pub fn get_setting(&self, key: impl AsRef<str>) -> Result<Option<String>> {
        let sync_settings = self
            .sync_tree
            .get_store_viewer::<DocStore>(SETTINGS_SUBTREE)?;
        match sync_settings.get_string(key) {
            Ok(value) => Ok(Some(value)),
            Err(e) if e.is_not_found() => Ok(None),
            Err(e) => Err(e),
        }
    }

    /// Upgrade the weak instance reference to a strong reference.
    ///
    /// # Returns
    /// A `Result` containing the Instance or an error if the Instance has been dropped.
    pub fn instance(&self) -> Result<Instance> {
        self.instance
            .upgrade()
            .ok_or_else(|| SyncError::InstanceDropped.into())
    }

    /// Get a reference to the underlying backend.
    pub fn backend(&self) -> Result<Backend> {
        Ok(self.instance()?.backend().handle())
    }

    /// Get a reference to the sync settings tree.
    pub fn sync_tree(&self) -> &Database {
        &self.sync_tree
    }

    /// Get the device ID for this sync instance.
    ///
    /// The device ID is the device's public key in ed25519:base64 format.
    pub fn get_device_id(&self) -> Result<String> {
        self.get_device_public_key()
    }

    /// Get the device public key for this sync instance.
    ///
    /// # Returns
    /// The device's public key in ed25519:base64 format.
    pub fn get_device_public_key(&self) -> Result<String> {
        let signing_key = self.get_device_signing_key()?;
        let verifying_key = signing_key.verifying_key();
        Ok(format_public_key(&verifying_key))
    }

    /// Get the device signing key for cryptographic operations.
    ///
    /// # Returns
    /// The device's private signing key if available.
    pub(crate) fn get_device_signing_key(&self) -> Result<ed25519_dalek::SigningKey> {
        let backend = self.backend()?;
        backend.get_private_key(DEVICE_KEY_NAME)?.ok_or_else(|| {
            SyncError::DeviceKeyNotFound {
                key_name: DEVICE_KEY_NAME.to_string(),
            }
            .into()
        })
    }

    // === Peer Management Methods ===

    /// Register a new remote peer in the sync network.
    ///
    /// # Arguments
    /// * `pubkey` - The peer's public key (formatted as ed25519:base64)
    /// * `display_name` - Optional human-readable name for the peer
    ///
    /// # Returns
    /// A Result indicating success or an error.
    pub fn register_peer(
        &self,
        pubkey: impl Into<String>,
        display_name: Option<&str>,
    ) -> Result<()> {
        let pubkey_str = pubkey.into();

        // Store in sync tree via PeerManager
        let op = self.sync_tree.new_transaction()?;
        PeerManager::new(&op).register_peer(&pubkey_str, display_name)?;
        op.commit()?;

        // Background sync will read peer info directly from sync tree when needed
        Ok(())
    }

    /// Update the status of a registered peer.
    ///
    /// # Arguments
    /// * `pubkey` - The peer's public key
    /// * `status` - The new status for the peer
    ///
    /// # Returns
    /// A Result indicating success or an error.
    pub fn update_peer_status(&self, pubkey: impl AsRef<str>, status: PeerStatus) -> Result<()> {
        let op = self.sync_tree.new_transaction()?;
        PeerManager::new(&op).update_peer_status(pubkey.as_ref(), status)?;
        op.commit()?;
        Ok(())
    }

    /// Get information about a registered peer.
    ///
    /// # Arguments
    /// * `pubkey` - The peer's public key
    ///
    /// # Returns
    /// The peer information if found, None otherwise.
    pub fn get_peer_info(&self, pubkey: impl AsRef<str>) -> Result<Option<PeerInfo>> {
        let op = self.sync_tree.new_transaction()?;
        PeerManager::new(&op).get_peer_info(pubkey.as_ref())
        // No commit - just reading
    }

    /// List all registered peers.
    ///
    /// # Returns
    /// A vector of all registered peer information.
    pub fn list_peers(&self) -> Result<Vec<PeerInfo>> {
        let op = self.sync_tree.new_transaction()?;
        PeerManager::new(&op).list_peers()
        // No commit - just reading
    }

    /// Remove a peer from the sync network.
    ///
    /// This removes the peer entry and all associated sync relationships and transport info.
    ///
    /// # Arguments
    /// * `pubkey` - The peer's public key
    ///
    /// # Returns
    /// A Result indicating success or an error.
    pub fn remove_peer(&self, pubkey: impl AsRef<str>) -> Result<()> {
        let op = self.sync_tree.new_transaction()?;
        PeerManager::new(&op).remove_peer(pubkey)?;
        op.commit()?;
        Ok(())
    }

    // === Declarative Sync API ===

    /// Register a peer for syncing (declarative API).
    ///
    /// This is the recommended way to set up syncing. It immediately registers
    /// the peer and tree/peer relationship, then the background sync engine
    /// handles the actual data synchronization.
    ///
    /// # Arguments
    /// * `info` - Information about the peer and sync configuration
    ///
    /// # Returns
    /// A handle for tracking sync status and adding more address hints.
    ///
    /// # Example
    /// ```no_run
    /// # use eidetica::*;
    /// # use eidetica::sync::{SyncPeerInfo, Address, AuthParams};
    /// # async fn example(sync: sync::Sync, peer_pubkey: String, tree_id: entry::ID) -> Result<()> {
    /// // Register peer for syncing
    /// let handle = sync.register_sync_peer(SyncPeerInfo {
    ///     peer_pubkey,
    ///     tree_id,
    ///     addresses: vec![Address {
    ///         transport_type: "http".to_string(),
    ///         address: "http://localhost:8080".to_string(),
    ///     }],
    ///     auth: None,
    ///     display_name: Some("My Peer".to_string()),
    /// })?;
    ///
    /// // Optionally wait for initial sync
    /// handle.wait_for_initial_sync().await?;
    ///
    /// // Check status anytime
    /// let status = handle.status()?;
    /// println!("Has local data: {}", status.has_local_data);
    /// # Ok(())
    /// # }
    /// ```
    pub fn register_sync_peer(&self, info: SyncPeerInfo) -> Result<SyncHandle> {
        let op = self.sync_tree.new_transaction()?;
        let peer_mgr = PeerManager::new(&op);

        // Register peer if it doesn't exist
        if peer_mgr.get_peer_info(&info.peer_pubkey)?.is_none() {
            peer_mgr.register_peer(&info.peer_pubkey, info.display_name.as_deref())?;
        }

        // Add all address hints
        for addr in &info.addresses {
            peer_mgr.add_address(&info.peer_pubkey, addr.clone())?;
        }

        // Register the tree/peer relationship
        peer_mgr.add_tree_sync(&info.peer_pubkey, &info.tree_id)?;

        // TODO: Store auth params if provided for bootstrap
        // For now, auth is passed during the actual sync handshake via on_local_write callback

        op.commit()?;

        info!(
            peer = %info.peer_pubkey,
            tree = %info.tree_id,
            address_count = info.addresses.len(),
            "Registered peer for syncing"
        );

        Ok(SyncHandle {
            tree_id: info.tree_id,
            peer_pubkey: info.peer_pubkey,
            sync: self.clone(),
        })
    }

    /// Get the current sync status for a tree/peer pair.
    ///
    /// # Arguments
    /// * `tree_id` - The tree to check
    /// * `peer_pubkey` - The peer public key
    ///
    /// # Returns
    /// Current sync status including whether we have local data.
    pub fn get_sync_status(&self, tree_id: &ID, _peer_pubkey: &str) -> Result<SyncStatus> {
        // Check if we have local data for this tree
        let backend = self.backend()?;
        let our_tips = backend.get_tips(tree_id).unwrap_or_default();

        // TODO: Track last_sync time and last_error in sync tree
        // For now, just report if we have data
        Ok(SyncStatus {
            has_local_data: !our_tips.is_empty(),
            last_sync: None,
            last_error: None,
        })
    }

    // === Database Sync Relationship Methods ===

    /// Add a tree to the sync relationship with a peer.
    ///
    /// # Arguments
    /// * `peer_pubkey` - The peer's public key
    /// * `tree_root_id` - The root ID of the tree to sync
    ///
    /// # Returns
    /// A Result indicating success or an error.
    pub fn add_tree_sync(
        &self,
        peer_pubkey: impl AsRef<str>,
        tree_root_id: impl AsRef<str>,
    ) -> Result<()> {
        let op = self.sync_tree.new_transaction()?;
        PeerManager::new(&op).add_tree_sync(peer_pubkey, tree_root_id)?;
        op.commit()?;
        Ok(())
    }

    /// Remove a tree from the sync relationship with a peer.
    ///
    /// # Arguments
    /// * `peer_pubkey` - The peer's public key
    /// * `tree_root_id` - The root ID of the tree to stop syncing
    ///
    /// # Returns
    /// A Result indicating success or an error.
    pub fn remove_tree_sync(
        &self,
        peer_pubkey: impl AsRef<str>,
        tree_root_id: impl AsRef<str>,
    ) -> Result<()> {
        let op = self.sync_tree.new_transaction()?;
        PeerManager::new(&op).remove_tree_sync(peer_pubkey, tree_root_id)?;
        op.commit()?;
        Ok(())
    }

    /// Get the list of trees synced with a peer.
    ///
    /// # Arguments
    /// * `peer_pubkey` - The peer's public key
    ///
    /// # Returns
    /// A vector of tree root IDs synced with this peer.
    pub fn get_peer_trees(&self, peer_pubkey: impl AsRef<str>) -> Result<Vec<String>> {
        let op = self.sync_tree.new_transaction()?;
        PeerManager::new(&op).get_peer_trees(peer_pubkey)
        // No commit - just reading
    }

    /// Get all peers that sync a specific tree.
    ///
    /// # Arguments
    /// * `tree_root_id` - The root ID of the tree
    ///
    /// # Returns
    /// A vector of peer public keys that sync this tree.
    pub fn get_tree_peers(&self, tree_root_id: impl AsRef<str>) -> Result<Vec<String>> {
        let op = self.sync_tree.new_transaction()?;
        PeerManager::new(&op).get_tree_peers(tree_root_id)
        // No commit - just reading
    }

    /// Connect to a remote peer and perform handshake.
    ///
    /// This method initiates a connection to a peer, performs the handshake protocol,
    /// and automatically registers the peer if successful.
    ///
    /// # Arguments
    /// * `address` - The address of the peer to connect to
    ///
    /// # Returns
    /// A Result containing the peer's public key if successful.
    pub async fn connect_to_peer(&self, address: &Address) -> Result<String> {
        let (tx, rx) = oneshot::channel();

        self.command_tx
            .get()
            .ok_or(SyncError::NoTransportEnabled)?
            .send(SyncCommand::ConnectToPeer {
                address: address.clone(),
                response: tx,
            })
            .await
            .map_err(|e| SyncError::CommandSendError(e.to_string()))?;

        rx.await
            .map_err(|e| SyncError::Network(format!("Response channel error: {e}")))?
    }

    /// Update the connection state of a peer.
    ///
    /// # Arguments
    /// * `pubkey` - The peer's public key
    /// * `state` - The new connection state
    ///
    /// # Returns
    /// A Result indicating success or an error.
    pub fn update_peer_connection_state(
        &self,
        pubkey: impl AsRef<str>,
        state: ConnectionState,
    ) -> Result<()> {
        let op = self.sync_tree.new_transaction()?;
        let peer_manager = PeerManager::new(&op);

        // Get current peer info
        let mut peer_info = match peer_manager.get_peer_info(pubkey.as_ref())? {
            Some(info) => info,
            None => return Err(SyncError::PeerNotFound(pubkey.as_ref().to_string()).into()),
        };

        // Update connection state
        peer_info.connection_state = state;
        peer_info.touch();

        // Save updated peer info
        peer_manager.update_peer_info(pubkey.as_ref(), peer_info)?;
        op.commit()?;
        Ok(())
    }

    /// Check if a tree is synced with a specific peer.
    ///
    /// # Arguments
    /// * `peer_pubkey` - The peer's public key
    /// * `tree_root_id` - The root ID of the tree
    ///
    /// # Returns
    /// True if the tree is synced with the peer, false otherwise.
    pub fn is_tree_synced_with_peer(
        &self,
        peer_pubkey: impl AsRef<str>,
        tree_root_id: impl AsRef<str>,
    ) -> Result<bool> {
        let op = self.sync_tree.new_transaction()?;
        PeerManager::new(&op).is_tree_synced_with_peer(peer_pubkey, tree_root_id)
        // No commit - just reading
    }

    // === Address Management Methods ===

    /// Add an address to a peer.
    ///
    /// # Arguments
    /// * `peer_pubkey` - The peer's public key
    /// * `address` - The address to add
    ///
    /// # Returns
    /// A Result indicating success or an error.
    pub fn add_peer_address(&self, peer_pubkey: impl AsRef<str>, address: Address) -> Result<()> {
        let peer_pubkey_str = peer_pubkey.as_ref();

        // Update sync tree via PeerManager
        let op = self.sync_tree.new_transaction()?;
        PeerManager::new(&op).add_address(peer_pubkey_str, address)?;
        op.commit()?;

        // Background sync will read updated peer info directly from sync tree when needed
        Ok(())
    }

    /// Remove a specific address from a peer.
    ///
    /// # Arguments
    /// * `peer_pubkey` - The peer's public key
    /// * `address` - The address to remove
    ///
    /// # Returns
    /// A Result indicating success or an error (true if removed, false if not found).
    pub fn remove_peer_address(
        &self,
        peer_pubkey: impl AsRef<str>,
        address: &Address,
    ) -> Result<bool> {
        let op = self.sync_tree.new_transaction()?;
        let result = PeerManager::new(&op).remove_address(peer_pubkey.as_ref(), address)?;
        op.commit()?;
        Ok(result)
    }

    /// Get addresses for a peer, optionally filtered by transport type.
    ///
    /// # Arguments
    /// * `peer_pubkey` - The peer's public key
    /// * `transport_type` - Optional transport type filter
    ///
    /// # Returns
    /// A vector of addresses matching the criteria.
    pub fn get_peer_addresses(
        &self,
        peer_pubkey: impl AsRef<str>,
        transport_type: Option<&str>,
    ) -> Result<Vec<Address>> {
        let op = self.sync_tree.new_transaction()?;
        PeerManager::new(&op).get_addresses(peer_pubkey.as_ref(), transport_type)
        // No commit - just reading
    }

    // === User Synchronization Methods ===

    /// Synchronize a user's preferences with the sync system.
    ///
    /// This establishes tracking for a user's preferences database and synchronizes
    /// their current preferences to the sync tree. The sync system will monitor the
    /// user's preferences and automatically sync databases according to their settings.
    ///
    /// This method ensures the user is tracked and reads their preferences database
    /// to update sync configuration. It detects changes via tip comparison and only
    /// processes updates when preferences have changed.
    ///
    /// This operation is idempotent and can be called multiple times safely.
    ///
    /// **CRITICAL**: All updates to the sync tree happen in a single transaction
    /// to ensure atomicity.
    ///
    /// # Arguments
    /// * `user_uuid` - The user's unique identifier
    /// * `preferences_db_id` - The ID of the user's private database
    ///
    /// # Returns
    /// A Result indicating success or an error.
    ///
    /// # Example
    /// ```rust,ignore
    /// // After creating or logging in a user
    /// let user = instance.login_user("alice", Some("password"))?;
    /// sync.sync_user(user.user_uuid(), user.user_database().root_id())?;
    /// ```
    pub fn sync_user(
        &self,
        user_uuid: impl AsRef<str>,
        preferences_db_id: &crate::entry::ID,
    ) -> Result<()> {
        use crate::store::Table;
        use crate::user::types::UserDatabasePreferences;

        let user_uuid_str = user_uuid.as_ref();

        // CRITICAL: Single transaction for all sync tree updates
        let tx = self.sync_tree.new_transaction()?;
        let user_mgr = UserSyncManager::new(&tx);

        // Ensure user is tracked, get their current preferences state
        let old_tips = match user_mgr.get_tracked_user_state(user_uuid_str)? {
            Some((_stored_prefs_db_id, tips)) => tips,
            None => {
                // User not yet tracked - register them
                user_mgr.track_user_preferences(user_uuid_str, preferences_db_id)?;
                Vec::new() // Empty tips means this is first sync
            }
        };

        // Open user's preferences database (read-only)
        let instance = self.instance.upgrade().ok_or(SyncError::InstanceDropped)?;
        let prefs_db = crate::Database::open_readonly(preferences_db_id.clone(), &instance)?;
        let current_tips = prefs_db.get_tips()?;

        // Check if preferences have changed via tip comparison
        if current_tips == old_tips {
            debug!(user_uuid = %user_uuid_str, "No changes to user preferences, skipping update");
            return Ok(());
        }

        debug!(user_uuid = %user_uuid_str, "User preferences changed, updating sync configuration");

        // Read all current preferences
        let databases_table =
            prefs_db.get_store_viewer::<Table<UserDatabasePreferences>>("databases")?;
        let all_prefs = databases_table.search(|_| true)?; // Get all entries

        // Get databases user previously tracked
        let old_databases = user_mgr.get_linked_databases(user_uuid_str)?;

        // Build set of current database IDs
        let current_databases: std::collections::HashSet<_> = all_prefs
            .iter()
            .map(|(_uuid, pref)| pref)
            .filter(|p| p.sync_settings.sync_enabled)
            .map(|p| p.database_id.clone())
            .collect();

        // Track which databases need settings recomputation
        let mut affected_databases = std::collections::HashSet::new();

        // Remove user from databases they no longer track
        for old_db in &old_databases {
            if !current_databases.contains(old_db) {
                user_mgr.unlink_user_from_database(old_db, user_uuid_str)?;
                affected_databases.insert(old_db.clone());
                debug!(user_uuid = %user_uuid_str, database_id = %old_db, "Removed user from database");
            }
        }

        // Add/update user for current databases
        for (_uuid, pref) in &all_prefs {
            if pref.sync_settings.sync_enabled {
                user_mgr.link_user_to_database(&pref.database_id, user_uuid_str)?;
                affected_databases.insert(pref.database_id.clone());
            }
        }

        // Recompute combined settings for all affected databases
        let affected_count = affected_databases.len();
        for db_id in affected_databases {
            let users = user_mgr.get_linked_users(&db_id)?;

            if users.is_empty() {
                // No users tracking this database, remove settings
                continue;
            }

            // Collect settings from all users tracking this database
            let instance = self.instance.upgrade().ok_or(SyncError::InstanceDropped)?;
            let mut settings_list = Vec::new();
            for uuid in &users {
                // Read preferences from each user's database
                if let Some((user_prefs_db_id, _)) = user_mgr.get_tracked_user_state(uuid)? {
                    let user_db = crate::Database::open_readonly(user_prefs_db_id, &instance)?;
                    let user_table =
                        user_db.get_store_viewer::<Table<UserDatabasePreferences>>("databases")?;

                    // Find this database's preferences
                    for (_pref_uuid, pref) in user_table.search(|_| true)? {
                        if pref.database_id == db_id && pref.sync_settings.sync_enabled {
                            settings_list.push(pref.sync_settings.clone());
                            break;
                        }
                    }
                }
            }

            // Merge settings using most aggressive strategy
            if !settings_list.is_empty() {
                let combined = crate::instance::settings_merge::merge_sync_settings(settings_list);
                user_mgr.set_combined_settings(&db_id, &combined)?;
                debug!(database_id = %db_id, "Updated combined settings for database");
            }
        }

        // Update stored tips to reflect processed state
        user_mgr.update_tracked_tips(user_uuid_str, &current_tips)?;

        // Commit all changes atomically
        tx.commit()?;

        info!(user_uuid = %user_uuid_str, affected_count = affected_count, "Updated user database sync configuration");
        Ok(())
    }

    /// Remove a user from the sync system.
    ///
    /// Removes all tracking for this user and updates affected databases'
    /// combined settings. This should be called when a user is deleted.
    ///
    /// # Arguments
    /// * `user_uuid` - The user's unique identifier
    ///
    /// # Returns
    /// A Result indicating success or an error.
    pub fn remove_user(&self, user_uuid: impl AsRef<str>) -> Result<()> {
        let user_uuid_str = user_uuid.as_ref();
        let tx = self.sync_tree.new_transaction()?;
        let user_mgr = UserSyncManager::new(&tx);

        // Get all databases this user was tracking
        let databases = user_mgr.get_linked_databases(user_uuid_str)?;

        // Remove user from each database
        for db_id in &databases {
            user_mgr.unlink_user_from_database(db_id, user_uuid_str)?;

            // Recompute combined settings for this database
            let remaining_users = user_mgr.get_linked_users(db_id)?;
            if remaining_users.is_empty() {
                // No more users, settings will be cleared automatically
                continue;
            }

            // Recompute settings from remaining users
            // (simplified - in practice would read each user's preferences)
            // For now, just note that settings need updating
            debug!(database_id = %db_id, "Database needs settings recomputation after user removal");
        }

        tx.commit()?;

        info!(user_uuid = %user_uuid_str, database_count = databases.len(), "Removed user from sync system");
        Ok(())
    }

    // === Network Transport Methods ===

    /// Start a sync server on the specified address (async version).
    ///
    /// # Arguments
    /// * `addr` - The address to bind the server to (e.g., "127.0.0.1:8080")
    ///
    /// # Returns
    /// A Result indicating success or failure of server startup.
    pub async fn start_server_async(&self, addr: &str) -> Result<()> {
        if !self.transport_enabled.load(Ordering::Acquire) {
            return Err(SyncError::NoTransportEnabled.into());
        }

        let (tx, rx) = oneshot::channel();

        self.command_tx
            .get()
            .ok_or(SyncError::NoTransportEnabled)?
            .send(SyncCommand::StartServer {
                addr: addr.to_string(),
                response: tx,
            })
            .await
            .map_err(|e| SyncError::CommandSendError(e.to_string()))?;

        rx.await
            .map_err(|e| SyncError::Network(format!("Response channel error: {e}")))?
    }

    /// Stop the running sync server (async version).
    ///
    /// # Returns
    /// A Result indicating success or failure of server shutdown.
    pub async fn stop_server_async(&self) -> Result<()> {
        if !self.transport_enabled.load(Ordering::Acquire) {
            return Err(SyncError::NoTransportEnabled.into());
        }
        let (tx, rx) = oneshot::channel();

        self.command_tx
            .get()
            .ok_or(SyncError::NoTransportEnabled)?
            .send(SyncCommand::StopServer { response: tx })
            .await
            .map_err(|e| SyncError::CommandSendError(e.to_string()))?;

        let result = rx
            .await
            .map_err(|e| SyncError::Network(format!("Response channel error: {e}")))?;

        // Clear the transport_enabled flag after successfully stopping the server
        if result.is_ok() {
            self.transport_enabled.store(false, Ordering::Release);
        }

        result
    }

    /// Enable HTTP transport for network communication.
    ///
    /// This initializes the HTTP transport layer and starts the background sync engine.
    pub fn enable_http_transport(&self) -> Result<()> {
        let transport = HttpTransport::new()?;
        self.start_background_sync(Box::new(transport))?;
        self.transport_enabled.store(true, Ordering::Release);
        Ok(())
    }

    /// Enable Iroh transport for peer-to-peer network communication.
    ///
    /// This initializes the Iroh transport layer with production defaults (n0's relay servers)
    /// and starts the background sync engine.
    pub fn enable_iroh_transport(&self) -> Result<()> {
        let transport = IrohTransport::new()?;
        self.start_background_sync(Box::new(transport))?;
        self.transport_enabled.store(true, Ordering::Release);
        Ok(())
    }

    /// Enable Iroh transport with custom configuration.
    ///
    /// This allows specifying custom relay modes, discovery options, etc.
    /// Use IrohTransport::builder() to create a configured transport.
    pub fn enable_iroh_transport_with_config(&self, transport: IrohTransport) -> Result<()> {
        self.start_background_sync(Box::new(transport))?;
        self.transport_enabled.store(true, Ordering::Release);
        Ok(())
    }

    /// Add a transport with a pre-created transport instance.
    ///
    /// This is useful for testing and advanced configuration scenarios.
    /// Eventually we will support multiple concurrent transports.
    pub fn add_transport(&self, transport: Box<dyn SyncTransport>) -> Result<()> {
        self.start_background_sync(transport)?;
        self.transport_enabled.store(true, Ordering::Release);
        Ok(())
    }

    /// Start the background sync engine with the given transport
    fn start_background_sync(&self, transport: Box<dyn SyncTransport>) -> Result<()> {
        if self.transport_enabled.load(Ordering::Acquire) {
            return Err(SyncError::ServerAlreadyRunning {
                // This is a placeholder until the backend supports multiple transports simultaneously.
                address: "background sync".to_string(),
            }
            .into());
        }

        let sync_tree_id = self.sync_tree.root_id().clone();
        let instance = self.instance()?;

        // Create the background sync and get command sender
        let command_tx = if tokio::runtime::Handle::try_current().is_ok() {
            BackgroundSync::start(transport, instance, sync_tree_id)
        } else {
            // If not in async context, create a runtime to spawn the background task
            let rt = tokio::runtime::Runtime::new()
                .map_err(|e| SyncError::RuntimeCreation(e.to_string()))?;

            let _guard = rt.enter();
            let tx = BackgroundSync::start(transport, instance, sync_tree_id);

            // Keep the runtime alive by detaching it
            std::mem::forget(rt);
            tx
        };

        // Initialize the command channel (can only be done once)
        self.command_tx
            .set(command_tx)
            .map_err(|_| SyncError::ServerAlreadyRunning {
                address: "command channel already initialized".to_string(),
            })?;

        Ok(())
    }

    /// Get the server address if the transport is running a server.
    ///
    /// # Returns
    /// The address the server is bound to, or an error if no server is running.
    /// Get the server address (async version).
    pub async fn get_server_address_async(&self) -> Result<String> {
        if !self.transport_enabled.load(Ordering::Acquire) {
            return Err(SyncError::NoTransportEnabled.into());
        }
        let (tx, rx) = oneshot::channel();

        self.command_tx
            .get()
            .ok_or(SyncError::NoTransportEnabled)?
            .send(SyncCommand::GetServerAddress { response: tx })
            .await
            .map_err(|e| SyncError::CommandSendError(e.to_string()))?;

        rx.await
            .map_err(|e| SyncError::Network(format!("Response channel error: {e}")))?
    }

    /// Get the server address (sync version).
    ///
    /// Note: This method may not work correctly when called from within an async context.
    /// Use get_server_address_async() instead when possible.
    pub fn get_server_address(&self) -> Result<String> {
        // Try to use existing async context, or create runtime if needed
        if let Ok(handle) = tokio::runtime::Handle::try_current() {
            handle.block_on(self.get_server_address_async())
        } else {
            let runtime = tokio::runtime::Runtime::new()
                .map_err(|e| SyncError::RuntimeCreation(e.to_string()))?;

            runtime.block_on(self.get_server_address_async())
        }
    }

    /// Start a sync server on the specified address.
    ///
    /// # Arguments
    /// * `addr` - The address to bind the server to (e.g., "127.0.0.1:8080")
    ///
    /// # Returns
    /// A Result indicating success or failure of server startup.
    pub fn start_server(&self, addr: impl AsRef<str>) -> Result<()> {
        // Try to use existing async context, or create runtime if needed
        if let Ok(handle) = tokio::runtime::Handle::try_current() {
            handle.block_on(self.start_server_async(addr.as_ref()))
        } else {
            let runtime = tokio::runtime::Runtime::new()
                .map_err(|e| SyncError::RuntimeCreation(e.to_string()))?;

            runtime.block_on(self.start_server_async(addr.as_ref()))
        }
    }

    /// Stop the running sync server.
    ///
    /// # Returns
    /// A Result indicating success or failure of server shutdown.
    pub fn stop_server(&self) -> Result<()> {
        // Try to use existing async context, or create runtime if needed
        if let Ok(handle) = tokio::runtime::Handle::try_current() {
            handle.block_on(self.stop_server_async())
        } else {
            let runtime = tokio::runtime::Runtime::new()
                .map_err(|e| SyncError::RuntimeCreation(e.to_string()))?;

            runtime.block_on(self.stop_server_async())
        }
    }

    // === Core Sync Methods ===

    /// Synchronize a specific tree with a peer using bidirectional sync.
    ///
    /// This is the main synchronization method that implements tip exchange
    /// and bidirectional entry transfer to keep trees in sync between peers.
    /// It performs both pull (fetch missing entries) and push (send our entries).
    ///
    /// # Arguments
    /// * `peer_pubkey` - The public key of the peer to sync with
    /// * `tree_id` - The ID of the tree to synchronize
    ///
    /// # Returns
    /// A Result indicating success or failure of the sync operation.
    pub async fn sync_tree_with_peer(
        &self,
        peer_pubkey: &str,
        tree_id: &crate::entry::ID,
    ) -> Result<()> {
        // Get peer information and address
        let peer_info = self
            .get_peer_info(peer_pubkey)?
            .ok_or_else(|| SyncError::PeerNotFound(peer_pubkey.to_string()))?;

        let address = peer_info
            .addresses
            .first()
            .ok_or_else(|| SyncError::Network("No addresses found for peer".to_string()))?;

        // Get our current tips for this tree (empty if tree doesn't exist)
        let backend = self.backend()?;
        let our_tips = backend
            .get_tips(tree_id)
            .map_err(|e| SyncError::BackendError(format!("Failed to get local tips: {e}")))?;

        // Get our device public key for automatic peer tracking
        let our_device_pubkey = self.get_device_public_key().ok();

        // Send unified sync request
        let request = SyncRequest::SyncTree(SyncTreeRequest {
            tree_id: tree_id.clone(),
            our_tips,
            peer_pubkey: our_device_pubkey,
            requesting_key: None, // TODO: Add auth support for direct sync
            requesting_key_name: None,
            requested_permission: None,
        });

        // Send request via background sync command
        let (tx, rx) = oneshot::channel();
        self.command_tx
            .get()
            .ok_or(SyncError::NoTransportEnabled)?
            .send(SyncCommand::SendRequest {
                address: address.clone(),
                request,
                response: tx,
            })
            .await
            .map_err(|e| SyncError::CommandSendError(e.to_string()))?;

        let response = rx
            .await
            .map_err(|e| SyncError::Network(format!("Response channel error: {e}")))?
            .map_err(|e| SyncError::Network(format!("Request failed: {e}")))?;

        match response {
            SyncResponse::Bootstrap(bootstrap_response) => {
                self.handle_bootstrap_response(bootstrap_response).await?;
            }
            SyncResponse::Incremental(incremental_response) => {
                self.handle_incremental_response(incremental_response, address)
                    .await?;
            }
            SyncResponse::Error(msg) => {
                return Err(SyncError::SyncProtocolError(format!("Sync error: {msg}")).into());
            }
            _ => {
                return Err(SyncError::UnexpectedResponse {
                    expected: "Bootstrap or Incremental",
                    actual: format!("{response:?}"),
                }
                .into());
            }
        }

        // Track tree/peer relationship for sync_on_commit to work
        // This allows on_local_write() to find this peer when queueing entries
        self.add_tree_sync(peer_pubkey, tree_id)?;

        Ok(())
    }

    /// Handle bootstrap response by storing root and all entries
    async fn handle_bootstrap_response(&self, response: protocol::BootstrapResponse) -> Result<()> {
        tracing::info!(tree_id = %response.tree_id, "Processing bootstrap response");

        // Store root entry first

        // Store the root entry
        let backend = self.backend()?;
        backend
            .put_verified(response.root_entry.clone())
            .map_err(|e| SyncError::BackendError(format!("Failed to store root entry: {e}")))?;

        // Store all other entries using existing method
        self.store_received_entries(&response.tree_id, response.all_entries)
            .await?;

        tracing::info!(tree_id = %response.tree_id, "Bootstrap completed successfully");
        Ok(())
    }

    /// Handle incremental response by storing missing entries and sending back what server is missing
    async fn handle_incremental_response(
        &self,
        response: protocol::IncrementalResponse,
        peer_address: &peer_types::Address,
    ) -> Result<()> {
        tracing::debug!(tree_id = %response.tree_id, "Processing incremental response");

        // Step 1: Store missing entries
        self.store_received_entries(&response.tree_id, response.missing_entries)
            .await?;

        // Step 2: Check if server is missing entries from us
        let backend = self.backend()?;
        let our_tips = backend.get_tips(&response.tree_id)?;
        let their_tips = &response.their_tips;

        // Find tips they don't have
        let missing_tip_ids: Vec<_> = our_tips
            .iter()
            .filter(|tip_id| !their_tips.contains(tip_id))
            .cloned()
            .collect();

        if !missing_tip_ids.is_empty() {
            tracing::debug!(
                tree_id = %response.tree_id,
                missing_tips = missing_tip_ids.len(),
                "Server is missing some of our entries, sending them back"
            );

            // Collect entries server is missing
            let backend = self.backend()?;
            let entries_for_server = crate::sync::utils::collect_ancestors_to_send(
                backend.as_backend_impl(),
                &missing_tip_ids,
                their_tips,
            )?;

            if !entries_for_server.is_empty() {
                // Send these entries back to server
                self.send_missing_entries_to_peer(
                    peer_address,
                    &response.tree_id,
                    entries_for_server,
                )
                .await?;
            }
        }

        tracing::debug!(tree_id = %response.tree_id, "Incremental sync completed");
        Ok(())
    }

    /// Send entries that the server is missing back to complete bidirectional sync
    async fn send_missing_entries_to_peer(
        &self,
        peer_address: &peer_types::Address,
        tree_id: &crate::entry::ID,
        entries: Vec<Entry>,
    ) -> Result<()> {
        if entries.is_empty() {
            return Ok(());
        }

        tracing::debug!(
            tree_id = %tree_id,
            entry_count = entries.len(),
            "Sending missing entries back to peer for bidirectional sync"
        );

        let request = protocol::SyncRequest::SendEntries(entries);

        // Send via command channel
        let (tx, rx) = tokio::sync::oneshot::channel();
        self.command_tx
            .get()
            .ok_or(SyncError::NoTransportEnabled)?
            .send(SyncCommand::SendRequest {
                address: peer_address.clone(),
                request,
                response: tx,
            })
            .await
            .map_err(|e| SyncError::CommandSendError(e.to_string()))?;

        // Wait for acknowledgment
        let response = rx
            .await
            .map_err(|e| SyncError::Network(format!("Response channel error: {e}")))?
            .map_err(|e| SyncError::Network(format!("Request failed: {e}")))?;

        match response {
            protocol::SyncResponse::Ack | protocol::SyncResponse::Count(_) => {
                tracing::debug!(tree_id = %tree_id, "Server acknowledged receipt of missing entries");
                Ok(())
            }
            protocol::SyncResponse::Error(e) => {
                Err(SyncError::Network(format!("Server error receiving entries: {e}")).into())
            }
            _ => Err(SyncError::UnexpectedResponse {
                expected: "Ack or Count",
                actual: format!("{response:?}"),
            }
            .into()),
        }
    }

    /// Validate and store received entries from a peer.
    async fn store_received_entries(
        &self,
        _tree_id: &crate::entry::ID,
        entries: Vec<Entry>,
    ) -> Result<()> {
        for entry in entries {
            // Basic validation: check that entry ID matches content
            let calculated_id = entry.id();
            if entry.id() != calculated_id {
                return Err(SyncError::InvalidEntry(format!(
                    "Entry ID {} doesn't match calculated ID {}",
                    entry.id(),
                    calculated_id
                ))
                .into());
            }

            // TODO: Add more validation (signatures, parent existence, etc.)

            // Store the entry (marking it as verified for now)
            let backend = self.backend()?;
            backend
                .put_verified(entry)
                .map_err(|e| SyncError::BackendError(format!("Failed to store entry: {e}")))?;
        }

        Ok(())
    }

    /// Send a batch of entries to a sync peer (async version).
    ///
    /// # Arguments
    /// * `entries` - The entries to send
    /// * `address` - The address of the peer to send to
    ///
    /// # Returns
    /// A Result indicating whether the entries were successfully acknowledged.
    pub async fn send_entries_async(
        &self,
        entries: impl AsRef<[Entry]>,
        address: &Address,
    ) -> Result<()> {
        let entries_vec = entries.as_ref().to_vec();
        let request = SyncRequest::SendEntries(entries_vec);
        let response = self.send_request_async(&request, address).await?;

        match response {
            SyncResponse::Ack | SyncResponse::Count(_) => Ok(()),
            SyncResponse::Error(msg) => Err(SyncError::SyncProtocolError(format!(
                "Peer {} returned error: {}",
                address.address, msg
            ))
            .into()),
            _ => Err(SyncError::UnexpectedResponse {
                expected: "Ack or Count",
                actual: format!("{response:?}"),
            }
            .into()),
        }
    }

    /// Send a batch of entries to a sync peer.
    ///
    /// # Arguments
    /// * `entries` - The entries to send
    /// * `address` - The address of the peer to send to
    ///
    /// # Returns
    /// A Result indicating whether the entries were successfully acknowledged.
    pub fn send_entries(&self, entries: impl AsRef<[Entry]>, address: &Address) -> Result<()> {
        // Try to use existing async context, or create runtime if needed
        if let Ok(handle) = tokio::runtime::Handle::try_current() {
            handle.block_on(self.send_entries_async(entries, address))
        } else {
            let entries_ref = entries.as_ref();
            let runtime = tokio::runtime::Runtime::new()
                .map_err(|e| SyncError::RuntimeCreation(e.to_string()))?;

            runtime.block_on(self.send_entries_async(entries_ref, address))
        }
    }

    /// Send specific entries to a peer via the background sync engine.
    ///
    /// This method queues entries for direct transmission without duplicate filtering.
    /// The caller is responsible for determining which entries should be sent.
    ///
    /// # Duplicate Prevention Architecture
    ///
    /// Eidetica uses **smart duplicate prevention** in the background sync engine:
    /// - **Database sync** (`SyncWithPeer` command): Uses tip comparison for semantic filtering
    /// - **Direct send** (this method): Trusts caller to provide appropriate entries
    ///
    /// For automatic duplicate prevention, use tree-based sync relationships instead
    /// of calling this method directly.
    ///
    /// # Arguments
    /// * `peer_pubkey` - The public key of the peer to send to
    /// * `entries` - The specific entries to send (no filtering applied)
    ///
    /// # Returns
    /// A Result indicating whether the command was successfully queued for background processing.
    pub async fn send_entries_to_peer(&self, peer_pubkey: &str, entries: Vec<Entry>) -> Result<()> {
        self.command_tx
            .get()
            .ok_or(SyncError::NoTransportEnabled)?
            .send(SyncCommand::SendEntries {
                peer: peer_pubkey.to_string(),
                entries,
            })
            .await
            .map_err(|e| SyncError::CommandSendError(e.to_string()))?;
        Ok(())
    }

    /// Queue an entry for sync to a peer (non-blocking, for use in callbacks).
    ///
    /// This method is designed for use in write callbacks where async operations
    /// are not possible. It uses try_send to avoid blocking, and logs errors
    /// rather than failing the callback.
    ///
    /// # Arguments
    /// * `peer_pubkey` - The public key of the peer to sync with
    /// * `entry_id` - The ID of the entry to queue
    /// * `tree_id` - The tree ID where the entry belongs
    ///
    /// # Returns
    /// Ok(()) if the entry was successfully queued or the queue was full.
    /// Only returns Err if transport is not enabled.
    pub fn queue_entry_for_sync(
        &self,
        peer_pubkey: &str,
        entry_id: &ID,
        tree_id: &ID,
    ) -> Result<()> {
        let command_tx = self.command_tx.get().ok_or(SyncError::NoTransportEnabled)?;

        let command = SyncCommand::QueueEntry {
            peer: peer_pubkey.to_string(),
            entry_id: entry_id.clone(),
            tree_id: tree_id.clone(),
        };

        // Use try_send for non-blocking operation
        // Log errors but don't fail since this is called during commit
        if let Err(e) = command_tx.try_send(command) {
            tracing::error!(
                "Failed to queue entry {:?} for sync with peer {}: {}",
                entry_id,
                peer_pubkey,
                e
            );
        }

        Ok(())
    }

    /// Handle local write events for automatic sync.
    ///
    /// This method is called by the Instance write callback system when entries
    /// are committed locally. It looks up the combined sync settings for the database
    /// and queues the entry for sync with all configured peers if sync is enabled.
    ///
    /// This is the core method that implements automatic sync-on-commit behavior.
    ///
    /// # Arguments
    /// * `entry` - The newly committed entry
    /// * `database` - The database where the entry was committed
    /// * `_instance` - The instance (unused but required by callback signature)
    ///
    /// # Returns
    /// Ok(()) on success, or an error if settings lookup fails
    pub(crate) fn on_local_write(
        &self,
        entry: &Entry,
        database: &Database,
        _instance: &Instance,
    ) -> Result<()> {
        // Early return if transport not enabled
        if !self.transport_enabled.load(Ordering::Acquire) {
            return Ok(());
        }

        // Look up combined settings for this database
        let tx = self.sync_tree.new_transaction()?;
        let user_mgr = UserSyncManager::new(&tx);
        let peer_mgr = PeerManager::new(&tx);

        let combined_settings = match user_mgr.get_combined_settings(database.root_id())? {
            Some(settings) => settings,
            None => {
                // No settings configured for this database - no sync needed
                debug!(database_id = %database.root_id(), "No sync settings for database, skipping");
                return Ok(());
            }
        };

        // Check if sync is enabled and sync_on_commit is true
        if !combined_settings.sync_enabled || !combined_settings.sync_on_commit {
            debug!(
                database_id = %database.root_id(),
                sync_enabled = combined_settings.sync_enabled,
                sync_on_commit = combined_settings.sync_on_commit,
                "Sync not enabled for database"
            );
            return Ok(());
        }

        // Get list of peers for this database
        let peers = peer_mgr.get_tree_peers(database.root_id())?;

        if peers.is_empty() {
            debug!(database_id = %database.root_id(), "No peers configured for database");
            return Ok(());
        }

        // Queue entry for sync with each peer
        let entry_id = entry.id();
        let tree_id = database.root_id();

        debug!(
            database_id = %tree_id,
            entry_id = %entry_id,
            peer_count = peers.len(),
            "Queueing entry for automatic sync"
        );

        for peer_pubkey in peers {
            self.queue_entry_for_sync(&peer_pubkey, &entry_id, tree_id)?;
        }

        Ok(())
    }

    /// Initialize combined settings for all users.
    ///
    /// This is called during Sync initialization. For new sync trees (just created),
    /// it scans the _users database to register all existing users. For existing
    /// sync trees (loaded), it updates combined settings for already-tracked users.
    fn initialize_user_settings(&self) -> Result<()> {
        use crate::store::{DocStore, Table};
        use crate::user::types::UserInfo;

        // Check if sync tree is freshly created (no users tracked yet)
        let user_tracking = self
            .sync_tree
            .get_store_viewer::<DocStore>(user_sync_manager::USER_TRACKING_SUBTREE)?;
        let all_tracked = user_tracking.get_all()?;

        if all_tracked.keys().count() == 0 {
            // New sync tree - register all users from _users database
            let instance = self.instance.upgrade().ok_or(SyncError::InstanceDropped)?;
            let users_db = instance.users_db()?;
            let users_table = users_db.get_store_viewer::<Table<UserInfo>>("users")?;
            let all_users = users_table.search(|_| true)?;

            for (user_uuid, user_info) in all_users {
                self.sync_user(&user_uuid, &user_info.user_database_id)?;
            }
        } else {
            // Existing sync tree - update settings for tracked users if changed
            let tx = self.sync_tree.new_transaction()?;
            let user_mgr = UserSyncManager::new(&tx);

            for user_uuid in all_tracked.keys() {
                if let Some((prefs_db_id, _tips)) = user_mgr.get_tracked_user_state(user_uuid)? {
                    self.sync_user(user_uuid, &prefs_db_id)?;
                }
            }
        }

        Ok(())
    }

    /// Send a sync request to a peer and get a response (async version).
    ///
    /// # Arguments
    /// * `request` - The sync request to send
    /// * `address` - The address of the peer
    ///
    /// # Returns
    /// The sync response from the peer.
    async fn send_request_async(
        &self,
        request: &SyncRequest,
        address: &Address,
    ) -> Result<SyncResponse> {
        if !self.transport_enabled.load(Ordering::Acquire) {
            return Err(SyncError::NoTransportEnabled.into());
        }
        let (tx, rx) = oneshot::channel();

        self.command_tx
            .get()
            .ok_or(SyncError::NoTransportEnabled)?
            .send(SyncCommand::SendRequest {
                address: address.clone(),
                request: request.clone(),
                response: tx,
            })
            .await
            .map_err(|e| SyncError::CommandSendError(e.to_string()))?;

        rx.await
            .map_err(|e| SyncError::Network(format!("Response channel error: {e}")))?
    }

    /// Discover available trees from a peer (simplified API).
    ///
    /// This method connects to a peer and retrieves the list of trees they're willing to sync.
    /// This is useful for discovering what can be synced before setting up sync relationships.
    ///
    /// # Arguments
    /// * `peer_address` - The address of the peer to connect to (format: "host:port")
    ///
    /// # Returns
    /// A vector of TreeInfo describing available trees, or an error.
    pub async fn discover_peer_trees(&self, peer_address: &str) -> Result<Vec<protocol::TreeInfo>> {
        use peer_types::Address;

        let address = Address {
            transport_type: "http".to_string(),
            address: peer_address.to_string(),
        };

        // Connect and get handshake info
        let _peer_pubkey = self.connect_to_peer(&address).await?;

        // The handshake already contains the tree list, but we need to get it again
        // since connect_to_peer doesn't return it. For now, return empty list
        // TODO: Enhance this to actually return the tree list from handshake

        tracing::warn!(
            "discover_peer_trees not fully implemented - handshake contains tree info but API needs enhancement"
        );
        Ok(vec![])
    }

    /// Sync with a peer at a given address.
    ///
    /// This is a blocking convenience method that:
    /// 1. Connects to discover the peer's public key
    /// 2. Registers the peer and performs immediate sync
    /// 3. Returns after sync completes
    ///
    /// For new code, prefer using [`register_sync_peer()`](Self::register_sync_peer)
    /// directly, which registers intent and lets background sync handle it.
    ///
    /// # Arguments
    /// * `peer_address` - The address of the peer (format: "host:port")
    /// * `tree_id` - Optional tree ID to sync (None = discover available trees)
    ///
    /// # Returns
    /// Result indicating success or failure.
    pub async fn sync_with_peer(
        &self,
        peer_address: &str,
        tree_id: Option<&crate::entry::ID>,
    ) -> Result<()> {
        use peer_types::Address;

        // Auto-detect transport type from address format
        let address = if peer_address.starts_with('{') || peer_address.contains("\"node_id\"") {
            // JSON format indicates Iroh NodeAddr
            Address {
                transport_type: "iroh".to_string(),
                address: peer_address.to_string(),
            }
        } else {
            // Default to HTTP for traditional host:port format
            Address {
                transport_type: "http".to_string(),
                address: peer_address.to_string(),
            }
        };

        // Connect to peer if not already connected
        let peer_pubkey = self.connect_to_peer(&address).await?;

        // Store the address for this peer (needed for sync_tree_with_peer)
        self.add_peer_address(&peer_pubkey, address.clone())?;

        if let Some(tree_id) = tree_id {
            // Sync specific tree
            self.sync_tree_with_peer(&peer_pubkey, tree_id).await?;
        } else {
            // TODO: Sync all available trees
            tracing::warn!(
                "Syncing all trees not yet implemented - need to enhance discover_peer_trees first"
            );
        }

        Ok(())
    }

    /// Sync a specific tree with a peer, with optional authentication for bootstrap.
    ///
    /// This is a lower-level method that allows specifying authentication parameters
    /// for bootstrap scenarios where access needs to be requested.
    ///
    /// # Arguments
    /// * `peer_pubkey` - The public key of the peer to sync with
    /// * `tree_id` - The ID of the tree to sync
    /// * `requesting_key` - Optional public key requesting access (for bootstrap)
    /// * `requesting_key_name` - Optional name/ID of the requesting key
    /// * `requested_permission` - Optional permission level being requested
    ///
    /// # Returns
    /// A Result indicating success or failure.
    pub async fn sync_tree_with_peer_auth(
        &self,
        peer_pubkey: &str,
        tree_id: &crate::entry::ID,
        requesting_key: Option<&str>,
        requesting_key_name: Option<&str>,
        requested_permission: Option<crate::auth::Permission>,
    ) -> Result<()> {
        // Get peer information and address
        let peer_info = self
            .get_peer_info(peer_pubkey)?
            .ok_or_else(|| SyncError::PeerNotFound(peer_pubkey.to_string()))?;

        let address = peer_info
            .addresses
            .first()
            .ok_or_else(|| SyncError::Network("No addresses found for peer".to_string()))?;

        // Get our current tips for this tree (empty if tree doesn't exist)
        let backend = self.backend()?;
        let our_tips = backend
            .get_tips(tree_id)
            .map_err(|e| SyncError::BackendError(format!("Failed to get local tips: {e}")))?;

        // Get our device public key for automatic peer tracking
        let our_device_pubkey = self.get_device_public_key().ok();

        // Send unified sync request with auth parameters
        let request = SyncRequest::SyncTree(SyncTreeRequest {
            tree_id: tree_id.clone(),
            our_tips,
            peer_pubkey: our_device_pubkey,
            requesting_key: requesting_key.map(|k| k.to_string()),
            requesting_key_name: requesting_key_name.map(|k| k.to_string()),
            requested_permission,
        });

        // Send request via background sync command
        let (tx, rx) = oneshot::channel();
        self.command_tx
            .get()
            .ok_or(SyncError::NoTransportEnabled)?
            .send(SyncCommand::SendRequest {
                address: address.clone(),
                request,
                response: tx,
            })
            .await
            .map_err(|_| {
                SyncError::CommandSendError("Background sync command channel closed".to_string())
            })?;

        // Wait for response
        let response = rx
            .await
            .map_err(|_| {
                SyncError::CommandSendError("Background sync response channel closed".to_string())
            })?
            .map_err(|e| SyncError::Network(format!("Sync request failed: {e}")))?;

        // Handle the response (same logic as existing sync_tree_with_peer)
        match response {
            SyncResponse::Bootstrap(bootstrap_response) => {
                info!(peer = %peer_pubkey, tree = %tree_id, entry_count = bootstrap_response.all_entries.len() + 1, "Received bootstrap response");

                // Store the root entry
                let backend = self.backend()?;
                backend.put_verified(bootstrap_response.root_entry)?;

                // Store all other entries
                for entry in bootstrap_response.all_entries {
                    backend.put_unverified(entry)?;
                }

                info!(peer = %peer_pubkey, tree = %tree_id, "Bootstrap sync completed successfully");
            }
            SyncResponse::Incremental(incremental_response) => {
                info!(peer = %peer_pubkey, tree = %tree_id, missing_count = incremental_response.missing_entries.len(), "Received incremental sync response");

                // Use the enhanced handler that supports bidirectional sync
                self.handle_incremental_response(incremental_response, address)
                    .await?;

                debug!(peer = %peer_pubkey, tree = %tree_id, "Incremental sync completed");
            }
            SyncResponse::BootstrapPending {
                request_id,
                message,
            } => {
                info!(peer = %peer_pubkey, tree = %tree_id, request_id = %request_id, "Bootstrap request pending manual approval");
                return Err(SyncError::BootstrapPending {
                    request_id,
                    message,
                }
                .into());
            }
            SyncResponse::Error(err) => {
                return Err(SyncError::Network(format!("Peer returned error: {err}")).into());
            }
            _ => {
                return Err(SyncError::SyncProtocolError(
                    "Unexpected response type for sync tree request".to_string(),
                )
                .into());
            }
        }

        // Track tree/peer relationship for sync_on_commit to work
        // This allows on_local_write() to find this peer when queueing entries
        self.add_tree_sync(peer_pubkey, tree_id)?;

        Ok(())
    }

    // === Bootstrap Sync Methods ===
    //
    // Eidetica provides two bootstrap sync methods for different key management scenarios:
    //
    // 1. `sync_with_peer_for_bootstrap_with_key()` - **Preferred** for user-managed keys
    //    - Signing key provided directly as parameter
    //    - Keys remain in memory (not stored in backend)
    //    - Required for User API which manages its own key lifecycle
    //    - **Use this method for new code** - it provides better key isolation and security
    //
    // 2. `sync_with_peer_for_bootstrap()` - For legacy backend-managed keys
    //    - Keys are stored in backend storage
    //    - Method looks up the signing key automatically
    //    - Suitable for simple applications and direct sync API usage
    //    - Consider migrating to the `_with_key()` variant for better security
    //
    // Both methods delegate to `sync_with_peer_for_bootstrap_internal()` which contains
    // the common bootstrap logic. Prefer `_with_key()` for new implementations.

    /// Internal helper for bootstrap sync operations.
    ///
    /// This method contains the common logic for bootstrap scenarios where the local
    /// device doesn't have access to the target tree yet and needs to request
    /// permission during the initial sync.
    ///
    /// # Arguments
    /// * `peer_address` - The address of the peer to sync with
    /// * `tree_id` - The ID of the tree to sync
    /// * `requesting_public_key` - The formatted public key string for authentication
    /// * `requesting_key_name` - The name/ID of the requesting key
    /// * `requested_permission` - The permission level being requested
    ///
    /// # Returns
    /// A Result indicating success or failure.
    ///
    /// # Errors
    /// * `SyncError::InvalidPublicKey` if the public key is empty or malformed
    /// * `SyncError::InvalidKeyName` if the key name is empty
    async fn sync_with_peer_for_bootstrap_internal(
        &self,
        peer_address: &str,
        tree_id: &crate::entry::ID,
        requesting_public_key: String,
        requesting_key_name: &str,
        requested_permission: crate::auth::Permission,
    ) -> Result<()> {
        use peer_types::Address;

        // Validate public key is not empty
        if requesting_public_key.is_empty() {
            return Err(SyncError::InvalidPublicKey {
                reason: "Public key cannot be empty".to_string(),
            }
            .into());
        }

        // Validate public key format by attempting to parse it
        crate::auth::crypto::parse_public_key(&requesting_public_key).map_err(|e| {
            SyncError::InvalidPublicKey {
                reason: format!("Invalid public key format: {e}"),
            }
        })?;

        // Validate key name is not empty
        if requesting_key_name.is_empty() {
            return Err(SyncError::InvalidKeyName {
                reason: "Key name cannot be empty".to_string(),
            }
            .into());
        }

        // Auto-detect transport type from address format
        let address = if peer_address.starts_with('{') || peer_address.contains("\"node_id\"") {
            // JSON format indicates Iroh NodeAddr
            Address {
                transport_type: "iroh".to_string(),
                address: peer_address.to_string(),
            }
        } else {
            // Default to HTTP for traditional host:port format
            Address {
                transport_type: "http".to_string(),
                address: peer_address.to_string(),
            }
        };

        // Connect to peer if not already connected
        let peer_pubkey = self.connect_to_peer(&address).await?;

        // Store the address for this peer
        self.add_peer_address(&peer_pubkey, address.clone())?;

        // Sync tree with authentication
        self.sync_tree_with_peer_auth(
            &peer_pubkey,
            tree_id,
            Some(&requesting_public_key),
            Some(requesting_key_name),
            Some(requested_permission),
        )
        .await?;

        Ok(())
    }

    /// Sync with a peer, requesting access with authentication for bootstrap scenarios.
    ///
    /// This method is specifically designed for bootstrap scenarios where the local
    /// device doesn't have access to the target tree yet and needs to request
    /// permission during the initial sync. The signing key is looked up from backend
    /// storage using the provided key name.
    ///
    /// # Arguments
    /// * `peer_address` - The address of the peer to sync with
    /// * `tree_id` - The ID of the tree to sync
    /// * `requesting_key_name` - The name/ID of the local authentication key in backend storage
    /// * `requested_permission` - The permission level being requested
    ///
    /// # Returns
    /// A Result indicating success or failure.
    pub async fn sync_with_peer_for_bootstrap(
        &self,
        peer_address: &str,
        tree_id: &crate::entry::ID,
        requesting_key_name: &str,
        requested_permission: crate::auth::Permission,
    ) -> Result<()> {
        // Get our public key for the requesting key from backend
        let backend = self.backend()?;
        let signing_key = backend
            .get_private_key(requesting_key_name)?
            .ok_or_else(|| {
                SyncError::BackendError(format!(
                    "Private key not found for key name: {requesting_key_name}"
                ))
            })?;

        let verifying_key = signing_key.verifying_key();
        let requesting_public_key = crate::auth::crypto::format_public_key(&verifying_key);

        // Delegate to internal method
        self.sync_with_peer_for_bootstrap_internal(
            peer_address,
            tree_id,
            requesting_public_key,
            requesting_key_name,
            requested_permission,
        )
        .await
    }

    /// Sync with a peer for bootstrap using a user-provided public key.
    ///
    /// This method is specifically designed for bootstrap scenarios where the local
    /// device doesn't have access to the target tree yet and needs to request
    /// permission during the initial sync. Unlike `sync_with_peer_for_bootstrap`,
    /// this variant accepts a public key directly instead of looking it up from
    /// backend storage, making it compatible with User API managed keys.
    ///
    /// # Arguments
    /// * `peer_address` - The address of the peer to sync with
    /// * `tree_id` - The ID of the tree to sync
    /// * `requesting_public_key` - The formatted public key string (e.g., "ed25519:base64...")
    /// * `requesting_key_name` - The name/ID of the requesting key for audit trail
    /// * `requested_permission` - The permission level being requested
    ///
    /// # Returns
    /// A Result indicating success or failure.
    ///
    /// # Example
    /// ```rust,ignore
    /// // With User API managed keys:
    /// let public_key = user.get_public_key(user_key_id)?;
    /// sync.sync_with_peer_for_bootstrap_with_key(
    ///     "127.0.0.1:8080",
    ///     &tree_id,
    ///     &public_key,
    ///     user_key_id,
    ///     Permission::Write(5),
    /// ).await?;
    /// ```
    pub async fn sync_with_peer_for_bootstrap_with_key(
        &self,
        peer_address: &str,
        tree_id: &crate::entry::ID,
        requesting_public_key: &str,
        requesting_key_name: &str,
        requested_permission: crate::auth::Permission,
    ) -> Result<()> {
        // Delegate to internal method
        self.sync_with_peer_for_bootstrap_internal(
            peer_address,
            tree_id,
            requesting_public_key.to_string(),
            requesting_key_name,
            requested_permission,
        )
        .await
    }

    // === Bootstrap Request Management Methods ===

    /// Get all pending bootstrap requests.
    ///
    /// # Returns
    /// A vector of (request_id, bootstrap_request) pairs for pending requests.
    pub fn pending_bootstrap_requests(&self) -> Result<Vec<(String, BootstrapRequest)>> {
        let op = self.sync_tree.new_transaction()?;
        let manager = BootstrapRequestManager::new(&op);
        manager.pending_requests()
    }

    /// Get all approved bootstrap requests.
    ///
    /// # Returns
    /// A vector of (request_id, bootstrap_request) pairs for approved requests.
    pub fn approved_bootstrap_requests(&self) -> Result<Vec<(String, BootstrapRequest)>> {
        let op = self.sync_tree.new_transaction()?;
        let manager = BootstrapRequestManager::new(&op);
        manager.approved_requests()
    }

    /// Get all rejected bootstrap requests.
    ///
    /// # Returns
    /// A vector of (request_id, bootstrap_request) pairs for rejected requests.
    pub fn rejected_bootstrap_requests(&self) -> Result<Vec<(String, BootstrapRequest)>> {
        let op = self.sync_tree.new_transaction()?;
        let manager = BootstrapRequestManager::new(&op);
        manager.rejected_requests()
    }

    /// Get a specific bootstrap request by ID.
    ///
    /// # Arguments
    /// * `request_id` - The unique identifier of the request
    ///
    /// # Returns
    /// A tuple of (request_id, bootstrap_request) if found, None otherwise.
    pub fn get_bootstrap_request(
        &self,
        request_id: &str,
    ) -> Result<Option<(String, BootstrapRequest)>> {
        let op = self.sync_tree.new_transaction()?;
        let manager = BootstrapRequestManager::new(&op);

        match manager.get_request(request_id)? {
            Some(request) => Ok(Some((request_id.to_string(), request))),
            None => Ok(None),
        }
    }

    /// Approve a bootstrap request and add the key to the target database.
    ///
    /// This method loads the bootstrap request, validates it exists and is pending,
    /// then adds the requesting key to the target database using the specified
    /// approving key for authentication.
    ///
    /// # Arguments
    /// * `request_id` - The unique identifier of the request to approve
    /// * `approving_key_name` - The name of the local key to use for the approval
    ///
    /// # Returns
    /// Result indicating success or failure of the approval operation.
    pub fn approve_bootstrap_request(
        &self,
        request_id: &str,
        approving_key_name: &str,
    ) -> Result<()> {
        // Load the request from sync database
        let sync_op = self.sync_tree.new_transaction()?;
        let manager = BootstrapRequestManager::new(&sync_op);

        let request = manager
            .get_request(request_id)?
            .ok_or_else(|| SyncError::RequestNotFound(request_id.to_string()))?;

        // Validate request is still pending
        if !matches!(request.status, RequestStatus::Pending) {
            return Err(SyncError::InvalidRequestState {
                request_id: request_id.to_string(),
                current_status: format!("{:?}", request.status),
                expected_status: "Pending".to_string(),
            }
            .into());
        }

        // Load target database with the approving key
        let backend = self.backend()?;
        let approving_signing_key =
            backend
                .get_private_key(approving_key_name)?
                .ok_or_else(|| {
                    SyncError::BackendError(format!(
                        "Approving key not found: {approving_key_name}"
                    ))
                })?;

        let database = Database::open(
            self.instance()?,
            &request.tree_id,
            approving_signing_key,
            approving_key_name.to_string(),
        )?;
        let tx = database.new_transaction()?;

        // Get settings store and update auth configuration using SettingsStore API
        let settings_store = SettingsStore::new(&tx)?;

        // Create the auth key for the requesting device
        let auth_key = AuthKey::active(
            request.requesting_pubkey.clone(),
            request.requested_permission.clone(),
        )?;

        // Add the new key to auth settings using SettingsStore API
        // This provides proper upsert behavior and validation
        settings_store.set_auth_key(&request.requesting_key_name, auth_key)?;

        tx.commit()?;

        // Update request status to approved
        let approval_time = bootstrap_request_manager::current_timestamp();
        manager.update_status(
            request_id,
            RequestStatus::Approved {
                approved_by: approving_key_name.to_string(),
                approval_time,
            },
        )?;
        sync_op.commit()?;

        info!(
            request_id = %request_id,
            tree_id = %request.tree_id,
            approved_by = %approving_key_name,
            "Bootstrap request approved and key added to database"
        );

        // TODO: Implement notification to requesting peer (future enhancement)

        Ok(())
    }

    /// Approve a bootstrap request using a user-provided signing key.
    ///
    /// This variant allows approval using keys that are not stored in the backend,
    /// such as user keys managed in memory.
    ///
    /// # Arguments
    /// * `request_id` - The unique identifier of the request to approve
    /// * `approving_signing_key` - The signing key to use for the transaction
    /// * `approving_sigkey` - The sigkey identifier for audit trail
    ///
    /// # Returns
    /// Result indicating success or failure of the approval operation.
    ///
    /// # Errors
    /// Returns `SyncError::InsufficientPermission` if the approving key does not have
    /// Admin permission on the target database.
    pub fn approve_bootstrap_request_with_key(
        &self,
        request_id: &str,
        approving_signing_key: &ed25519_dalek::SigningKey,
        approving_sigkey: &str,
    ) -> Result<()> {
        // Load the request from sync database
        let sync_op = self.sync_tree.new_transaction()?;
        let manager = BootstrapRequestManager::new(&sync_op);

        let request = manager
            .get_request(request_id)?
            .ok_or_else(|| SyncError::RequestNotFound(request_id.to_string()))?;

        // Validate request is still pending
        if !matches!(request.status, RequestStatus::Pending) {
            return Err(SyncError::InvalidRequestState {
                request_id: request_id.to_string(),
                current_status: format!("{:?}", request.status),
                expected_status: "Pending".to_string(),
            }
            .into());
        }

        // Load the existing database with the user's signing key
        let database = Database::open(
            self.instance()?,
            &request.tree_id,
            approving_signing_key.clone(),
            approving_sigkey.to_string(),
        )?;

        // Explicitly check that the approving user has Admin permission
        // This provides clear error messages and fails fast before modifying the database
        let permission = database.get_sigkey_permission(approving_sigkey)?;
        if !permission.can_admin() {
            return Err(SyncError::InsufficientPermission {
                request_id: request_id.to_string(),
                required_permission: "Admin".to_string(),
                actual_permission: permission,
            }
            .into());
        }

        // Create transaction - this will use the provided signing key
        let tx = database.new_transaction()?;

        // Get settings store and update auth configuration
        let settings_store = tx.get_settings()?;

        // Create the auth key for the requesting device
        let auth_key = AuthKey::active(
            request.requesting_pubkey.clone(),
            request.requested_permission.clone(),
        )?;

        // Add the new key to auth settings using SettingsStore API
        // This provides proper upsert behavior and validation
        settings_store.set_auth_key(&request.requesting_key_name, auth_key)?;

        // Commit will validate that the user's key has Admin permission
        // If this fails, it means the user lacks the necessary permission
        tx.commit()?;

        // Update request status to approved
        let approval_time = bootstrap_request_manager::current_timestamp();
        manager.update_status(
            request_id,
            RequestStatus::Approved {
                approved_by: approving_sigkey.to_string(),
                approval_time,
            },
        )?;
        sync_op.commit()?;

        info!(
            request_id = %request_id,
            tree_id = %request.tree_id,
            approved_by = %approving_sigkey,
            "Bootstrap request approved and key added to database using user-provided key"
        );

        Ok(())
    }

    /// Reject a bootstrap request.
    ///
    /// This method marks the request as rejected without adding any keys
    /// to the target database.
    ///
    /// # Arguments
    /// * `request_id` - The unique identifier of the request to reject
    /// * `rejecting_key_name` - The name of the local key making the rejection
    ///
    /// # Returns
    /// Result indicating success or failure of the rejection operation.
    pub fn reject_bootstrap_request(
        &self,
        request_id: &str,
        rejecting_key_name: &str,
    ) -> Result<()> {
        let op = self.sync_tree.new_transaction()?;
        let manager = BootstrapRequestManager::new(&op);

        // Validate request exists and is pending
        let request = manager
            .get_request(request_id)?
            .ok_or_else(|| SyncError::RequestNotFound(request_id.to_string()))?;

        if !matches!(request.status, RequestStatus::Pending) {
            return Err(SyncError::InvalidRequestState {
                request_id: request_id.to_string(),
                current_status: format!("{:?}", request.status),
                expected_status: "Pending".to_string(),
            }
            .into());
        }

        // Update status to rejected
        let rejection_time = bootstrap_request_manager::current_timestamp();
        manager.update_status(
            request_id,
            RequestStatus::Rejected {
                rejected_by: rejecting_key_name.to_string(),
                rejection_time,
            },
        )?;
        op.commit()?;

        info!(
            request_id = %request_id,
            tree_id = %request.tree_id,
            rejected_by = %rejecting_key_name,
            "Bootstrap request rejected"
        );

        // TODO: Implement notification to requesting peer (future enhancement)

        Ok(())
    }

    /// Reject a bootstrap request using a user-provided signing key with Admin permission validation.
    ///
    /// This variant allows rejection using keys that are not stored in the backend,
    /// such as user keys managed in memory. It validates that the rejecting user has
    /// Admin permission on the target database before allowing the rejection.
    ///
    /// # Arguments
    /// * `request_id` - The unique identifier of the request to reject
    /// * `rejecting_signing_key` - The signing key to use for permission validation
    /// * `rejecting_sigkey` - The sigkey identifier for audit trail
    ///
    /// # Returns
    /// Result indicating success or failure of the rejection operation.
    ///
    /// # Errors
    /// Returns `SyncError::InsufficientPermission` if the rejecting key does not have
    /// Admin permission on the target database.
    pub fn reject_bootstrap_request_with_key(
        &self,
        request_id: &str,
        rejecting_signing_key: &ed25519_dalek::SigningKey,
        rejecting_sigkey: &str,
    ) -> Result<()> {
        // Load the request from sync database
        let sync_op = self.sync_tree.new_transaction()?;
        let manager = BootstrapRequestManager::new(&sync_op);

        let request = manager
            .get_request(request_id)?
            .ok_or_else(|| SyncError::RequestNotFound(request_id.to_string()))?;

        // Validate request is still pending
        if !matches!(request.status, RequestStatus::Pending) {
            return Err(SyncError::InvalidRequestState {
                request_id: request_id.to_string(),
                current_status: format!("{:?}", request.status),
                expected_status: "Pending".to_string(),
            }
            .into());
        }

        // Load the existing database with the user's signing key to validate permissions
        let database = Database::open(
            self.instance()?,
            &request.tree_id,
            rejecting_signing_key.clone(),
            rejecting_sigkey.to_string(),
        )?;

        // Check that the rejecting user has Admin permission
        let permission = database.get_sigkey_permission(rejecting_sigkey)?;
        if !permission.can_admin() {
            return Err(SyncError::InsufficientPermission {
                request_id: request_id.to_string(),
                required_permission: "Admin".to_string(),
                actual_permission: permission,
            }
            .into());
        }

        // User has Admin permission, proceed with rejection
        let rejection_time = bootstrap_request_manager::current_timestamp();
        manager.update_status(
            request_id,
            RequestStatus::Rejected {
                rejected_by: rejecting_sigkey.to_string(),
                rejection_time,
            },
        )?;
        sync_op.commit()?;

        info!(
            request_id = %request_id,
            tree_id = %request.tree_id,
            rejected_by = %rejecting_sigkey,
            "Bootstrap request rejected by user with Admin permission"
        );

        Ok(())
    }
}

impl Sync {
    // === Test Helpers ===
}