wsb-daemon 0.248.6265

wsb's daemon: the workbench, the GitHub mirror's schedule and peer continuity, for every workspace on the machine
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
//! What survives a restart: peers, relationships, baselines and conflicts.
//!
//! A machine-level SQLite database beside the machine identity, separate from
//! every workspace's own. The split is deliberate — see `wsb::daemon::machine`.
//! Peers are a fact about this MACHINE; a workspace's model, catalogue and
//! secrets are facts about the workspace, and putting them in one file would
//! make the daemon's globalisation a globalisation of everything it touches.
//!
//! # What must survive, and what must not
//!
//! Survive: which machines are paired and their pinned keys, which
//! relationships the operator enabled, the baselines convergence is computed
//! against, and every unresolved conflict. Losing any of those loses work or
//! trust.
//!
//! Must NOT survive as fact: "synced". That is an observation about two live
//! trees, and a daemon that came back up and believed a stored `synced` would
//! skip the very check that tells it the tree changed while it was down. It is
//! recomputed, always, from `checking`.

use std::collections::BTreeMap;
use std::path::Path;

use rusqlite::{params, Connection, OptionalExtension};
use wsb::peer::converge::{Baseline, Entry, EntryKind};
use wsb::peer::identity::{Fingerprint, PairedPeer};
use wsb::peer::model::{Desired, PeerId, RepositoryId, Service, Switch, SyncMode, WorkspaceId};

/// The machine's own database.
pub struct MachineStore {
    connection: std::sync::Mutex<Connection>,
}

impl MachineStore {
    /// Open it, creating the schema the first time.
    pub fn open(machine_dir: &Path) -> Result<Self, String> {
        let path = machine_dir.join("machine.db");
        let connection = Connection::open(&path)
            .map_err(|e| format!("cannot open {}: {e}", path.display()))?;
        // Write-ahead logging: the coordinator writes baselines while the web
        // handlers read state, and a reader blocking a write here would stall
        // a transfer behind a page refresh.
        connection
            .execute_batch(
                "PRAGMA journal_mode = WAL;
                 PRAGMA synchronous = FULL;
                 PRAGMA foreign_keys = ON;",
            )
            .map_err(|e| format!("cannot configure {}: {e}", path.display()))?;
        let store = Self {
            connection: std::sync::Mutex::new(connection),
        };
        store.migrate()?;
        Ok(store)
    }


    fn with<T>(&self, body: impl FnOnce(&Connection) -> Result<T, rusqlite::Error>) -> Result<T, String> {
        let connection = self
            .connection
            .lock()
            .map_err(|_| "the machine database is unusable after a panic".to_string())?;
        body(&connection).map_err(|e| format!("machine database: {e}"))
    }

    fn migrate(&self) -> Result<(), String> {
        self.with(|c| {
            c.execute_batch(
                r#"
                -- A machine this one has been introduced to. The public key is
                -- the identity; everything else is presentation or a hint.
                CREATE TABLE IF NOT EXISTS peers (
                    peer_id     TEXT PRIMARY KEY NOT NULL,
                    name        TEXT NOT NULL,
                    public_key  TEXT NOT NULL,
                    fingerprint TEXT NOT NULL,
                    address     TEXT NOT NULL,
                    paired_at   INTEGER NOT NULL,
                    last_seen   INTEGER
                );

                -- One workspace, on one peer: what the operator asked for.
                -- Observed state is NOT here; it is recomputed every time.
                CREATE TABLE IF NOT EXISTS relationships (
                    peer_id      TEXT NOT NULL REFERENCES peers(peer_id) ON DELETE CASCADE,
                    workspace_id TEXT NOT NULL,
                    desired      TEXT NOT NULL,
                    enabled_at   INTEGER NOT NULL,
                    PRIMARY KEY (peer_id, workspace_id)
                );

                -- The last state both sides acknowledged, per path. This is
                -- the thing that makes convergence three-way rather than a
                -- copy, and losing it silently turns every edit into a
                -- conflict.
                CREATE TABLE IF NOT EXISTS baselines (
                    peer_id      TEXT NOT NULL,
                    workspace_id TEXT NOT NULL,
                    repository   TEXT NOT NULL,
                    path         TEXT NOT NULL,
                    kind         TEXT NOT NULL,
                    hash         TEXT NOT NULL,
                    size         INTEGER NOT NULL,
                    executable   INTEGER NOT NULL,
                    PRIMARY KEY (peer_id, workspace_id, repository, path)
                );

                -- A path both sides changed differently. Kept until a person
                -- resolves it: both versions stay recoverable, and the
                -- baseline for that path does not move.
                CREATE TABLE IF NOT EXISTS conflicts (
                    peer_id      TEXT NOT NULL,
                    workspace_id TEXT NOT NULL,
                    repository   TEXT NOT NULL,
                    path         TEXT NOT NULL,
                    here_hash    TEXT,
                    there_hash   TEXT,
                    base_hash    TEXT,
                    detected_at  INTEGER NOT NULL,
                    PRIMARY KEY (peer_id, workspace_id, repository, path)
                );

                -- Which repositories have had a baseline established at all.
                --
                -- An empty baseline and a never-seeded one look identical in
                -- the table above — no rows — and they mean opposite things:
                -- one says "both sides have agreed that this repository is
                -- empty", the other says "nothing has been agreed yet". The
                -- second must seed from the commit both sides share, and the
                -- first must not.
                CREATE TABLE IF NOT EXISTS baseline_seeded (
                    peer_id      TEXT NOT NULL,
                    workspace_id TEXT NOT NULL,
                    repository   TEXT NOT NULL,
                    seeded_at    INTEGER NOT NULL,
                    PRIMARY KEY (peer_id, workspace_id, repository)
                );

                -- A conflict a person has settled, waiting to be carried.
                --
                -- A decision, not an edit: the next reconciliation turns it
                -- into an ordinary transfer, which is what makes a resolution
                -- go through the same epoch check, the same verification and
                -- the same acknowledgement as every other change. Moving the
                -- baseline here instead would change a shared fact on one
                -- machine only, and the two would then refuse each other's
                -- transfers for ever.
                CREATE TABLE IF NOT EXISTS resolutions (
                    peer_id      TEXT NOT NULL,
                    workspace_id TEXT NOT NULL,
                    repository   TEXT NOT NULL,
                    path         TEXT NOT NULL,
                    -- 'here' | 'there'
                    keep         TEXT NOT NULL,
                    decided_at   INTEGER NOT NULL,
                    PRIMARY KEY (peer_id, workspace_id, repository, path)
                );

                -- Which of the things two paired machines do for each other
                -- are switched on with this one.
                --
                -- A row per service that has been decided; an absent row is
                -- the default, which is on. Machine-wide rather than per
                -- workspace, because "stop carrying files with the laptop" and
                -- "stop answering the laptop about secrets" are decisions
                -- about a MACHINE, and having to make each of them once per
                -- workspace is how somebody ends up with the laptop still
                -- syncing one of five.
                CREATE TABLE IF NOT EXISTS peer_services (
                    peer_id    TEXT NOT NULL REFERENCES peers(peer_id) ON DELETE CASCADE,
                    service    TEXT NOT NULL,
                    switch     TEXT NOT NULL,
                    changed_at INTEGER NOT NULL,
                    PRIMARY KEY (peer_id, service)
                );

                -- A difference somebody chose to leave alone.
                --
                -- Keyed by the pair of hashes it was dismissed AT, not by the
                -- path: "I do not care about this file as it stands" is a
                -- statement about two versions of it, and a machine that kept
                -- hiding the path after either side changed would be hiding
                -- work rather than noise. Either hash absent means that side
                -- does not have the file, which is itself a state somebody can
                -- dismiss.
                CREATE TABLE IF NOT EXISTS dismissals (
                    peer_id      TEXT NOT NULL,
                    workspace_id TEXT NOT NULL,
                    repository   TEXT NOT NULL,
                    path         TEXT NOT NULL,
                    here_hash    TEXT,
                    there_hash   TEXT,
                    dismissed_at INTEGER NOT NULL,
                    PRIMARY KEY (peer_id, workspace_id, repository, path)
                );

                -- Every worktree this machine has opened, so the page can
                -- list them without walking the filesystem. Keyed by what this
                -- machine calls it; `workspace_id` is what a peer calls it,
                -- absent while it has nothing a peer could recognise.
                CREATE TABLE IF NOT EXISTS worktrees (
                    worktree_id  TEXT PRIMARY KEY NOT NULL,
                    project      TEXT,
                    name         TEXT NOT NULL,
                    workspace_id TEXT,
                    super_root   TEXT NOT NULL,
                    root_commit  TEXT,
                    last_seen    INTEGER NOT NULL
                );

                -- Keyed by repository alone, which handed every worktree of a
                -- project the first one's state. Its rows describe no worktree.
                DROP TABLE IF EXISTS workspaces;
                "#,
            )
        })?;

        // Continuity named a repository, not one of its worktrees, before
        // workspace ids carried the worktree's name (`<family>@<name>`). A
        // relationship, baseline or conflict under the old id says nothing
        // about which worktree it was for, so none of them can be carried
        // forward; peers and their pinned keys are not keyed by it and stay.
        let dropped = self.with(|c| {
            let mut dropped = 0;
            for table in [
                "relationships",
                "baselines",
                "conflicts",
                "baseline_seeded",
                "resolutions",
                "dismissals",
            ] {
                dropped += c.execute(
                    &format!("DELETE FROM {table} WHERE instr(workspace_id, '@') = 0"),
                    [],
                )?;
            }
            Ok(dropped)
        })?;
        if dropped > 0 {
            tracing::warn!(
                rows = dropped,
                "dropped continuity records that named a repository rather than a worktree; \
                 enable continuity again with `wsb peer sync <peer>` in each worktree"
            );
        }

        // How a workspace is carried, added to relationships that already
        // existed. `CREATE TABLE IF NOT EXISTS` does nothing for a table that
        // is already there, and this database holds the pinned keys of every
        // paired machine — recreating it to add a column would end every trust
        // relationship on the machine.
        //
        // Manual for the rows that predate the column, which is the same
        // default a new relationship gets: a machine that upgrades must not
        // start moving files while nobody is looking.
        let has_mode = self.with(|c| {
            let mut statement = c.prepare("PRAGMA table_info(relationships)")?;
            let mut rows = statement.query([])?;
            let mut found = false;
            while let Some(row) = rows.next()? {
                if row.get::<_, String>(1)? == "mode" {
                    found = true;
                }
            }
            Ok(found)
        })?;
        if !has_mode {
            self.with(|c| {
                c.execute_batch(
                    "ALTER TABLE relationships ADD COLUMN mode TEXT NOT NULL DEFAULT 'manual'",
                )
            })?;
        }
        Ok(())
    }

    // ── peers ──────────────────────────────────────────────────────────────

    pub fn add_peer(&self, peer: &PairedPeer) -> Result<(), String> {
        self.with(|c| {
            c.execute(
                "INSERT INTO peers (peer_id, name, public_key, fingerprint, address, paired_at)
                 VALUES (?1, ?2, ?3, ?4, ?5, ?6)
                 ON CONFLICT(peer_id) DO UPDATE SET
                     name = excluded.name,
                     address = excluded.address",
                params![
                    peer.id.as_str(),
                    peer.name,
                    peer.public_key,
                    peer.fingerprint.as_str(),
                    peer.address,
                    peer.paired_at as i64,
                ],
            )?;
            Ok(())
        })?;
        // A peer whose key changed is a different machine wearing a name.
        // Re-pairing is the only way in, and it goes through `remove_peer`
        // first — so this refuses rather than updating the key in place.
        let stored = self.peer(&peer.id)?.ok_or_else(|| "the peer vanished".to_string())?;
        if stored.public_key != peer.public_key {
            return Err(format!(
                "{} is already paired with a different identity ({}). Remove it first if \
                 this is deliberate.",
                peer.id, stored.fingerprint
            ));
        }
        Ok(())
    }

    pub fn peer(&self, id: &PeerId) -> Result<Option<PairedPeer>, String> {
        self.with(|c| {
            c.query_row(
                "SELECT peer_id, name, public_key, fingerprint, address, paired_at
                 FROM peers WHERE peer_id = ?1",
                params![id.as_str()],
                row_to_peer,
            )
            .optional()
        })
    }

    pub fn peers(&self) -> Result<Vec<PairedPeer>, String> {
        self.with(|c| {
            let mut statement = c.prepare(
                "SELECT peer_id, name, public_key, fingerprint, address, paired_at
                 FROM peers ORDER BY name, peer_id",
            )?;
            let rows = statement.query_map([], row_to_peer)?;
            rows.collect()
        })
    }

    /// Forget a peer and everything that depended on trusting it.
    ///
    /// The baselines go with it deliberately: they describe an agreement with
    /// a machine this one no longer trusts, and keeping them would let a
    /// re-pairing silently continue from a state neither side verified.
    pub fn remove_peer(&self, id: &PeerId) -> Result<bool, String> {
        self.with(|c| {
            c.execute("DELETE FROM baselines WHERE peer_id = ?1", params![id.as_str()])?;
            c.execute(
                "DELETE FROM baseline_seeded WHERE peer_id = ?1",
                params![id.as_str()],
            )?;
            c.execute("DELETE FROM conflicts WHERE peer_id = ?1", params![id.as_str()])?;
            c.execute("DELETE FROM resolutions WHERE peer_id = ?1", params![id.as_str()])?;
            c.execute("DELETE FROM relationships WHERE peer_id = ?1", params![id.as_str()])?;
            let removed = c.execute("DELETE FROM peers WHERE peer_id = ?1", params![id.as_str()])?;
            Ok(removed > 0)
        })
    }

    pub fn note_seen(&self, id: &PeerId, when: u64) -> Result<(), String> {
        self.with(|c| {
            c.execute(
                "UPDATE peers SET last_seen = ?2 WHERE peer_id = ?1",
                params![id.as_str(), when as i64],
            )?;
            Ok(())
        })
    }

    pub fn last_seen(&self, id: &PeerId) -> Result<Option<u64>, String> {
        self.with(|c| {
            c.query_row(
                "SELECT last_seen FROM peers WHERE peer_id = ?1",
                params![id.as_str()],
                |row| row.get::<_, Option<i64>>(0),
            )
            .optional()
            .map(|value| value.flatten().map(|v| v as u64))
        })
    }

    // ── relationships ──────────────────────────────────────────────────────

    pub fn set_desired(
        &self,
        peer: &PeerId,
        workspace: &WorkspaceId,
        desired: Desired,
        when: u64,
    ) -> Result<(), String> {
        self.with(|c| {
            c.execute(
                "INSERT INTO relationships (peer_id, workspace_id, desired, enabled_at)
                 VALUES (?1, ?2, ?3, ?4)
                 ON CONFLICT(peer_id, workspace_id) DO UPDATE SET desired = excluded.desired",
                params![peer.as_str(), workspace.as_str(), desired.as_str(), when as i64],
            )?;
            Ok(())
        })
    }

    /// Which services run with one peer.
    ///
    /// Absent rows are the default rather than an error: pairing writes no
    /// service rows, and a machine paired before this table existed has none
    /// either. The default is stated once, in the model.
    pub fn services(&self, peer: &PeerId) -> Result<BTreeMap<Service, Switch>, String> {
        let stored: Vec<(String, String)> = self.with(|c| {
            let mut statement =
                c.prepare("SELECT service, switch FROM peer_services WHERE peer_id = ?1")?;
            let rows = statement.query_map(params![peer.as_str()], |row| {
                Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
            })?;
            let mut out = Vec::new();
            for row in rows {
                out.push(row?);
            }
            Ok(out)
        })?;

        let mut services = BTreeMap::new();
        // wsb's own services always appear; a plugin's appears once a switch
        // for it has been written, and is off until then (see the model).
        for service in Service::BUILT_IN {
            let default = Switch::default_for(&service);
            services.insert(service, default);
        }
        for (service, switch) in stored {
            // A row naming a service this build does not have is a database
            // from a later version. Ignored, not fatal: the services it does
            // know about still answer.
            let (Ok(service), Ok(switch)) = (Service::parse(&service), Switch::parse(&switch))
            else {
                continue;
            };
            services.insert(service, switch);
        }
        Ok(services)
    }

    /// Whether one service runs with one peer.
    pub fn service(&self, peer: &PeerId, service: Service) -> Result<Switch, String> {
        Ok(self
            .services(peer)?
            .get(&service)
            .copied()
            .unwrap_or_else(|| Switch::default_for(&service)))
    }

    pub fn set_service(
        &self,
        peer: &PeerId,
        service: Service,
        switch: Switch,
        when: u64,
    ) -> Result<(), String> {
        self.with(|c| {
            c.execute(
                "INSERT INTO peer_services (peer_id, service, switch, changed_at)
                 VALUES (?1, ?2, ?3, ?4)
                 ON CONFLICT(peer_id, service) DO UPDATE SET
                     switch = excluded.switch,
                     changed_at = excluded.changed_at",
                params![peer.as_str(), service.as_str(), switch.as_str(), when as i64],
            )?;
            Ok(())
        })
    }

    /// How this workspace is carried with this peer: by hand, or by itself.
    pub fn mode(&self, peer: &PeerId, workspace: &WorkspaceId) -> Result<SyncMode, String> {
        let stored: Option<String> = self.with(|c| {
            c.query_row(
                "SELECT mode FROM relationships WHERE peer_id = ?1 AND workspace_id = ?2",
                params![peer.as_str(), workspace.as_str()],
                |row| row.get(0),
            )
            .optional()
        })?;
        Ok(stored
            .as_deref()
            .and_then(|raw| SyncMode::parse(raw).ok())
            .unwrap_or_default())
    }

    /// Set the mode, whether or not the workspace is being carried yet.
    ///
    /// A relationship row is created if there is none: choosing how a
    /// workspace would be carried before choosing to carry it is an ordinary
    /// order to do things in, and refusing it would make the workbench's two
    /// switches depend on which was touched first.
    pub fn set_mode(
        &self,
        peer: &PeerId,
        workspace: &WorkspaceId,
        mode: SyncMode,
        when: u64,
    ) -> Result<(), String> {
        self.with(|c| {
            c.execute(
                "INSERT INTO relationships (peer_id, workspace_id, desired, enabled_at, mode)
                 VALUES (?1, ?2, ?3, ?4, ?5)
                 ON CONFLICT(peer_id, workspace_id) DO UPDATE SET mode = excluded.mode",
                params![
                    peer.as_str(),
                    workspace.as_str(),
                    Desired::Disabled.as_str(),
                    when as i64,
                    mode.as_str()
                ],
            )?;
            Ok(())
        })
    }

    pub fn desired(&self, peer: &PeerId, workspace: &WorkspaceId) -> Result<Desired, String> {
        let stored: Option<String> = self.with(|c| {
            c.query_row(
                "SELECT desired FROM relationships WHERE peer_id = ?1 AND workspace_id = ?2",
                params![peer.as_str(), workspace.as_str()],
                |row| row.get(0),
            )
            .optional()
        })?;
        Ok(match stored.as_deref() {
            Some("enabled") => Desired::Enabled,
            Some("paused") => Desired::Paused,
            // Never asked for, or explicitly turned off.
            _ => Desired::Disabled,
        })
    }

    /// Every relationship the operator has an opinion about.
    pub fn relationships(&self) -> Result<Vec<(PeerId, WorkspaceId, Desired)>, String> {
        let rows = self.with(|c| {
            let mut statement = c.prepare(
                "SELECT peer_id, workspace_id, desired FROM relationships
                 ORDER BY peer_id, workspace_id",
            )?;
            let rows = statement.query_map([], |row| {
                let peer: String = row.get(0)?;
                let workspace: String = row.get(1)?;
                let desired: String = row.get(2)?;
                Ok((peer, workspace, desired))
            })?;
            rows.collect::<Result<Vec<_>, _>>()
        })?;
        // A row whose ids do not parse is a database somebody edited: every
        // id is written from a parsed one. Named, rather than skipped — a
        // relationship that silently stopped existing is one nobody can find.
        rows.into_iter()
            .map(|(peer, workspace, desired)| {
                let peer = PeerId::parse(&peer)
                    .map_err(|e| format!("machine database, relationships: {e}"))?;
                let workspace = WorkspaceId::parse(&workspace)
                    .map_err(|e| format!("machine database, relationships: {e}"))?;
                let desired = match desired.as_str() {
                    "enabled" => Desired::Enabled,
                    "paused" => Desired::Paused,
                    "disabled" => Desired::Disabled,
                    other => {
                        return Err(format!(
                            "machine database, relationship {peer}/{workspace}: '{other}' is not \
                             enabled, paused or disabled"
                        ))
                    }
                };
                Ok((peer, workspace, desired))
            })
            .collect()
    }

    // ── baselines ──────────────────────────────────────────────────────────

    pub fn baseline(
        &self,
        peer: &PeerId,
        workspace: &WorkspaceId,
        repository: &RepositoryId,
    ) -> Result<Baseline, String> {
        self.with(|c| {
            let mut statement = c.prepare(
                "SELECT path, kind, hash, size, executable FROM baselines
                 WHERE peer_id = ?1 AND workspace_id = ?2 AND repository = ?3",
            )?;
            let rows = statement.query_map(
                params![peer.as_str(), workspace.as_str(), repository.as_str()],
                |row| {
                    let path: String = row.get(0)?;
                    let kind: String = row.get(1)?;
                    Ok((
                        path,
                        Entry {
                            kind: if kind == "symlink" {
                                EntryKind::Symlink
                            } else {
                                EntryKind::File
                            },
                            hash: row.get(2)?,
                            size: row.get::<_, i64>(3)? as u64,
                            executable: row.get::<_, i64>(4)? != 0,
                        },
                    ))
                },
            )?;
            let mut baseline = Baseline::new();
            for row in rows {
                let (path, entry) = row?;
                baseline.insert(path, entry);
            }
            Ok(baseline)
        })
    }

    /// Replace one repository's baseline, in one transaction.
    ///
    /// Whole rather than incremental: a baseline is the state both sides
    /// agreed on at one moment, and a half-written one describes a moment that
    /// never existed.
    pub fn put_baseline(
        &self,
        peer: &PeerId,
        workspace: &WorkspaceId,
        repository: &RepositoryId,
        baseline: &Baseline,
    ) -> Result<(), String> {
        self.with(|c| {
            let transaction = c.unchecked_transaction()?;
            transaction.execute(
                "DELETE FROM baselines WHERE peer_id = ?1 AND workspace_id = ?2 AND repository = ?3",
                params![peer.as_str(), workspace.as_str(), repository.as_str()],
            )?;
            {
                let mut insert = transaction.prepare(
                    "INSERT INTO baselines
                     (peer_id, workspace_id, repository, path, kind, hash, size, executable)
                     VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)",
                )?;
                for (path, entry) in baseline {
                    insert.execute(params![
                        peer.as_str(),
                        workspace.as_str(),
                        repository.as_str(),
                        path,
                        match entry.kind {
                            EntryKind::File => "file",
                            EntryKind::Symlink => "symlink",
                        },
                        entry.hash,
                        entry.size as i64,
                        i64::from(entry.executable),
                    ])?;
                }
            }
            transaction.commit()
        })
    }

    /// Whether this repository's baseline has ever been established.
    pub fn is_seeded(
        &self,
        peer: &PeerId,
        workspace: &WorkspaceId,
        repository: &RepositoryId,
    ) -> Result<bool, String> {
        self.with(|c| {
            c.query_row(
                "SELECT 1 FROM baseline_seeded
                 WHERE peer_id = ?1 AND workspace_id = ?2 AND repository = ?3",
                params![peer.as_str(), workspace.as_str(), repository.as_str()],
                |_| Ok(()),
            )
            .optional()
            .map(|found| found.is_some())
        })
    }

    pub fn mark_seeded(
        &self,
        peer: &PeerId,
        workspace: &WorkspaceId,
        repository: &RepositoryId,
        when: u64,
    ) -> Result<(), String> {
        self.with(|c| {
            c.execute(
                "INSERT OR REPLACE INTO baseline_seeded
                 (peer_id, workspace_id, repository, seeded_at) VALUES (?1, ?2, ?3, ?4)",
                params![
                    peer.as_str(),
                    workspace.as_str(),
                    repository.as_str(),
                    when as i64
                ],
            )?;
            Ok(())
        })
    }

    // ── conflicts ──────────────────────────────────────────────────────────

    pub fn record_conflict(
        &self,
        peer: &PeerId,
        workspace: &WorkspaceId,
        repository: &RepositoryId,
        path: &str,
        here: Option<&Entry>,
        there: Option<&Entry>,
        base: Option<&Entry>,
        when: u64,
    ) -> Result<(), String> {
        self.with(|c| {
            c.execute(
                "INSERT INTO conflicts
                 (peer_id, workspace_id, repository, path, here_hash, there_hash, base_hash, detected_at)
                 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)
                 ON CONFLICT(peer_id, workspace_id, repository, path) DO UPDATE SET
                     here_hash = excluded.here_hash,
                     there_hash = excluded.there_hash",
                params![
                    peer.as_str(),
                    workspace.as_str(),
                    repository.as_str(),
                    path,
                    here.map(|e| e.hash.clone()),
                    there.map(|e| e.hash.clone()),
                    base.map(|e| e.hash.clone()),
                    when as i64,
                ],
            )?;
            Ok(())
        })
    }

    pub fn conflicts(
        &self,
        peer: &PeerId,
        workspace: &WorkspaceId,
    ) -> Result<Vec<ConflictRow>, String> {
        self.with(|c| {
            let mut statement = c.prepare(
                "SELECT repository, path, here_hash, there_hash, base_hash, detected_at
                 FROM conflicts WHERE peer_id = ?1 AND workspace_id = ?2
                 ORDER BY repository, path",
            )?;
            let rows = statement.query_map(params![peer.as_str(), workspace.as_str()], |row| {
                Ok(ConflictRow {
                    repository: row.get(0)?,
                    path: row.get(1)?,
                    here_hash: row.get(2)?,
                    there_hash: row.get(3)?,
                    base_hash: row.get(4)?,
                    detected_at: row.get::<_, i64>(5)? as u64,
                })
            })?;
            rows.collect()
        })
    }

    /// Every unresolved conflict on this machine, counted by where it is.
    ///
    /// One query rather than one per relationship: the count is read by the
    /// workbench on every refresh, and asking per peer and per workspace would
    /// be N queries to answer "is anything waiting for me".
    pub fn conflict_counts(&self) -> Result<Vec<ConflictCount>, String> {
        self.with(|c| {
            let mut statement = c.prepare(
                "SELECT workspace_id, repository, peer_id, COUNT(*)
                 FROM conflicts
                 GROUP BY workspace_id, repository, peer_id
                 ORDER BY workspace_id, repository, peer_id",
            )?;
            let rows = statement.query_map([], |row| {
                Ok(ConflictCount {
                    workspace: row.get(0)?,
                    repository: row.get(1)?,
                    peer: row.get(2)?,
                    conflicts: row.get::<_, i64>(3)? as usize,
                })
            })?;
            rows.collect()
        })
    }

    pub fn clear_conflict(
        &self,
        peer: &PeerId,
        workspace: &WorkspaceId,
        repository: &RepositoryId,
        path: &str,
    ) -> Result<(), String> {
        self.with(|c| {
            c.execute(
                "DELETE FROM conflicts
                 WHERE peer_id = ?1 AND workspace_id = ?2 AND repository = ?3 AND path = ?4",
                params![peer.as_str(), workspace.as_str(), repository.as_str(), path],
            )?;
            Ok(())
        })
    }

    /// Record a person's decision about one conflicted path.
    pub fn set_resolution(
        &self,
        peer: &PeerId,
        workspace: &WorkspaceId,
        repository: &RepositoryId,
        path: &str,
        keep: &str,
        when: u64,
    ) -> Result<(), String> {
        if keep != "here" && keep != "there" {
            return Err(format!("'{keep}' is not a side to keep"));
        }
        self.with(|c| {
            c.execute(
                "INSERT OR REPLACE INTO resolutions
                 (peer_id, workspace_id, repository, path, keep, decided_at)
                 VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
                params![
                    peer.as_str(),
                    workspace.as_str(),
                    repository.as_str(),
                    path,
                    keep,
                    when as i64
                ],
            )?;
            Ok(())
        })
    }

    /// The decisions waiting to be carried for one repository.
    pub fn resolutions(
        &self,
        peer: &PeerId,
        workspace: &WorkspaceId,
        repository: &RepositoryId,
    ) -> Result<BTreeMap<String, String>, String> {
        self.with(|c| {
            let mut statement = c.prepare(
                "SELECT path, keep FROM resolutions
                 WHERE peer_id = ?1 AND workspace_id = ?2 AND repository = ?3",
            )?;
            let rows = statement.query_map(
                params![peer.as_str(), workspace.as_str(), repository.as_str()],
                |row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)),
            )?;
            let mut out = BTreeMap::new();
            for row in rows {
                let (path, keep) = row?;
                out.insert(path, keep);
            }
            Ok(out)
        })
    }

    pub fn clear_resolution(
        &self,
        peer: &PeerId,
        workspace: &WorkspaceId,
        repository: &RepositoryId,
        path: &str,
    ) -> Result<(), String> {
        self.with(|c| {
            c.execute(
                "DELETE FROM resolutions
                 WHERE peer_id = ?1 AND workspace_id = ?2 AND repository = ?3 AND path = ?4",
                params![peer.as_str(), workspace.as_str(), repository.as_str(), path],
            )?;
            Ok(())
        })
    }

    // ── dismissals ─────────────────────────────────────────────────────────

    /// Leave one difference alone, as it stands right now.
    pub fn dismiss(
        &self,
        peer: &PeerId,
        workspace: &WorkspaceId,
        repository: &RepositoryId,
        path: &str,
        here_hash: Option<&str>,
        there_hash: Option<&str>,
        when: u64,
    ) -> Result<(), String> {
        self.with(|c| {
            c.execute(
                "INSERT OR REPLACE INTO dismissals
                 (peer_id, workspace_id, repository, path, here_hash, there_hash, dismissed_at)
                 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
                params![
                    peer.as_str(),
                    workspace.as_str(),
                    repository.as_str(),
                    path,
                    here_hash,
                    there_hash,
                    when as i64
                ],
            )?;
            Ok(())
        })
    }

    /// The dismissals for one repository, by path, with the two hashes each
    /// was made at.
    pub fn dismissals(
        &self,
        peer: &PeerId,
        workspace: &WorkspaceId,
        repository: &RepositoryId,
    ) -> Result<BTreeMap<String, (Option<String>, Option<String>)>, String> {
        self.with(|c| {
            let mut statement = c.prepare(
                "SELECT path, here_hash, there_hash FROM dismissals
                 WHERE peer_id = ?1 AND workspace_id = ?2 AND repository = ?3",
            )?;
            let rows = statement.query_map(
                params![peer.as_str(), workspace.as_str(), repository.as_str()],
                |row| {
                    Ok((
                        row.get::<_, String>(0)?,
                        row.get::<_, Option<String>>(1)?,
                        row.get::<_, Option<String>>(2)?,
                    ))
                },
            )?;
            let mut out = BTreeMap::new();
            for row in rows {
                let (path, here, there) = row?;
                out.insert(path, (here, there));
            }
            Ok(out)
        })
    }

    pub fn clear_dismissal(
        &self,
        peer: &PeerId,
        workspace: &WorkspaceId,
        repository: &RepositoryId,
        path: &str,
    ) -> Result<(), String> {
        self.with(|c| {
            c.execute(
                "DELETE FROM dismissals
                 WHERE peer_id = ?1 AND workspace_id = ?2 AND repository = ?3 AND path = ?4",
                params![peer.as_str(), workspace.as_str(), repository.as_str(), path],
            )?;
            Ok(())
        })
    }

    // ── worktrees ──────────────────────────────────────────────────────────

    pub fn register_worktree(
        &self,
        worktree: &wsb::daemon::RegisteredWorktree,
    ) -> Result<(), String> {
        self.with(|c| {
            c.execute(
                "INSERT INTO worktrees
                     (worktree_id, project, name, workspace_id, super_root, root_commit, last_seen)
                 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)
                 ON CONFLICT(worktree_id) DO UPDATE SET
                     project = excluded.project,
                     name = excluded.name,
                     workspace_id = excluded.workspace_id,
                     super_root = excluded.super_root,
                     root_commit = excluded.root_commit,
                     last_seen = excluded.last_seen",
                params![
                    worktree.id.as_str(),
                    worktree.project,
                    worktree.name,
                    worktree.workspace.as_ref().map(WorkspaceId::as_str),
                    worktree.super_root.display().to_string(),
                    worktree.root_commit,
                    worktree.last_seen as i64,
                ],
            )?;
            Ok(())
        })
    }

    /// Drop a worktree record.
    ///
    /// Used to correct a record that should never have been written — see
    /// `MachineState::forget_contained_worktrees`.
    pub fn forget_worktree(&self, worktree: &wsb::daemon::WorktreeId) -> Result<(), String> {
        self.with(|c| {
            c.execute(
                "DELETE FROM worktrees WHERE worktree_id = ?1",
                params![worktree.as_str()],
            )?;
            Ok(())
        })
    }

    /// Every worktree this machine has opened.
    ///
    /// A row that does not read is an error naming it, not a row skipped:
    /// every column is written from a parsed value, so one that does not
    /// parse was edited by hand, and a list quietly missing a worktree is
    /// the harder thing to explain.
    pub fn worktrees(&self) -> Result<Vec<wsb::daemon::RegisteredWorktree>, String> {
        let rows = self.with(|c| {
            let mut statement = c.prepare(
                "SELECT worktree_id, project, name, workspace_id, super_root, root_commit, last_seen
                 FROM worktrees ORDER BY project, name, worktree_id",
            )?;
            let rows = statement.query_map([], |row| {
                Ok((
                    row.get::<_, String>(0)?,
                    row.get::<_, Option<String>>(1)?,
                    row.get::<_, String>(2)?,
                    row.get::<_, Option<String>>(3)?,
                    row.get::<_, String>(4)?,
                    row.get::<_, Option<String>>(5)?,
                    row.get::<_, i64>(6)? as u64,
                ))
            })?;
            rows.collect::<Result<Vec<_>, _>>()
        })?;
        rows.into_iter()
            .map(|(id, project, name, workspace, super_root, root_commit, last_seen)| {
                let id = wsb::daemon::WorktreeId::parse(&id)
                    .map_err(|e| format!("machine database, worktrees: {e}"))?;
                let workspace = workspace
                    .map(|raw| WorkspaceId::parse(&raw))
                    .transpose()
                    .map_err(|e| format!("machine database, worktree {id}: {e}"))?;
                let super_root = std::path::PathBuf::from(super_root);
                Ok(wsb::daemon::RegisteredWorktree {
                    id,
                    project,
                    name,
                    workspace,
                    available: super_root.is_dir(),
                    super_root,
                    root_commit,
                    last_seen,
                })
            })
            .collect()
    }
}

/// How many conflicts are waiting in one repository, with one peer.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConflictCount {
    pub workspace: String,
    /// Workspace-relative; the superproject is the empty string.
    pub repository: String,
    pub peer: String,
    pub conflicts: usize,
}

/// One unresolved conflict, as stored.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ConflictRow {
    pub repository: String,
    pub path: String,
    pub here_hash: Option<String>,
    pub there_hash: Option<String>,
    pub base_hash: Option<String>,
    pub detected_at: u64,
}

fn row_to_peer(row: &rusqlite::Row<'_>) -> Result<PairedPeer, rusqlite::Error> {
    let id: String = row.get(0)?;
    Ok(PairedPeer {
        // A row whose id does not parse cannot be turned into a peer, and a
        // peer with an invented id would be a peer nothing can reach. The
        // column is written only from a parsed id, so this is unreachable
        // without hand-editing the database.
        id: PeerId::parse(&id).map_err(|e| {
            rusqlite::Error::FromSqlConversionFailure(0, rusqlite::types::Type::Text, e.into())
        })?,
        name: row.get(1)?,
        public_key: row.get(2)?,
        fingerprint: Fingerprint::from_stored(row.get::<_, String>(3)?),
        address: row.get(4)?,
        paired_at: row.get::<_, i64>(5)? as u64,
    })
}

#[cfg(test)]
#[path = "store_tests.rs"]
mod tests;