wsb 0.275.7622

Workspace tools for every project under $PRJ: git across submodules, template stamping, GitHub, and the workbench
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
//! The vocabulary of worktree continuity: what a peer is, what a worktree
//! relationship is, and every state either can be in.
//!
//! Closed enums, not strings. A UI that has to parse an error message to know
//! whether it may offer a "Sync" button is a UI that will offer one when it
//! must not, and a state nobody enumerated is a state nobody handled. Every
//! state here is one the coordinator can produce and every surface can render.
//!
//! # Two axes, deliberately separate
//!
//! [`Desired`] is what the operator asked for. [`Observed`] is what is true
//! right now. Collapsing them loses the case this feature exists for: a
//! continuity relationship that is enabled but temporarily blocked by a branch
//! change must resume by itself when the branch comes back, and one the
//! operator paused must not.

use serde::{Deserialize, Serialize};

/// A machine's stable identity, as everyone refers to it.
///
/// The base32 of the ed25519 public key's SHA-256, truncated — long enough
/// that a collision is not a thing that happens, short enough to read out over
/// a phone. Never a hostname: hostnames repeat, change and lie.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct PeerId(String);

impl PeerId {
    /// Wrap a value that came from [`crate::peer::identity`], which is the only
    /// thing that derives one.
    pub(crate) fn from_derived(value: String) -> Self {
        Self(value)
    }

    /// Parse one that came back over the wire or out of the database.
    ///
    /// Checked rather than trusted: this value keys trust relationships and
    /// appears in file paths under the staging directory, and a peer id
    /// carrying a `/` would be a peer id that escapes it.
    pub fn parse(raw: &str) -> Result<Self, String> {
        if raw.is_empty() {
            return Err("a peer id is not empty".to_string());
        }
        if raw.len() > 64 {
            return Err(format!("a peer id is at most 64 characters, this is {}", raw.len()));
        }
        if !raw.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit()) {
            return Err(format!(
                "'{raw}' is not a peer id: they are lowercase letters and digits"
            ));
        }
        Ok(Self(raw.to_string()))
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl std::fmt::Display for PeerId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

/// What two machines call one worktree: the repository's family and the
/// worktree's name, `<family>@<name>`.
///
/// The family is the superproject's root commit, hashed, so two clones of one
/// repository share it on machines that have never spoken. The name is the
/// worktree's — `main`, `fix`, or a checkout's folder outside `$PRJ` — so a
/// machine's `main` is carried with the other machine's `main`, and its `fix`
/// worktree with the other's `fix`, never across. Where a worktree sits on
/// either machine is local presentation; matching paths across peers is the
/// mistake this type exists to make unrepresentable.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(try_from = "String", into = "String")]
pub struct SharedWorktreeId(String);

impl SharedWorktreeId {
    /// A family and a worktree name, together.
    pub fn of(family: &str, worktree: &str) -> Result<Self, String> {
        Self::parse(&format!("{family}@{worktree}"))
    }

    pub fn parse(raw: &str) -> Result<Self, String> {
        let Some((family, worktree)) = raw.split_once('@') else {
            return Err(format!(
                "'{raw}' is not a worktree id: <family>@<worktree>"
            ));
        };
        if family.is_empty()
            || family.len() > 64
            || !family.chars().all(|c| c.is_ascii_digit() || ('a'..='f').contains(&c))
        {
            return Err(format!(
                "'{family}' is not a repository family: up to 64 lowercase hex digits"
            ));
        }
        if !is_worktree_name(worktree) {
            return Err(format!(
                "'{worktree}' cannot name a worktree two machines share: letters, digits, \
                 '.', '_' and '-', starting with a letter or digit"
            ));
        }
        Ok(Self(raw.to_string()))
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// The repository family, shared by every worktree of the repository.
    pub fn family(&self) -> &str {
        self.0.split_once('@').map(|(family, _)| family).unwrap_or(&self.0)
    }

    /// The worktree's name.
    pub fn worktree(&self) -> &str {
        self.0.split_once('@').map(|(_, worktree)| worktree).unwrap_or_default()
    }
}

impl TryFrom<String> for SharedWorktreeId {
    type Error = String;
    fn try_from(raw: String) -> Result<Self, String> {
        Self::parse(&raw)
    }
}

impl From<SharedWorktreeId> for String {
    fn from(id: SharedWorktreeId) -> String {
        id.0
    }
}

/// The names `prj` gives worktrees, which are the names two machines can
/// agree on. The same rule as `prj`'s, stated here because a peer's request is
/// validated before anything else about it is read.
fn is_worktree_name(name: &str) -> bool {
    let mut chars = name.chars();
    matches!(chars.next(), Some(first) if first.is_ascii_alphanumeric())
        && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
}

impl std::fmt::Display for SharedWorktreeId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

/// One repository inside a worktree, named by its path relative to the
/// worktree root.
///
/// The superproject is the empty string, exactly as the fleet's own repository
/// listing names it. A relative path is a stable identity across machines in a
/// way an absolute one is not — and unlike a remote URL it exists even for a
/// repository that has no remote.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct RepositoryId(String);

impl RepositoryId {
    /// The superproject.
    pub fn root() -> Self {
        Self(String::new())
    }

    pub fn parse(raw: &str) -> Result<Self, String> {
        if raw.len() > 512 {
            return Err("a repository path is at most 512 characters".to_string());
        }
        if raw.starts_with('/') || raw.contains("..") || raw.contains('\\') {
            return Err(format!(
                "'{raw}' is not a repository path relative to the worktree root"
            ));
        }
        Ok(Self(raw.to_string()))
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }

    pub fn is_root(&self) -> bool {
        self.0.is_empty()
    }

    /// How it reads in a report: the superproject has a name rather than an
    /// empty column.
    pub fn label(&self) -> &str {
        if self.0.is_empty() {
            "superproject"
        } else {
            &self.0
        }
    }
}

impl std::fmt::Display for RepositoryId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.label())
    }
}

/// Where a peer relationship stands.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PeerState {
    /// Known of, but no trust relationship: nothing may be exchanged.
    Unpaired,
    Offline,
    Connecting,
    Connected,
    /// The last attempt failed for a reason that is not "it is not there".
    Error,
}

impl PeerState {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Unpaired => "unpaired",
            Self::Offline => "offline",
            Self::Connecting => "connecting",
            Self::Connected => "connected",
            Self::Error => "error",
        }
    }
}

/// Whether both machines have a given worktree.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum WorktreePresence {
    /// Here, and not on the peer.
    LocalOnly,
    /// On the peer, and not here.
    PeerOnly,
    Shared,
}

impl WorktreePresence {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::LocalOnly => "local_only",
            Self::PeerOnly => "peer_only",
            Self::Shared => "shared",
        }
    }
}

/// One of the things two paired machines do for each other.
///
/// Each is switched on its own, per peer, so a service added later does not
/// ride on the switch of one that was already there. A plugin's services are
/// services like any other here, each with its own switch: wsb carries them,
/// and whether it carries one with a given machine is a decision made for
/// that service alone.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(try_from = "String", into = "String")]
pub enum Service {
    /// Carrying the working tree: scans, comparisons, transfers, conflicts.
    Files,
    /// A service a plugin offers, `<plugin>.<service>`, carried over the
    /// peer bridge for that plugin's copy on the other machine.
    Plugin(crate::plugin::PluginService),
}

impl Service {
    /// The services wsb itself provides. Surfaces iterate this rather than
    /// listing names, so a service added here appears everywhere at once;
    /// plugin services are added to these from what is registered and
    /// switched.
    pub const BUILT_IN: [Service; 1] = [Service::Files];

    pub fn as_str(&self) -> &str {
        match self {
            Self::Files => "files",
            Self::Plugin(service) => service.as_str(),
        }
    }

    /// A service by name: `files`, or a plugin's `<plugin>.<service>`.
    pub fn parse(raw: &str) -> Result<Self, String> {
        match raw {
            "files" => Ok(Self::Files),
            other if other.contains('.') => {
                Ok(Self::Plugin(crate::plugin::PluginService::parse(other)?))
            }
            other => Err(format!(
                "'{other}' is not a service: files, or a plugin's <plugin>.<service>"
            )),
        }
    }

    /// What this service does, in the words a person would use.
    pub fn describe(&self) -> String {
        match self {
            Self::Files => "carry this machine's working tree with that machine".to_string(),
            Self::Plugin(service) => format!(
                "let the {} plugin answer that machine's {} requests",
                service.plugin(),
                service
            ),
        }
    }
}

impl TryFrom<String> for Service {
    type Error = String;
    fn try_from(raw: String) -> Result<Self, String> {
        Self::parse(&raw)
    }
}

impl From<Service> for String {
    fn from(service: Service) -> String {
        service.as_str().to_string()
    }
}

impl std::fmt::Display for Service {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// One service and its switch with one peer.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ServiceSwitch {
    /// The service's name: wsb's own, or `<plugin>.<service>`.
    pub service: String,
    pub switch: Switch,
    /// What it does, in a sentence.
    pub describes: String,
}

/// What the daemon answers [`super::route::services`] with: every service
/// there is with that peer, the ones that are on included.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PeerServices {
    pub peer: String,
    pub services: Vec<ServiceSwitch>,
}

/// Whether a service runs with a peer at all.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Switch {
    On,
    Off,
}

impl Switch {
    /// What a service does until somebody says otherwise.
    ///
    /// Files are on: a machine somebody paired is a machine they meant to work
    /// with, and the thing that is off by default is not the SERVICE but the
    /// carrying of files without being asked — see [`SyncMode`].
    ///
    /// A plugin's service is off. Pairing two machines was a decision about
    /// working trees; what a plugin answers — a secret, say — was not part of
    /// it, and is switched on for each machine by somebody who means it.
    pub fn default_for(service: &Service) -> Self {
        match service {
            Service::Files => Self::On,
            Service::Plugin(_) => Self::Off,
        }
    }

    pub fn as_str(self) -> &'static str {
        match self {
            Self::On => "on",
            Self::Off => "off",
        }
    }

    pub fn parse(raw: &str) -> Result<Self, String> {
        match raw {
            "on" => Ok(Self::On),
            "off" => Ok(Self::Off),
            other => Err(format!("'{other}' is not a switch: on, off")),
        }
    }

    pub fn is_on(self) -> bool {
        matches!(self, Self::On)
    }
}

/// How a worktree's files move INTO this machine from one peer, once both
/// sides are comparable.
///
/// The distinction this exists for: comparing is safe and moving is not
/// always. Two machines can agree on what differs without either one deciding
/// that the difference should be resolved in a particular direction, and for
/// most of a working day that is exactly what somebody wants to see — a list,
/// not an action.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SyncMode {
    /// Differences are found and listed. Nothing crosses until a person says
    /// so, path by path — in either direction. The default, because a machine
    /// that starts moving files the moment it is paired is one nobody can
    /// reason about.
    Manual,
    /// Changes ARRIVING from that machine are applied here by themselves.
    /// Conflicts still wait for a person — that has never been automatic and
    /// is not now.
    ///
    /// One direction. This is a statement about this machine's own working
    /// tree, not about the peer's: whether the peer applies THIS machine's
    /// changes is the peer's own setting, so the two may differ and changes
    /// can travel automatically one way only.
    Auto,
}

impl SyncMode {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Manual => "manual",
            Self::Auto => "auto",
        }
    }

    pub fn parse(raw: &str) -> Result<Self, String> {
        match raw {
            "manual" => Ok(Self::Manual),
            "auto" => Ok(Self::Auto),
            other => Err(format!("'{other}' is not a sync mode: manual, auto")),
        }
    }
}

impl Default for SyncMode {
    fn default() -> Self {
        Self::Manual
    }
}

/// What continuity actually does for one worktree with one peer, right now.
///
/// Three inputs decide it and they are at different granularities: the
/// machine-wide switch for the files service, whether this worktree is
/// carried with this peer at all, and how it is carried. This enum is the
/// answer, computed once by [`Continuity::of`] so that no surface has to
/// re-derive it and none of them can disagree.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Continuity {
    /// Nothing is compared and nothing moves. The two machines do not even
    /// exchange a report — which is what makes this a real pause rather than
    /// a quiet one, and what leaves the peer free to answer for a secret.
    Off,
    /// Compared and listed; nothing moves, and no decision moves it either.
    /// The operator's own pause, kept distinct from [`Continuity::Manual`]
    /// because resuming from it must not act on a decision made before it.
    Paused,
    /// Compared and listed. What crosses is what somebody chose, path by path.
    Manual,
    /// Compared, and everything that is not a conflict crosses by itself.
    Auto,
}

impl Continuity {
    /// The one place the three switches are combined.
    pub fn of(files: Switch, desired: Desired, mode: SyncMode) -> Self {
        match (files, desired) {
            // The service switch wins over everything: off is off, whatever a
            // worktree's own relationship says.
            (Switch::Off, _) => Self::Off,
            (_, Desired::Disabled) => Self::Off,
            (_, Desired::Paused) => Self::Paused,
            (_, Desired::Enabled) => match mode {
                SyncMode::Manual => Self::Manual,
                SyncMode::Auto => Self::Auto,
            },
        }
    }

    /// Whether the two machines exchange reports at all.
    ///
    /// Everything but `Off` compares: a paused or manual relationship is one
    /// somebody wants to SEE, and seeing costs a report.
    pub fn compares(self) -> bool {
        !matches!(self, Self::Off)
    }

    /// Whether a difference nobody decided about may be TAKEN onto this
    /// machine.
    ///
    /// One direction, deliberately. `auto` is a statement a machine makes
    /// about its own working tree — "what arrives here is applied without
    /// asking me" — and never about the peer's. Whether this machine's changes
    /// are applied THERE is the peer's decision, made by the peer's own pass
    /// with the peer's own mode; two machines can therefore differ, and
    /// changes travel automatically in one direction only.
    ///
    /// It used to gate both directions from one side, so a machine set to
    /// `auto` pushed undecided changes onto a peer that had deliberately
    /// stayed manual — the one thing manual exists to prevent.
    pub fn takes_undecided(self) -> bool {
        matches!(self, Self::Auto)
    }

    /// Whether a difference somebody decided about may cross.
    ///
    /// Not while paused: a decision taken before a pause is not consent to act
    /// during it, and the decision keeps until the pause ends.
    pub fn carries_decided(self) -> bool {
        matches!(self, Self::Manual | Self::Auto)
    }

    pub fn as_str(self) -> &'static str {
        match self {
            Self::Off => "off",
            Self::Paused => "paused",
            Self::Manual => "manual",
            Self::Auto => "auto",
        }
    }
}

/// What the operator asked for. Changed only by an explicit action.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Desired {
    /// Never enabled, or explicitly disabled.
    Disabled,
    Enabled,
    /// Enabled once, and paused by hand. Distinct from disabled: the
    /// relationship and its baselines are kept, and `resume` is the one thing
    /// that starts it again — compatibility returning is not.
    Paused,
}

impl Desired {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Disabled => "disabled",
            Self::Enabled => "enabled",
            Self::Paused => "paused",
        }
    }
}

/// What is true right now for one repository of one relationship.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Observed {
    /// Continuity is not enabled here.
    Idle,
    /// Compatibility is being recalculated. Every path out of an unstable git
    /// state passes through this rather than guessing.
    Checking,
    /// Compatible and quiet, but the baseline has not been verified this
    /// session yet.
    Ready,
    Syncing,
    /// Verified: both sides hold the same tree against the same baseline.
    Synced,
    /// The operator's own pause.
    Paused,
    /// Differences are known, listed, and waiting for somebody to say what
    /// should happen to them. Manual mode's ordinary resting state — and not
    /// an error: a machine with sixteen undecided differences is working
    /// exactly as asked.
    Undecided,
    /// Something makes synchronisation unsafe. Always carries a [`Blocked`].
    Blocked,
    /// A path changed on both sides from the same base, differently.
    Conflict,
    Error,
}

impl Observed {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Idle => "idle",
            Self::Checking => "checking",
            Self::Ready => "ready",
            Self::Syncing => "syncing",
            Self::Synced => "synced",
            Self::Paused => "paused",
            Self::Undecided => "undecided",
            Self::Blocked => "blocked",
            Self::Conflict => "conflict",
            Self::Error => "error",
        }
    }
}

/// Why a repository is blocked, as data.
///
/// Every one of these is a state the coordinator computes; none is a message
/// somebody wrote. The UI decides what to say and what to offer from the
/// variant, never from prose.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "reason", rename_all = "snake_case")]
pub enum Blocked {
    /// The two sides are not the same repository (different remote identity,
    /// or an unrelated history).
    RepositoryMismatch { here: String, there: String },
    BranchMismatch { here: String, there: String },
    /// Either side is on no named branch. Two detached heads at the same
    /// commit are NOT a branch: nothing says the next commit lands anywhere
    /// the other side can follow.
    DetachedHead { here: bool, there: bool },
    HeadMismatch { here: String, there: String },
    /// A git operation is in progress on one side — a checkout, merge, rebase,
    /// cherry-pick, bisect, or a moving index.
    GitOperation { here: bool, there: bool },
    /// The peer does not have this worktree at all.
    WorktreeMissing,
    /// The peer does not have this repository, or has not initialised it.
    SubmoduleMissing { here: bool, there: bool },
    PeerOffline,
    /// The two sides disagree about what may be synchronised — one declares an
    /// include or exclude the other does not.
    PolicyMismatch { detail: String },
}

impl Blocked {
    /// The stable word for this reason, for records and tests.
    pub fn code(&self) -> &'static str {
        match self {
            Self::RepositoryMismatch { .. } => "repository_mismatch",
            Self::BranchMismatch { .. } => "branch_mismatch",
            Self::DetachedHead { .. } => "detached_head",
            Self::HeadMismatch { .. } => "head_mismatch",
            Self::GitOperation { .. } => "git_operation",
            Self::WorktreeMissing => "worktree_missing",
            Self::SubmoduleMissing { .. } => "submodule_missing",
            Self::PeerOffline => "peer_offline",
            Self::PolicyMismatch { .. } => "policy_mismatch",
        }
    }

    /// One line a person reads. Derived from the variant, so the words and the
    /// state cannot drift apart.
    pub fn describe(&self) -> String {
        match self {
            Self::RepositoryMismatch { here, there } => format!(
                "these are not the same repository — here {here}, on the peer {there}"
            ),
            Self::BranchMismatch { here, there } => {
                format!("branch mismatch — here {here}, on the peer {there}")
            }
            Self::DetachedHead { here, there } => match (here, there) {
                (true, true) => "both sides are on a detached HEAD".to_string(),
                (true, false) => "this side is on a detached HEAD".to_string(),
                (false, true) => "the peer is on a detached HEAD".to_string(),
                // Not producible: the variant is only built when one is true.
                (false, false) => "a detached HEAD was reported with neither side detached"
                    .to_string(),
            },
            Self::HeadMismatch { here, there } => format!(
                "HEAD mismatch — here {}, on the peer {}",
                short_commit(here),
                short_commit(there)
            ),
            Self::GitOperation { here, there } => match (here, there) {
                (true, true) => "a git operation is in progress on both sides".to_string(),
                (true, false) => "a git operation is in progress here".to_string(),
                (false, true) => "a git operation is in progress on the peer".to_string(),
                (false, false) => "a git operation was reported with neither side busy".to_string(),
            },
            Self::WorktreeMissing => "the peer does not have this worktree".to_string(),
            Self::SubmoduleMissing { here, there } => match (here, there) {
                (false, true) => "this side does not have this repository".to_string(),
                (true, false) => "the peer does not have this repository".to_string(),
                _ => "this repository is missing on both sides".to_string(),
            },
            Self::PeerOffline => "the peer is not connected".to_string(),
            Self::PolicyMismatch { detail } => {
                format!("the two sides declare different continuity policy: {detail}")
            }
        }
    }
}

/// The first characters of a commit, for a message. Never used to compare.
pub(crate) fn short_commit(id: &str) -> String {
    id.chars().take(7).collect()
}

/// What a relationship is doing, in full: what was asked for, what is true,
/// and — when it is blocked — why.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RepositoryStatus {
    pub repository: RepositoryId,
    pub desired: Desired,
    /// What the three switches come to for this repository's worktree. The
    /// surfaces read this rather than recombining `desired` with a service
    /// switch they would have to fetch separately.
    pub continuity: Continuity,
    pub observed: Observed,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub blocked: Option<Blocked>,
    /// Paths waiting to move, either way.
    pub pending: usize,
    /// Of the pending paths, how many would come ONTO this machine.
    ///
    /// Split from `outgoing` because the two are different facts about
    /// different machines and a person acts on them differently: what is
    /// coming here is this machine's to take, and what would leave is the
    /// peer's to accept. A single "pending" number could not say which, so
    /// every surface that wanted to had to fetch the deltas and count them.
    pub incoming: usize,
    /// Of the pending paths, how many would go TO the peer.
    pub outgoing: usize,
    /// Paths in conflict.
    pub conflicts: usize,
    /// Of the pending paths, how many nobody has decided about and this
    /// machine will not move by itself.
    ///
    /// In `manual` that is all of them. In `auto` the incoming ones have
    /// already been applied, so what is left is the outgoing ones — which this
    /// machine never pushes unasked, whatever its mode.
    pub undecided: usize,
    /// The branch both sides are on, when they agree on one.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub branch: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub head: Option<String>,
}

impl RepositoryStatus {
    /// The invariant every producer of this type must hold: `Blocked` carries
    /// a reason, and nothing else does.
    ///
    /// Checked here rather than trusted at each construction site, because
    /// "blocked with no reason" is exactly the state a UI cannot render and a
    /// person cannot act on.
    pub fn check(&self) -> Result<(), String> {
        match (self.observed, &self.blocked) {
            (Observed::Blocked, None) => Err(format!(
                "{} is blocked with no reason",
                self.repository.label()
            )),
            (state, Some(reason)) if state != Observed::Blocked => Err(format!(
                "{} is {} and carries the blocked reason {}",
                self.repository.label(),
                state.as_str(),
                reason.code()
            )),
            _ => Ok(()),
        }
    }
}

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