second-brain-api 0.13.4

HTTP API server for second-brain: REST endpoints for recall, remember, and ingest
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
use std::collections::HashMap;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::sync::mpsc::{self, Receiver, SendError, Sender};
use std::sync::{Arc, Mutex, PoisonError};
use std::thread::JoinHandle;
use std::time::{Duration, Instant};

use anyhow::{Context, Result};
use chrono::Utc;
use second_brain_core::keys::{DeviceKeys, load_device_keys};
use second_brain_core::schema::SyncState;
use second_brain_core::sqlite_store::SqliteStore;
use second_brain_core::store::StoreAdmin;
use second_brain_sync::crypto::seal_line;
use second_brain_sync::dial::{self, Dial, Route};
use second_brain_sync::export::export_page;
use second_brain_sync::keyring::Keyring;
use second_brain_sync::mdns::{self, Net};
use second_brain_sync::protocol::{Hello, Merging, SyncHeader, check_store_header, store_header};
use second_brain_sync::session::{self, Exported, Imported, Local, Merged, Transport};
use second_brain_sync::ssh::{SshTransport, device_alias, known_hosts_path_in};
use second_brain_sync::ssh_identity::{EphemeralIdentity, sweep_ephemeral_identities};

use crate::bootstrap::Bootstrap;
use crate::clock_gate::{ClockGate, is_untrusted};
use crate::device_access::DeviceAccess;
use crate::health::Health;
use crate::snapshot_merge;
use crate::sync_hello;
use crate::value_metrics::PeerOutcome;
use crate::write_gate::{WriteGate, WriteSlot};

const FULL_INTERVAL: Duration = Duration::from_secs(300);
const TICK: Duration = Duration::from_secs(1);
const PUSH_DELAY: Duration = Duration::from_secs(5);
const FIRST_BACKOFF: Duration = Duration::from_secs(30);
const MAX_BACKOFF: Duration = Duration::from_secs(30 * 60);
const ORIGIN_SCAN_PAGE: usize = 500;

pub type Connect = Arc<dyn Fn(&Route) -> Result<Box<dyn Transport + Send>> + Send + Sync>;

/// This device's ssh key, as the file ssh reads for device routes.
pub const SSH_KEY_FILE: &str = "sync-ssh-key";

/// Syncs with every active device in the signed device list that can be
/// reached, and with `sync-peers` lines not yet matched to one: a full pull
/// and push on start, every five minutes and right after a pairing, and a
/// push shortly after this machine writes.
pub struct SyncLoop {
    pub data_dir: PathBuf,
    pub sqlite: Arc<SqliteStore>,
    pub gate: Arc<WriteGate>,
    pub clock: Arc<ClockGate>,
    pub health: Arc<Health>,
    pub access: Arc<DeviceAccess>,
    pub bootstrap: Arc<Bootstrap>,
    pub connect: Connect,
    /// Where a device with no address, or none that answers, is looked up
    /// by mDNS; None looks nothing up.
    pub discovery: Option<Net>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum Job {
    Push,
    Full,
}

impl SyncLoop {
    pub fn over_ssh(
        data_dir: PathBuf,
        sqlite: Arc<SqliteStore>,
        gate: Arc<WriteGate>,
        clock: Arc<ClockGate>,
        health: Arc<Health>,
        access: Arc<DeviceAccess>,
        bootstrap: Arc<Bootstrap>,
    ) -> Self {
        if let Err(e) = sweep_ephemeral_identities(&data_dir) {
            tracing::warn!("removing ssh key files a killed daemon left: {e:#}");
        }
        match retire_plaintext_ssh_key(&data_dir) {
            Ok(true) => tracing::info!("removed the plaintext {SSH_KEY_FILE}"),
            Ok(false) => {}
            Err(e) => tracing::warn!("kept the plaintext {SSH_KEY_FILE}: {e:#}"),
        }
        let connect = ssh_connect(data_dir.clone(), sqlite.machine_id().to_string());
        Self {
            data_dir,
            sqlite,
            gate,
            clock,
            health,
            access,
            bootstrap,
            connect,
            discovery: None,
        }
    }

    pub fn with_health(mut self, health: Arc<Health>) -> Self {
        self.health = health;
        self
    }

    pub fn with_discovery(mut self, discovery: Net) -> Self {
        self.discovery = Some(discovery);
        self
    }

    pub fn spawn(self) -> JoinHandle<()> {
        std::thread::Builder::new()
            .name("sync-loop".to_string())
            .spawn(move || Arc::new(self).run())
            .expect("spawning the sync loop")
    }

    fn run(self: Arc<Self>) {
        let mut workers: HashMap<String, Sender<(Job, Dial)>> = HashMap::new();
        let mut next_full = Instant::now();
        let mut seen = self.sqlite.max_sync_seq().unwrap_or(0);
        let mut push_at: Option<Instant> = None;
        loop {
            let dials = self.listed_dials();
            if dials.is_empty() {
                seen = self.sqlite.max_sync_seq().unwrap_or(seen);
                push_at = None;
            } else if self.wrote_locally(&mut seen) {
                push_at.get_or_insert(Instant::now() + PUSH_DELAY);
            }

            let now = Instant::now();
            if self.access.take_kick() {
                next_full = now;
            }
            let job = if now >= next_full {
                next_full = now + FULL_INTERVAL;
                Some(Job::Full)
            } else if push_at.is_some_and(|at| now >= at) {
                Some(Job::Push)
            } else {
                None
            };
            if let Some(job) = job {
                push_at = None;
                let mut dials = dials;
                if job == Job::Full {
                    self.add_found(&mut dials);
                }
                for dial in dials {
                    self.dispatch(&mut workers, job, dial);
                }
            }
            std::thread::sleep(TICK);
        }
    }

    /// Workers are keyed by peer and outlive its removal from the list, so
    /// a changed route or a peer re-added mid-sync still gets one sync at a
    /// time.
    fn dispatch(
        self: &Arc<Self>,
        workers: &mut HashMap<String, Sender<(Job, Dial)>>,
        job: Job,
        dial: Dial,
    ) {
        let key = dial.key.clone();
        let worker = workers
            .entry(key.clone())
            .or_insert_with(|| self.clone().start_worker(&key));
        if let Err(SendError(message)) = worker.send((job, dial)) {
            tracing::warn!("the sync worker for {key} exited; starting another");
            let worker = self.clone().start_worker(&key);
            if worker.send(message).is_err() {
                tracing::warn!("the new sync worker for {key} exited at once");
            }
            workers.insert(key, worker);
        }
    }

    /// A device list or `sync-peers` that can't be read keeps the peers in
    /// health, so their lag keeps growing instead of vanishing from the
    /// report; an unreadable `sync-peers` still leaves the devices dialled.
    fn listed_dials(&self) -> Vec<Dial> {
        let mut dials = match dial::device_dials(&self.sqlite) {
            Ok(dials) => dials,
            Err(e) => {
                tracing::warn!("cannot read the devices to sync with: {e:#}");
                return Vec::new();
            }
        };
        match dial::line_dials(&self.sqlite, &self.data_dir) {
            Ok(lines) => {
                dials.extend(lines);
                let labels: Vec<String> = dials.iter().map(|dial| dial.label.clone()).collect();
                self.health.sync_peers_listed(&labels, Utc::now());
            }
            Err(e) => tracing::warn!(
                "cannot read {}: {e:#}",
                second_brain_sync::peers::PEERS_FILE
            ),
        }
        dials
    }

    fn report(&self, label: &str, outcome: PeerOutcome) {
        self.health.sync_attempted(label, outcome, Utc::now());
    }

    /// Imports also append to sync_log; only a row this machine originated is
    /// news to its peers.
    fn wrote_locally(&self, seen: &mut u64) -> bool {
        let max = match self.sqlite.max_sync_seq() {
            Ok(max) => max,
            Err(e) => {
                tracing::warn!("cannot read the sync log position: {e:#}");
                return false;
            }
        };
        let own = self.sqlite.machine_id();
        while *seen < max {
            let page = match self.sqlite.sync_log_page(*seen, Some(ORIGIN_SCAN_PAGE)) {
                Ok(page) => page,
                Err(e) => {
                    tracing::warn!("cannot read the sync log: {e:#}");
                    return false;
                }
            };
            let Some(last) = page.last() else {
                break;
            };
            if page.iter().any(|entry| entry.origin_machine_id == own) {
                *seen = max;
                return true;
            }
            *seen = last.local_seq.max(0) as u64;
        }
        *seen = max;
        false
    }

    fn start_worker(self: Arc<Self>, key: &str) -> Sender<(Job, Dial)> {
        let (jobs, inbox) = mpsc::channel();
        std::thread::Builder::new()
            .name(format!("sync-{key}"))
            .spawn(move || self.work(inbox))
            .expect("spawning a sync worker");
        jobs
    }

    /// One sync per peer at a time; a peer that fails waits out its backoff
    /// on its own thread, so it never holds up the others.
    fn work(&self, inbox: Receiver<(Job, Dial)>) {
        let mut backoff = PeerBackoff::default();
        while let Ok((mut job, mut dial)) = inbox.recv() {
            while let Ok((queued, latest)) = inbox.try_recv() {
                job = job.max(queued);
                dial = latest;
            }
            if !backoff.due(&dial, Instant::now()) {
                continue;
            }
            if job == Job::Push && !self.holds_identity() {
                tracing::info!(
                    "not pushing to {}: this device holds no sync identity yet; pair it with \
                     `sb pair`",
                    dial.label
                );
                continue;
            }
            match self.sync(&dial, job) {
                Ok(()) => {
                    backoff.succeeded();
                    let outcome = match job {
                        Job::Full => PeerOutcome::Synced,
                        Job::Push => PeerOutcome::Pushed,
                    };
                    self.report(&dial.label, outcome);
                }
                Err(e) if !counts_against_peer(&e) => {
                    tracing::info!("sync with {} waits for the next job: {e:#}", dial.label);
                }
                Err(e) => {
                    let wait = backoff.failed(&dial, Instant::now());
                    self.report(&dial.label, PeerOutcome::Failed(format!("{e:#}")));
                    tracing::warn!(
                        "sync with {} failed; its jobs are skipped for the next {}s: {e:#}",
                        dial.label,
                        wait.as_secs()
                    );
                }
            }
        }
    }

    /// Every way a store gets an identity (founding, migrating a sync.key,
    /// pairing) writes this device's own row, so its absence is the cheap
    /// test that needs no device key.
    fn holds_identity(&self) -> bool {
        match self.sqlite.device_record(self.sqlite.machine_id()) {
            Ok(row) => row.is_some(),
            Err(e) => {
                tracing::warn!("cannot read this device's sync identity row: {e:#}");
                true
            }
        }
    }

    /// Tries the peer's routes in order until one answers as the device it
    /// was dialled for; a route that answers is the one synced through. A
    /// device none of whose routes answers is looked up by mDNS, and the
    /// routes found are tried next. A failure there is reported only when
    /// the device had no route of its own, so an advert cannot replace the
    /// held route's error in health.
    fn sync(&self, dial: &Dial, job: Job) -> Result<()> {
        let failed = match self.sync_via(dial, &dial.routes, job)? {
            Reached::Synced => return Ok(()),
            Reached::Not(failed) => failed,
        };
        let found: Vec<Route> = match &dial.machine_id {
            Some(machine_id) => self
                .lookup()
                .into_iter()
                .filter(|found| found.key == *machine_id)
                .flat_map(|found| found.routes)
                .filter(|route| !dial.routes.contains(route))
                .collect(),
            None => Vec::new(),
        };
        let found_failed = if found.is_empty() {
            None
        } else {
            match self.sync_via(dial, &found, job)? {
                Reached::Synced => return Ok(()),
                Reached::Not(failed) => failed,
            }
        };
        Err(failed
            .or(found_failed)
            .unwrap_or_else(|| anyhow::anyhow!("{} has no route to dial", dial.label)))
    }

    /// Adds dials for the devices of this identity that `dials` lacks and a
    /// lookup finds, as a device with no recorded address.
    fn add_found(&self, dials: &mut Vec<Dial>) {
        if self.discovery.is_none() {
            return;
        }
        match dial::undialled(&self.sqlite, dials) {
            Ok(true) => {}
            Ok(false) => return,
            Err(e) => {
                tracing::warn!("cannot read the devices to sync with: {e:#}");
                return;
            }
        }
        for dial in self.lookup() {
            if !dials.iter().any(|listed| listed.key == dial.key) {
                dials.push(dial);
            }
        }
    }

    /// Dials for the devices of this identity an mDNS lookup finds; none
    /// without `discovery` or when the lookup fails.
    fn lookup(&self) -> Vec<Dial> {
        let Some(net) = &self.discovery else {
            return Vec::new();
        };
        let found = match mdns::browse(net, mdns::SERVICE, mdns::LOOKUP_WINDOW) {
            Ok(found) => found,
            Err(e) => {
                tracing::info!("cannot look devices up on the network: {e:#}");
                return Vec::new();
            }
        };
        dial::found_dials(&self.sqlite, &found).unwrap_or_else(|e| {
            tracing::warn!("cannot read the devices to match a lookup against: {e:#}");
            Vec::new()
        })
    }

    fn sync_via(&self, dial: &Dial, routes: &[Route], job: Job) -> Result<Reached> {
        let mut failed: Option<anyhow::Error> = None;
        for route in routes {
            let transport = match (self.connect)(route) {
                Ok(transport) => transport,
                Err(e) if !counts_against_peer(&e) => return Err(e),
                Err(e) => {
                    failed = Some(e.context(format!("reaching {}", route.describe())));
                    continue;
                }
            };
            let answered = match transport.whoami() {
                Ok(answered) => answered,
                Err(e) => {
                    failed = Some(e.context(format!(
                        "resolving the machine id at {} (is its daemon running?)",
                        route.describe()
                    )));
                    continue;
                }
            };
            if let Route::Line(peer) = route
                && let Some(_slot) = self.gate.try_enter()
            {
                dial::line_answered(&self.sqlite, peer, &answered)?;
            }
            if let Err(e) = dial::refuse_answer(&self.sqlite, dial, &answered) {
                if dial.machine_id.is_some() && !self.is_revoked(&answered) {
                    failed = Some(e);
                    continue;
                }
                return Err(e);
            }
            self.record_answered(route);
            return self
                .sync_through(transport.as_ref(), &answered, job)
                .map(|()| Reached::Synced);
        }
        Ok(Reached::Not(failed))
    }

    /// A route that answered as its device and is not yet held, as one an
    /// mDNS lookup found, becomes the first the device is dialled at.
    fn record_answered(&self, route: &Route) {
        let Some(_slot) = self.gate.try_enter() else {
            return;
        };
        match dial::record_answered(&self.sqlite, route) {
            Ok(true) => tracing::info!("recorded {} as a route to its device", route.describe()),
            Ok(false) => {}
            Err(e) => tracing::warn!("cannot record the route {}: {e:#}", route.describe()),
        }
    }

    fn is_revoked(&self, machine_id: &str) -> bool {
        self.sqlite
            .device_record(machine_id)
            .ok()
            .flatten()
            .is_some_and(|row| row.revoked)
    }

    fn sync_through(&self, transport: &dyn Transport, peer: &str, job: Job) -> Result<()> {
        let local = StoreLocal {
            sqlite: &self.sqlite,
            gate: &self.gate,
            clock: &self.clock,
            health: &self.health,
            access: &self.access,
            bootstrap: &self.bootstrap,
            data_dir: &self.data_dir,
        };
        let host = transport.host().to_string();
        let report = |line: &str| tracing::info!("sync with {host}: {}", line.trim());
        match job {
            Job::Full => session::sync_with(&local, transport, peer, &self.data_dir, &report),
            Job::Push => session::push(&local, transport, peer, &report).map(|_| ()),
        }
    }
}

/// Device routes go in with this device's own ssh key, derived from its
/// device key, loaded once per daemon and kept in memory, and trust only the host
/// keys pinned under the device's machine id; `sync-peers` lines keep the
/// user's ssh setup.
fn ssh_connect(data_dir: PathBuf, own: String) -> Connect {
    let device_keys: Arc<Mutex<Option<DeviceKeys>>> = Arc::default();
    Arc::new(move |route: &Route| -> Result<Box<dyn Transport + Send>> {
        let transport = match route {
            Route::Device {
                machine_id,
                login,
                address,
                port,
            } => {
                let identity = device_identity(&data_dir, &own, &device_keys)?;
                SshTransport::new(&format!("{login}@{address}"), "sb")?
                    .known_hosts(known_hosts_path_in(&data_dir))
                    .port(*port)
                    .host_key_alias(&device_alias(machine_id))
                    .ephemeral_identity(identity)
            }
            Route::Line(peer) => SshTransport::new(&peer.host, &peer.sb)?,
        };
        Ok(Box::new(transport.unattended()) as Box<dyn Transport + Send>)
    })
}

fn device_identity(
    data_dir: &Path,
    own: &str,
    cached: &Mutex<Option<DeviceKeys>>,
) -> Result<EphemeralIdentity> {
    let mut cached = cached.lock().unwrap_or_else(PoisonError::into_inner);
    if cached.is_none() {
        let keys = load_device_keys(data_dir)?
            .context("this device has no device key to sign in to its peers with")?;
        *cached = Some(keys);
    }
    let keys = cached.as_ref().expect("the keys were loaded above");
    EphemeralIdentity::create(
        data_dir,
        keys.ssh_signing_key(),
        &format!("second-brain:{own}"),
    )
}

/// `SSH_KEY_FILE` is a plaintext copy of the ssh key that older daemons kept.
/// It is deleted only once the device key it derives from loads, so a device
/// key that fails to open never leaves the device without its ssh key.
fn retire_plaintext_ssh_key(data_dir: &Path) -> Result<bool> {
    let path = data_dir.join(SSH_KEY_FILE);
    if std::fs::symlink_metadata(&path).is_err() {
        return Ok(false);
    }
    if load_device_keys(data_dir)?.is_none() {
        return Ok(false);
    }
    std::fs::remove_file(&path).with_context(|| format!("removing {}", path.display()))?;
    Ok(true)
}

#[derive(Debug)]
struct MaintenanceRunning;

impl std::fmt::Display for MaintenanceRunning {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("store maintenance is running")
    }
}

impl std::error::Error for MaintenanceRunning {}

/// Routine store maintenance and an untrusted local clock say nothing about
/// the peer, so they start no backoff; the clock may open at any moment and a
/// peer's handshake is what opens it. Other local faults do back off, which
/// also bounds how often a persistent one is logged; a daemon restart clears
/// the backoff.
fn counts_against_peer(error: &anyhow::Error) -> bool {
    error.downcast_ref::<MaintenanceRunning>().is_none() && !is_untrusted(error)
}

enum Reached {
    Synced,
    /// No route answered as the device; the last failure, if any route was
    /// tried.
    Not(Option<anyhow::Error>),
}

#[derive(Default)]
struct PeerBackoff {
    dial: Option<Dial>,
    failures: u32,
    retry_at: Option<Instant>,
}

impl PeerBackoff {
    /// A changed route is a new way to reach the peer, so it is tried at
    /// once rather than after the old routes' backoff.
    fn due(&self, dial: &Dial, now: Instant) -> bool {
        self.dial.as_ref() != Some(dial) || self.retry_at.is_none_or(|at| now >= at)
    }

    fn succeeded(&mut self) {
        *self = PeerBackoff::default();
    }

    fn failed(&mut self, dial: &Dial, now: Instant) -> Duration {
        if self.dial.as_ref() != Some(dial) {
            *self = PeerBackoff {
                dial: Some(dial.clone()),
                ..PeerBackoff::default()
            };
        }
        self.failures += 1;
        let wait = backoff(self.failures);
        self.retry_at = Some(now + wait);
        wait
    }
}

fn backoff(failures: u32) -> Duration {
    FIRST_BACKOFF
        .saturating_mul(2u32.saturating_pow(failures.saturating_sub(1)))
        .min(MAX_BACKOFF)
}

struct StoreLocal<'a> {
    sqlite: &'a Arc<SqliteStore>,
    gate: &'a WriteGate,
    clock: &'a ClockGate,
    health: &'a Health,
    access: &'a DeviceAccess,
    bootstrap: &'a Bootstrap,
    data_dir: &'a std::path::Path,
}

impl StoreLocal<'_> {
    fn write_slot(&self) -> Result<WriteSlot<'_>> {
        self.gate
            .try_enter()
            .ok_or_else(|| anyhow::Error::new(MaintenanceRunning))
    }
}

impl Local for StoreLocal<'_> {
    fn cursors(&self) -> Result<Vec<(String, u64)>> {
        Ok(self
            .sqlite
            .get_all_sync_states()?
            .into_iter()
            .map(|state| (state.peer_id, state.last_seq))
            .collect())
    }

    fn set_cursor(&self, peer_id: &str, last_seq: u64) -> Result<()> {
        let _slot = self.write_slot()?;
        self.sqlite.set_sync_state(&SyncState {
            peer_id: peer_id.to_string(),
            last_seq,
            last_sync_at: chrono::Utc::now(),
        })?;
        Ok(())
    }

    fn import(&self, header: &SyncHeader, lines: &[String]) -> Result<Imported> {
        let _slot = self.write_slot()?;
        check_store_header(self.sqlite, Some(header), "the sender")?;
        let records = Keyring::load(self.sqlite, self.data_dir)?
            .open_lines(header.hello.as_ref().map(|h| h.machine_id.as_str()), lines)?
            .iter()
            .map(|opened| Ok(serde_json::from_slice(opened)?))
            .collect::<Result<Vec<serde_json::Value>>>()?;
        let source = header.hello.as_ref().map(|h| h.machine_id.as_str());
        let applied = crate::sync_import::import_from(self.sqlite, source, &records)?;
        let stats = applied.stats;
        Ok(Imported {
            created: stats.created,
            updated: stats.updated,
            deleted: stats.deleted,
            skipped: stats.skipped,
            dangling: Imported::dangling_in(&stats.skipped_by_reason),
            errors: stats.errors,
            max_seq: applied.max_seq,
            reached: applied.reached,
        })
    }

    fn export(&self, peer_id: &str, after_seq: u64, limit: usize) -> Result<Exported> {
        store_header(self.sqlite)?;
        let (records, max_seq) = export_page(self.sqlite.as_ref(), after_seq, limit)?;
        let sealer = Keyring::load(self.sqlite, self.data_dir)?.sealer_for(peer_id, None)?;
        let lines = records
            .iter()
            .map(|record| seal_line(&sealer, &serde_json::to_vec(record)?))
            .collect::<Result<Vec<String>>>()?;
        Ok(Exported { lines, max_seq })
    }

    fn hello_for(&self, peer_id: &str) -> Result<Hello> {
        sync_hello::hello_for(self.sqlite, self.clock, self.data_dir, peer_id, None)
    }

    fn accept_hello(&self, hello: &Hello) -> Result<()> {
        sync_hello::check_identity(self.sqlite, self.data_dir, hello)?;
        let _slot = self.write_slot()?;
        sync_hello::accept_handshake(
            self.sqlite,
            self.clock,
            self.health,
            self.access,
            self.data_dir,
            hello,
        )
    }

    fn record_ack(&self, peer_id: &str, acked_seq: u64) -> Result<()> {
        let _slot = self.write_slot()?;
        self.sqlite
            .record_peer_ack(peer_id, acked_seq, self.clock.wall_micros())
    }

    fn record_peer_in(&self, peer_id: &str, seq: u64) -> Result<()> {
        let _slot = self.write_slot()?;
        self.sqlite.record_peer_in(peer_id, seq)
    }

    fn push_report(&self, peer_id: &str) -> Result<Option<u64>> {
        self.sqlite.push_report(peer_id)
    }

    fn record_push_report(&self, peer_id: &str, reported: Option<u64>) -> Result<()> {
        let _slot = self.write_slot()?;
        self.sqlite.record_push_report(peer_id, reported)
    }

    fn merging(&self) -> Result<Option<Merging>> {
        snapshot_merge::merging(self.data_dir)
    }

    fn merge_snapshot(&self, exporter: &str, stream: Box<dyn Read + Send>) -> Result<Merged> {
        let merging = snapshot_merge::receive(self.sqlite, self.data_dir, stream, Some(exporter))?;
        match snapshot_merge::merge_spooled(self.sqlite, self.data_dir, self.gate)? {
            Some(_) => Ok(Merged::Done { seq: merging.seq }),
            None => Ok(Merged::Running(merging)),
        }
    }

    fn bootstrap_pending(&self) -> Result<bool> {
        Ok(self.bootstrap.is_pending())
    }

    fn finish_bootstrap(&self) -> Result<()> {
        let _slot = self.write_slot()?;
        if self.bootstrap.finish(self.sqlite)? {
            tracing::info!("bootstrap finished; ingesting this device's own sessions");
        }
        Ok(())
    }

    fn export_snapshot(&self, peer: &Hello) -> Result<Box<dyn Read + Send>> {
        snapshot_merge::pin_for_snapshot(self.sqlite, self.gate, peer)?;
        let (reader, writer) = std::io::pipe()?;
        let (sqlite, data_dir, peer) = (
            self.sqlite.clone(),
            self.data_dir.to_path_buf(),
            peer.clone(),
        );
        std::thread::Builder::new()
            .name("snapshot-export".to_string())
            .spawn(move || {
                let out = std::io::BufWriter::with_capacity(1024 * 1024, writer);
                if let Err(e) = snapshot_merge::stream_snapshot(&sqlite, &data_dir, &peer, out) {
                    tracing::warn!("exporting a snapshot for {} failed: {e:#}", peer.machine_id);
                }
            })?;
        Ok(Box::new(reader))
    }
}

#[cfg(test)]
mod tests {
    use std::io::{Read, Write};
    use std::path::Path;
    use std::sync::Mutex;

    use anyhow::Context;
    use second_brain_core::keys::{
        DeviceKeys, DeviceRecord, DeviceRoute, Epoch, IdentityKey, IdentityTag, KeyGuard,
        admit_device,
    };
    use second_brain_core::sqlite_store::SCHEMA_VERSION;
    use second_brain_sync::crypto::XChaChaEncryptor;
    use second_brain_sync::keyring::{LEGACY_KEY_FILE, migrate_sync_key};
    use second_brain_sync::mdns::Responder;
    use second_brain_sync::peers::{self, Peer};
    use second_brain_sync::protocol::HandshakeKeys;
    use second_brain_sync::protocol::PushApplied;
    use second_brain_sync::session::{Exit, Remote};
    use second_brain_sync::ssh_identity::write_identity_file;

    use super::*;
    use crate::value_metrics::PeerSync;

    fn line_dial(line: &str) -> Dial {
        let peer = Peer::parse(line);
        Dial {
            key: peer.host.clone(),
            label: peer.host.clone(),
            machine_id: None,
            routes: vec![Route::Line(peer)],
        }
    }

    fn fresh_health() -> Arc<Health> {
        Arc::new(Health::new(chrono::Utc::now(), None))
    }

    #[test]
    fn the_daemon_refuses_to_export_from_a_database_newer_than_its_binary() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("future.db");
        drop(SqliteStore::open(&path, "m".to_string()).unwrap());
        rusqlite::Connection::open(&path)
            .unwrap()
            .pragma_update(None, "user_version", SCHEMA_VERSION + 1)
            .unwrap();
        let sqlite = Arc::new(SqliteStore::open(&path, "m".to_string()).unwrap());
        let gate = WriteGate::default();
        let clock = ClockGate::open_for_tests();
        let health = fresh_health();
        let local = StoreLocal {
            sqlite: &sqlite,
            gate: &gate,
            clock: &clock,
            health: &health,
            access: &DeviceAccess::default(),
            bootstrap: &Bootstrap::default(),
            data_dir: dir.path(),
        };
        let error = local.export("peer", 0, 10).err().expect("export refused");
        assert!(
            format!("{error:#}").contains("upgrade this daemon"),
            "{error:#}"
        );
    }

    #[test]
    fn a_host_keeps_one_worker_when_its_sb_path_changes() {
        let dir = tempfile::tempdir().unwrap();
        let sync_loop = Arc::new(SyncLoop {
            data_dir: dir.path().to_path_buf(),
            sqlite: Arc::new(SqliteStore::in_memory("m".to_string()).unwrap()),
            gate: Arc::new(WriteGate::default()),
            clock: ClockGate::open_for_tests(),
            health: fresh_health(),
            access: Arc::default(),
            bootstrap: Arc::default(),
            connect: Arc::new(|_: &Route| -> Result<Box<dyn Transport + Send>> {
                anyhow::bail!("offline")
            }),
            discovery: None,
        });
        let mut workers = HashMap::new();
        sync_loop.dispatch(&mut workers, Job::Push, line_dial("user@pi"));
        sync_loop.dispatch(&mut workers, Job::Push, line_dial("user@pi /opt/sb"));
        assert_eq!(workers.len(), 1);
    }

    const SYNC_KEY: [u8; 32] = [4; 32];

    /// The identity a store upgraded from `SYNC_KEY` holds, as a peer of it
    /// declares it.
    fn shared_identity() -> HandshakeKeys {
        let key = IdentityKey::from_bytes(KeyGuard::new(SYNC_KEY));
        HandshakeKeys {
            identity_tag: Some(IdentityTag::migrated(&key.key_id())),
            epochs: vec![Epoch {
                number: 0,
                key_id: key.key_id(),
            }],
            ..HandshakeKeys::default()
        }
    }

    fn upgraded_store(dir: &Path) -> SqliteStore {
        let sqlite = SqliteStore::in_memory("m".to_string()).unwrap();
        second_brain_core::keys::ensure_device_keys(&sqlite, dir).unwrap();
        std::fs::write(
            dir.join(LEGACY_KEY_FILE),
            XChaChaEncryptor::new(SYNC_KEY).key_base64(),
        )
        .unwrap();
        migrate_sync_key(&sqlite, dir, "m", Utc::now().timestamp_micros()).unwrap();
        sqlite
    }

    fn scripted_loop(dir: &Path, connect: Connect) -> SyncLoop {
        SyncLoop {
            data_dir: dir.to_path_buf(),
            sqlite: Arc::new(upgraded_store(dir)),
            gate: Arc::new(WriteGate::default()),
            clock: ClockGate::open_for_tests(),
            health: fresh_health(),
            access: Arc::default(),
            bootstrap: Arc::default(),
            connect,
            discovery: None,
        }
    }

    #[test]
    fn the_worker_takes_the_latest_line_and_backs_off_for_all_but_maintenance() {
        let dir = tempfile::tempdir().unwrap();
        let calls: Arc<Mutex<Vec<Route>>> = Arc::default();
        let connect: Connect = {
            let calls = calls.clone();
            Arc::new(move |route: &Route| -> Result<Box<dyn Transport + Send>> {
                let mut calls = calls.lock().unwrap();
                calls.push(route.clone());
                if calls.len() == 1 {
                    Err(anyhow::Error::new(MaintenanceRunning))
                } else {
                    anyhow::bail!("connection refused")
                }
            })
        };
        let sync_loop = Arc::new(scripted_loop(dir.path(), connect));
        let made = |n: usize| {
            let deadline = Instant::now() + Duration::from_secs(5);
            while Instant::now() < deadline {
                if calls.lock().unwrap().len() >= n {
                    return true;
                }
                std::thread::sleep(Duration::from_millis(10));
            }
            false
        };
        let bare = line_dial("user@pi");
        let fixed = line_dial("user@pi /opt/sb");
        let (jobs, inbox) = mpsc::channel();
        jobs.send((Job::Push, line_dial("user@pi /old/sb")))
            .unwrap();
        jobs.send((Job::Full, bare.clone())).unwrap();
        let worker = {
            let sync_loop = sync_loop.clone();
            std::thread::spawn(move || sync_loop.work(inbox))
        };
        assert!(made(1), "the queued jobs never ran");
        jobs.send((Job::Full, bare.clone())).unwrap();
        assert!(made(2), "local maintenance started a backoff");
        jobs.send((Job::Full, bare.clone())).unwrap();
        std::thread::sleep(Duration::from_millis(300));
        assert_eq!(
            calls.lock().unwrap().len(),
            2,
            "a job inside the backoff ran"
        );
        jobs.send((Job::Full, fixed.clone())).unwrap();
        assert!(made(3), "a changed line waited out the old backoff");
        drop(jobs);
        worker.join().unwrap();
        let route = |dial: &Dial| dial.routes[0].clone();
        assert_eq!(
            *calls.lock().unwrap(),
            vec![route(&bare), route(&bare), route(&fixed)]
        );
    }

    #[test]
    fn an_untrusted_local_clock_does_not_count_against_the_peer() {
        let error = anyhow::Error::new(second_brain_core::sqlite_store::ClockUntrusted)
            .context("importing from the peer");
        assert!(!counts_against_peer(&error), "{error:#}");
    }

    #[test]
    fn store_maintenance_does_not_count_against_the_peer() {
        let sqlite = Arc::new(SqliteStore::in_memory("m".to_string()).unwrap());
        let gate = WriteGate::default();
        let clock = ClockGate::open_for_tests();
        let health = fresh_health();
        let local = StoreLocal {
            sqlite: &sqlite,
            gate: &gate,
            clock: &clock,
            health: &health,
            access: &DeviceAccess::default(),
            bootstrap: &Bootstrap::default(),
            data_dir: Path::new("/nonexistent"),
        };
        let _maintenance = gate.close();
        let error = local
            .set_cursor("peer", 1)
            .context("updating sync state")
            .unwrap_err();
        assert!(!counts_against_peer(&error), "{error:#}");
        assert!(counts_against_peer(&anyhow::anyhow!("connection refused")));
    }

    #[test]
    fn a_changed_peer_line_is_tried_without_the_old_lines_backoff() {
        let now = Instant::now();
        let later = now + Duration::from_secs(1);
        let bare = line_dial("user@pi");
        let fixed = line_dial("user@pi /opt/sb");
        let mut state = PeerBackoff::default();
        assert!(state.due(&bare, now));
        assert_eq!(state.failed(&bare, now), FIRST_BACKOFF);
        assert!(!state.due(&bare, later));
        assert!(state.due(&fixed, later));
        assert_eq!(state.failed(&fixed, later), FIRST_BACKOFF);
        assert_eq!(state.failed(&fixed, later), FIRST_BACKOFF * 2);
        assert!(state.due(&bare, later));
        state.succeeded();
        assert_eq!(state.failed(&fixed, later), FIRST_BACKOFF);
    }

    #[test]
    fn backoff_doubles_from_thirty_seconds_up_to_half_an_hour() {
        let waits: Vec<u64> = (1..=8).map(|n| backoff(n).as_secs()).collect();
        assert_eq!(waits, vec![30, 60, 120, 240, 480, 960, 1800, 1800]);
    }

    struct EmptyPeer;

    impl EmptyPeer {
        fn header() -> String {
            SyncHeader {
                hello: Some(Hello {
                    machine_id: "peer".to_string(),
                    wall_micros: Utc::now().timestamp_micros(),
                    synced: false,
                    cursor: None,
                    held_origin_seq: None,
                    keys: Some(shared_identity()),
                    peer_in: None,
                    log_floor: 0,
                    head: 0,
                    applied: None,
                    merging: None,
                }),
                ..SyncHeader::local()
            }
            .to_line()
        }
    }

    impl Transport for EmptyPeer {
        fn host(&self) -> &str {
            "user@pi"
        }

        fn whoami(&self) -> Result<String> {
            Ok("peer".to_string())
        }

        fn export(
            &self,
            _after_seq: u64,
            _hello: &Hello,
        ) -> Result<(Box<dyn Read + Send>, Box<dyn Remote>)> {
            let stream = format!("{}\n", Self::header()).into_bytes();
            Ok((Box::new(std::io::Cursor::new(stream)), Box::new(Exited)))
        }

        fn import(&self) -> Result<(Box<dyn Write + Send>, Box<dyn Read + Send>, Box<dyn Remote>)> {
            let replies = format!(
                "{}\n{}\n",
                Self::header(),
                PushApplied { applied: 0 }.to_line()
            );
            Ok((
                Box::new(std::io::sink()),
                Box::new(std::io::Cursor::new(replies.into_bytes())),
                Box::new(Exited),
            ))
        }
    }

    struct Exited;

    impl Remote for Exited {
        fn wait(&mut self) -> Result<Exit> {
            Ok(Exit {
                success: true,
                status: "exit status: 0".to_string(),
            })
        }

        fn stop(&mut self) -> Result<()> {
            Ok(())
        }
    }

    fn reachable() -> Connect {
        Arc::new(|_: &Route| -> Result<Box<dyn Transport + Send>> { Ok(Box::new(EmptyPeer)) })
    }

    fn refusing() -> Connect {
        Arc::new(|_: &Route| -> Result<Box<dyn Transport + Send>> {
            anyhow::bail!("connection refused")
        })
    }

    fn watched_loop(dir: &Path, connect: Connect) -> (Arc<SyncLoop>, Arc<Health>) {
        let health = Arc::new(Health::new(Utc::now(), None));
        let sync_loop = Arc::new(scripted_loop(dir, connect).with_health(health.clone()));
        std::fs::write(dir.join(peers::PEERS_FILE), "user@pi\n").unwrap();
        assert_eq!(sync_loop.listed_dials(), vec![line_dial("user@pi")]);
        (sync_loop, health)
    }

    fn the_one_peer(health: &Health) -> PeerSync {
        let mut peers = health.report().value.sync_peers;
        assert_eq!(peers.len(), 1, "{peers:?}");
        peers.remove(0)
    }

    fn run_job(sync_loop: &Arc<SyncLoop>, job: Job, dial: Dial) {
        let (jobs, inbox) = mpsc::channel();
        jobs.send((job, dial)).unwrap();
        drop(jobs);
        let worker = {
            let sync_loop = sync_loop.clone();
            std::thread::spawn(move || sync_loop.work(inbox))
        };
        let deadline = Instant::now() + Duration::from_secs(10);
        while !worker.is_finished() {
            assert!(
                Instant::now() < deadline,
                "the worker never finished its job"
            );
            std::thread::sleep(Duration::from_millis(10));
        }
        worker.join().unwrap();
    }

    struct Answering(&'static str);

    impl Transport for Answering {
        fn host(&self) -> &str {
            "me@192.0.2.1"
        }

        fn whoami(&self) -> Result<String> {
            Ok(self.0.to_string())
        }

        fn export(
            &self,
            after_seq: u64,
            hello: &Hello,
        ) -> Result<(Box<dyn Read + Send>, Box<dyn Remote>)> {
            EmptyPeer.export(after_seq, hello)
        }

        fn import(&self) -> Result<(Box<dyn Write + Send>, Box<dyn Read + Send>, Box<dyn Remote>)> {
            EmptyPeer.import()
        }
    }

    fn device_dial(machine_id: &str, addresses: &[&str]) -> Dial {
        Dial {
            key: machine_id.to_string(),
            label: machine_id.to_string(),
            machine_id: Some(machine_id.to_string()),
            routes: addresses
                .iter()
                .map(|address| Route::Device {
                    machine_id: machine_id.to_string(),
                    login: "me".to_string(),
                    address: address.to_string(),
                    port: 22,
                })
                .collect(),
        }
    }

    /// Answers with the id scripted for each address, recording the
    /// addresses dialled.
    fn answering(
        by_address: &'static [(&'static str, &'static str)],
    ) -> (Connect, Arc<Mutex<Vec<String>>>) {
        let dialled: Arc<Mutex<Vec<String>>> = Arc::default();
        let connect: Connect = {
            let dialled = dialled.clone();
            Arc::new(move |route: &Route| -> Result<Box<dyn Transport + Send>> {
                let Route::Device { address, .. } = route else {
                    anyhow::bail!("not a device route")
                };
                dialled.lock().unwrap().push(address.clone());
                let Some((_, id)) = by_address.iter().find(|(a, _)| a == address) else {
                    anyhow::bail!("connection refused")
                };
                Ok(Box::new(Answering(id)))
            })
        };
        (connect, dialled)
    }

    fn admit_new_device(sync_loop: &SyncLoop, dir: &Path, machine_id: &str) {
        let device = load_device_keys(dir).unwrap().unwrap();
        let identity_tag = sync_loop
            .sqlite
            .device_records()
            .unwrap()
            .into_iter()
            .find(|row| row.current.record.machine_id == "m")
            .unwrap()
            .current
            .record
            .identity_tag;
        let keys = DeviceKeys::generate().unwrap();
        let record = DeviceRecord {
            machine_id: machine_id.to_string(),
            identity_tag,
            version: 1,
            name: machine_id.to_string(),
            age_recipient: keys.age_recipient().to_string(),
            ssh_public_key: keys.ssh_public_key(),
            signing_public_key: keys.verifying_key().to_bytes(),
            recovery_fingerprints: Vec::new(),
            ssh_login: None,
            ssh_port: None,
            ssh_host_key: None,
        };
        admit_device(&sync_loop.sqlite, &device, record).unwrap();
    }

    fn revoke_new_device(sync_loop: &SyncLoop, dir: &Path, machine_id: &str) {
        admit_new_device(sync_loop, dir, machine_id);
        Keyring::load(&sync_loop.sqlite, dir)
            .unwrap()
            .remove_device(machine_id, &std::collections::BTreeSet::new(), 10)
            .unwrap();
    }

    #[test]
    fn a_route_answering_as_another_device_moves_on_to_the_next() {
        let dir = tempfile::tempdir().unwrap();
        let (connect, dialled) = answering(&[("192.0.2.1", "someone-else"), ("192.0.2.2", "peer")]);
        let sync_loop = scripted_loop(dir.path(), connect);
        sync_loop
            .sync(&device_dial("peer", &["192.0.2.1", "192.0.2.2"]), Job::Full)
            .unwrap();
        assert_eq!(*dialled.lock().unwrap(), vec!["192.0.2.1", "192.0.2.2"]);
    }

    #[test]
    fn a_route_answering_as_a_revoked_device_stops_the_dial() {
        let dir = tempfile::tempdir().unwrap();
        let (connect, dialled) = answering(&[("192.0.2.1", "stolen"), ("192.0.2.2", "peer")]);
        let sync_loop = scripted_loop(dir.path(), connect);
        revoke_new_device(&sync_loop, dir.path(), "stolen");
        assert!(
            sync_loop
                .sync(&device_dial("peer", &["192.0.2.1", "192.0.2.2"]), Job::Full)
                .is_err()
        );
        assert_eq!(*dialled.lock().unwrap(), vec!["192.0.2.1"]);
    }

    /// A loopback responder advertising each id's sshd as the login `me`.
    fn advertising(ids: &[&str]) -> Responder {
        let adverts: Vec<_> = ids
            .iter()
            .map(|id| mdns::device_advert(id, "me", 22))
            .collect();
        Responder::spawn(
            &Net::Unicast(std::net::SocketAddr::from((
                std::net::Ipv4Addr::LOCALHOST,
                0,
            ))),
            Arc::new(move || adverts.clone()),
        )
        .unwrap()
    }

    fn looking_up(sync_loop: SyncLoop, responder: &Responder) -> SyncLoop {
        SyncLoop {
            discovery: Some(Net::Unicast(responder.local_addr())),
            ..sync_loop
        }
    }

    fn held_addresses(sync_loop: &SyncLoop, machine_id: &str) -> Vec<String> {
        sync_loop
            .sqlite
            .device_route(machine_id)
            .unwrap()
            .map(|route| route.addresses)
            .unwrap_or_default()
    }

    fn hold_route(sync_loop: &SyncLoop, machine_id: &str, addresses: &[&str]) {
        sync_loop
            .sqlite
            .set_device_route(DeviceRoute {
                machine_id: machine_id.to_string(),
                addresses: addresses.iter().map(|a| a.to_string()).collect(),
                ssh_login: Some("me".to_string()),
                ssh_port: None,
            })
            .unwrap();
    }

    #[test]
    fn a_device_whose_address_changed_is_found_synced_and_recorded() {
        let dir = tempfile::tempdir().unwrap();
        let (connect, dialled) = answering(&[("127.0.0.1", "peer")]);
        let responder = advertising(&["peer"]);
        let sync_loop = looking_up(scripted_loop(dir.path(), connect), &responder);
        admit_new_device(&sync_loop, dir.path(), "peer");
        hold_route(&sync_loop, "peer", &["192.0.2.1"]);
        let dials = sync_loop.listed_dials();
        assert_eq!(dials.len(), 1, "{dials:?}");

        sync_loop.sync(&dials[0], Job::Full).unwrap();
        assert_eq!(*dialled.lock().unwrap(), vec!["192.0.2.1", "127.0.0.1"]);
        assert_eq!(
            held_addresses(&sync_loop, "peer"),
            vec!["127.0.0.1", "192.0.2.1"]
        );
        let Route::Device { address, .. } = &sync_loop.listed_dials()[0].routes[0] else {
            panic!("a device is dialled by its device route");
        };
        assert_eq!(address, "127.0.0.1");
    }

    #[test]
    fn an_address_now_held_by_another_machine_is_looked_past() {
        let dir = tempfile::tempdir().unwrap();
        let (connect, dialled) = answering(&[("192.0.2.1", "someone-else"), ("127.0.0.1", "peer")]);
        let responder = advertising(&["peer"]);
        let sync_loop = looking_up(scripted_loop(dir.path(), connect), &responder);
        admit_new_device(&sync_loop, dir.path(), "peer");
        hold_route(&sync_loop, "peer", &["192.0.2.1"]);
        sync_loop
            .sync(&sync_loop.listed_dials()[0], Job::Push)
            .unwrap();
        assert_eq!(*dialled.lock().unwrap(), vec!["192.0.2.1", "127.0.0.1"]);
        assert_eq!(held_addresses(&sync_loop, "peer")[0], "127.0.0.1");
    }

    #[test]
    fn a_device_with_no_address_is_looked_up_on_a_full_pass() {
        let dir = tempfile::tempdir().unwrap();
        let (connect, dialled) = answering(&[("127.0.0.1", "peer")]);
        let responder = advertising(&["peer"]);
        let sync_loop = looking_up(scripted_loop(dir.path(), connect), &responder);
        admit_new_device(&sync_loop, dir.path(), "peer");
        let mut dials = sync_loop.listed_dials();
        assert_eq!(dials, Vec::<Dial>::new());

        sync_loop.add_found(&mut dials);
        assert_eq!(dials.len(), 1, "{dials:?}");
        assert_eq!(dials[0].routes[0].describe(), "me@127.0.0.1");
        sync_loop.sync(&dials[0], Job::Full).unwrap();
        assert_eq!(*dialled.lock().unwrap(), vec!["127.0.0.1"]);
        assert_eq!(held_addresses(&sync_loop, "peer"), vec!["127.0.0.1"]);
        assert_eq!(sync_loop.listed_dials().len(), 1);
    }

    #[test]
    fn a_responder_under_an_unknown_or_revoked_id_is_never_dialled() {
        let dir = tempfile::tempdir().unwrap();
        let (connect, dialled) = answering(&[]);
        let responder = advertising(&["stranger", "stolen"]);
        let sync_loop = looking_up(scripted_loop(dir.path(), connect), &responder);
        revoke_new_device(&sync_loop, dir.path(), "stolen");
        admit_new_device(&sync_loop, dir.path(), "peer");
        hold_route(&sync_loop, "peer", &["192.0.2.1"]);

        let mut dials = sync_loop.listed_dials();
        assert!(sync_loop.sync(&dials[0], Job::Full).is_err());
        assert_eq!(*dialled.lock().unwrap(), vec!["192.0.2.1"]);
        sync_loop.add_found(&mut dials);
        assert_eq!(
            dials.iter().map(|d| d.key.as_str()).collect::<Vec<_>>(),
            vec!["peer"]
        );
        assert_eq!(held_addresses(&sync_loop, "peer"), vec!["192.0.2.1"]);
        assert_eq!(held_addresses(&sync_loop, "stolen"), Vec::<String>::new());
        assert_eq!(held_addresses(&sync_loop, "stranger"), Vec::<String>::new());
    }

    #[test]
    fn a_full_sync_reports_the_peer_synced() {
        let dir = tempfile::tempdir().unwrap();
        let (sync_loop, health) = watched_loop(dir.path(), reachable());
        let before = Utc::now();
        run_job(&sync_loop, Job::Full, line_dial("user@pi"));
        let peer = the_one_peer(&health);
        assert_eq!(peer.peer, "user@pi");
        let synced = peer.last_success_at.expect("a full sync is a success");
        assert!(synced >= before, "{synced} predates the sync");
        assert_eq!(peer.consecutive_failures, 0);
    }

    #[test]
    fn a_failed_sync_counts_a_failure_and_no_success() {
        let dir = tempfile::tempdir().unwrap();
        let (sync_loop, health) = watched_loop(dir.path(), refusing());
        run_job(&sync_loop, Job::Full, line_dial("user@pi"));
        let peer = the_one_peer(&health);
        assert_eq!(peer.peer, "user@pi");
        assert_eq!(peer.consecutive_failures, 1);
        assert_eq!(peer.last_success_at, None);
        assert!(peer.last_attempt_at.is_some(), "the failure is an attempt");
        let error = peer.last_error.expect("the failure's text is kept");
        assert!(error.contains("connection refused"), "{error}");
    }

    #[test]
    fn start_deletes_the_plaintext_ssh_key_once_the_device_key_loads() {
        let dir = tempfile::tempdir().unwrap();
        let sqlite = SqliteStore::in_memory("m".to_string()).unwrap();
        second_brain_core::keys::ensure_device_keys(&sqlite, dir.path()).unwrap();
        let keys = load_device_keys(dir.path()).unwrap().unwrap();
        let legacy = dir.path().join(SSH_KEY_FILE);
        write_identity_file(&legacy, keys.ssh_signing_key(), "second-brain:m").unwrap();
        let before = std::fs::read(&legacy).unwrap();

        assert!(retire_plaintext_ssh_key(dir.path()).unwrap());
        assert!(!legacy.exists());
        assert!(!retire_plaintext_ssh_key(dir.path()).unwrap());

        let reloaded = load_device_keys(dir.path()).unwrap().unwrap();
        let elsewhere = tempfile::tempdir().unwrap();
        let rederived = elsewhere.path().join("id");
        write_identity_file(&rederived, reloaded.ssh_signing_key(), "second-brain:m").unwrap();
        assert_eq!(std::fs::read(&rederived).unwrap(), before);
    }

    #[test]
    fn a_plaintext_ssh_key_stays_while_no_device_key_loads() {
        let dir = tempfile::tempdir().unwrap();
        let legacy = dir.path().join(SSH_KEY_FILE);
        let stray = DeviceKeys::generate().unwrap();
        write_identity_file(&legacy, stray.ssh_signing_key(), "second-brain:m").unwrap();
        assert!(!retire_plaintext_ssh_key(dir.path()).unwrap());
        assert!(legacy.exists());

        std::fs::write(
            dir.path().join(second_brain_core::keys::DEVICE_KEY_FILE),
            b"torn",
        )
        .unwrap();
        assert!(retire_plaintext_ssh_key(dir.path()).is_err());
        assert!(legacy.exists());
    }

    #[test]
    fn a_push_from_a_device_without_an_identity_is_not_held_against_the_peer() {
        let dir = tempfile::tempdir().unwrap();
        let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let connect: Connect = {
            let calls = calls.clone();
            Arc::new(move |_: &Route| -> Result<Box<dyn Transport + Send>> {
                calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                anyhow::bail!("connection refused")
            })
        };
        let sqlite = SqliteStore::in_memory("m".to_string()).unwrap();
        second_brain_core::keys::ensure_device_keys(&sqlite, dir.path()).unwrap();
        let health = Arc::new(Health::new(Utc::now(), None));
        let sync_loop = Arc::new(SyncLoop {
            data_dir: dir.path().to_path_buf(),
            sqlite: Arc::new(sqlite),
            gate: Arc::new(WriteGate::default()),
            clock: ClockGate::open_for_tests(),
            health: health.clone(),
            access: Arc::default(),
            bootstrap: Arc::default(),
            connect,
            discovery: None,
        });
        std::fs::write(dir.path().join(peers::PEERS_FILE), "user@pi\n").unwrap();
        sync_loop.listed_dials();

        run_job(&sync_loop, Job::Push, line_dial("user@pi"));
        assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 0);
        let peer = the_one_peer(&health);
        assert_eq!(peer.last_attempt_at, None);
        assert_eq!(peer.consecutive_failures, 0);

        run_job(&sync_loop, Job::Full, line_dial("user@pi"));
        assert_eq!(calls.load(std::sync::atomic::Ordering::SeqCst), 1);
        assert_eq!(the_one_peer(&health).consecutive_failures, 1);
    }

    #[test]
    fn a_push_ends_a_failure_streak_without_counting_as_a_sync() {
        let dir = tempfile::tempdir().unwrap();
        let calls = Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let connect: Connect = {
            let calls = calls.clone();
            Arc::new(move |_: &Route| -> Result<Box<dyn Transport + Send>> {
                if calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst) == 0 {
                    anyhow::bail!("connection refused");
                }
                Ok(Box::new(EmptyPeer))
            })
        };
        let (sync_loop, health) = watched_loop(dir.path(), connect);
        run_job(&sync_loop, Job::Full, line_dial("user@pi"));
        assert_eq!(the_one_peer(&health).consecutive_failures, 1);
        run_job(&sync_loop, Job::Push, line_dial("user@pi"));
        let peer = the_one_peer(&health);
        assert_eq!(peer.last_success_at, None);
        assert!(peer.last_attempt_at.is_some());
        assert_eq!(peer.consecutive_failures, 0);
    }

    #[test]
    fn maintenance_reports_no_sync_outcome() {
        let dir = tempfile::tempdir().unwrap();
        let connect: Connect = Arc::new(|_: &Route| -> Result<Box<dyn Transport + Send>> {
            Err(anyhow::Error::new(MaintenanceRunning))
        });
        let (sync_loop, health) = watched_loop(dir.path(), connect);
        run_job(&sync_loop, Job::Full, line_dial("user@pi"));
        let peer = the_one_peer(&health);
        assert_eq!(peer.last_success_at, None);
        assert_eq!(peer.last_attempt_at, None);
        assert_eq!(peer.consecutive_failures, 0);
    }

    #[test]
    fn a_peer_removed_from_sync_peers_drops_out_of_health() {
        let dir = tempfile::tempdir().unwrap();
        let (sync_loop, health) = watched_loop(dir.path(), refusing());
        let listed = |text: &str| {
            std::fs::write(dir.path().join(peers::PEERS_FILE), text).unwrap();
            let kept = sync_loop.listed_dials();
            let mut reported: Vec<String> = health
                .report()
                .value
                .sync_peers
                .into_iter()
                .map(|peer| peer.peer)
                .collect();
            reported.sort();
            (kept.len(), reported)
        };
        assert_eq!(
            listed("user@pi\nuser@mac\nuser@pi /opt/sb\n"),
            (2, vec!["user@mac".to_string(), "user@pi".to_string()])
        );
        assert_eq!(listed("user@mac\n"), (1, vec!["user@mac".to_string()]));
    }

    #[test]
    fn an_unreadable_sync_peers_keeps_its_peers_in_health() {
        let dir = tempfile::tempdir().unwrap();
        let (sync_loop, health) = watched_loop(dir.path(), refusing());
        let file = dir.path().join(peers::PEERS_FILE);
        std::fs::remove_file(&file).unwrap();
        std::fs::create_dir(&file).unwrap();
        assert!(peers::configured_peers(dir.path()).is_err());

        assert_eq!(sync_loop.listed_dials(), Vec::<Dial>::new());
        assert_eq!(the_one_peer(&health).peer, "user@pi");
    }
}