pitboard-core 0.14.0

The engine behind Pitboard: switches Claude Code, Codex and Claude Desktop between accounts by parking and restoring their logins. Its API serves Pitboard's own front ends.
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
//! Finishing what an interrupted run started.
//!
//! A switch writes this record before creating the park item it names. Whether an install
//! landed is decided by asking Anthropic who owns the live credential, an answer that
//! survives Claude Code rotating the token. When any fact cannot be read, recovery changes
//! nothing and keeps the record.

use super::{Error, Result, identify_document};
use crate::context::Context;
use crate::in_use::{self, InUse};
use crate::provider::{self, LoginKind, Provider, ProviderId};
use crate::service::Permit;
use crate::state::{Account, Key, Park, ParkKind, State};
use crate::{atomic, home, park, state, store};
use serde_json::Value;
use std::path::PathBuf;

#[derive(serde::Serialize, serde::Deserialize)]
pub(super) struct Journal {
    /// Which tool's login moved. Both sides of a switch are always the same tool's: a
    /// switch replaces one tool's live login with another account of that same tool.
    ///
    /// Absent from a record written before there was a second tool, and every one of those
    /// was Claude Code's.
    #[serde(default = "claude")]
    pub(super) provider: ProviderId,
    pub(super) started_at: i64,
    pub(super) from_label: String,
    /// The accounts' ids, under the names a record has always given them.
    #[serde(rename = "from_uuid")]
    pub(super) from_id: String,
    pub(super) to_label: String,
    #[serde(rename = "to_uuid")]
    pub(super) to_id: String,
    pub(super) park_service: String,
    /// The park being installed, so recovery consumes exactly that copy.
    pub(super) incoming_service: String,
    /// The refresh tokens on each side, as fingerprints. Eight bytes of SHA-256, which is
    /// what `Park` already records, and no more a secret there than here.
    ///
    /// These let recovery answer the question it usually needs Anthropic for. Empty on a
    /// record written before they existed, which is a record that simply asks.
    #[serde(default)]
    pub(super) from_fingerprint: String,
    #[serde(default)]
    pub(super) to_fingerprint: String,
    /// Where the tool's live login was when the switch started, as the tool names it.
    ///
    /// Which login is live depends on a home variable, and recovery judges an interrupted
    /// switch by reading the live login. Read from another place, it would compare the
    /// switch's two sides with a login that has nothing to do with them, and could decide
    /// the switch landed when it never did. `None` on a record written before this was kept.
    #[serde(default)]
    pub(super) slot: Option<String>,
}

/// What a later run found an interrupted switch had done, now recorded in the state.
#[derive(Debug)]
pub struct Recovered {
    pub from: String,
    pub to: String,
    pub finished: bool,
}

impl Recovered {
    pub fn code(&self) -> &'static str {
        if self.finished {
            "interrupted_switch_finished"
        } else {
            "interrupted_switch_undone"
        }
    }
}

impl std::fmt::Display for Recovered {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "an earlier switch from `{}` to `{}` was interrupted; {}",
            self.from,
            self.to,
            if self.finished {
                "it had in fact finished, and Pitboard has recorded that"
            } else {
                "it had not finished, and nothing was lost"
            }
        )
    }
}

fn claude() -> ProviderId {
    ProviderId::Claude
}

impl Journal {
    fn from(&self) -> Key {
        Key::new(self.provider, self.from_label.clone())
    }

    fn to(&self) -> Key {
        Key::new(self.provider, self.to_label.clone())
    }
}

fn journal_path(ctx: &Context) -> PathBuf {
    home::dir(ctx).join("journal.json")
}

/// Durable before the park it names is created: a record lost to a crash would leave a
/// consumed login looking restorable.
pub(super) fn write_journal(ctx: &Context, permit: Permit, entry: &Journal) -> Result<()> {
    let path = journal_path(ctx);
    let fail = |source| Error::RecoveryFailed {
        path: path.clone(),
        source,
    };
    home::ensure(ctx, permit).map_err(fail)?;
    let body = serde_json::to_string(entry).expect("a journal entry is always serialisable");
    atomic::write(permit, &path, body.as_bytes(), atomic::Perms::Secret).map_err(fail)
}

/// A switch was interrupted, and the next command that changes state will finish it.
pub(crate) fn pending(ctx: &Context) -> bool {
    journal_path(ctx).exists()
}

/// Which tool's switch was interrupted, where one was and its record can be read.
pub(crate) fn interrupted_tool(ctx: &Context) -> Option<ProviderId> {
    let raw = std::fs::read_to_string(journal_path(ctx)).ok()?;
    serde_json::from_str::<Journal>(&raw)
        .ok()
        .map(|journal| journal.provider)
}

/// The switch reached a state the account index fully describes.
pub(super) fn clear_journal(ctx: &Context, permit: Permit) {
    let _ = crate::host::fs::remove_file(permit, &journal_path(ctx));
}

struct Found {
    /// The park the record reserved: written, never written, or `None` if unreadable.
    parked: Option<Option<Value>>,
    /// The id of the account the live login belongs to, or `None` if that cannot be learned.
    live_owner: Option<String>,
}

#[derive(Default, Debug, PartialEq)]
struct Repair {
    /// Hold the interrupted run's park for the account it came from. Keyed by account id,
    /// not label: the label may have been reused since.
    hold: Option<(String, Park)>,
    /// The interrupted run's park copies a login that is still signed in, so Claude Code
    /// will rotate past it.
    drop: bool,
    /// The destination's login is live: it is in use, and its park was consumed.
    landed: bool,
}

/// What recovery read of the tool's own record and of its store, which is what a switch
/// that landed leaves recorded as in use.
struct Seen {
    /// What the tool's own record named, read before its store.
    named: Option<String>,
    /// The fingerprint of the login the store held: the one installed, or what Claude Code
    /// rotated it to since. Empty where the store could not be read.
    login: String,
}

/// `None` when the facts do not settle what happened.
fn repair_for(
    state: &State,
    tool: &'static dyn Provider,
    journal: &Journal,
    found: &Found,
) -> Option<Repair> {
    let parked = found.parked.as_ref()?;
    let owner = found.live_owner.as_deref()?;
    let mut repair = Repair {
        landed: owner == journal.to_id,
        ..Repair::default()
    };
    if owner == journal.from_id {
        repair.drop = parked.is_some();
    } else if let Some(oauth) = parked
        && !state.references(&journal.park_service)
    {
        repair.hold = Some((
            journal.from_id.clone(),
            park::describe(tool, &journal.park_service, journal.started_at, oauth),
        ));
    }
    Some(repair)
}

/// A switch that landed leaves the login recovery `seen` in the store recorded as the
/// destination's, at `at`.
fn apply(state: &mut State, journal: &Journal, repair: Repair, seen: Seen, at: i64) {
    if repair.drop {
        state.discard(&journal.park_service, ParkKind::Vault);
    }
    if let Some((id, park)) = repair.hold {
        match state.by_id(journal.provider, &id).map(Account::key) {
            Some(key) => state.park(&key, park),
            // The account it belongs to is gone, so nothing will ever restore this copy.
            // Listing it is what gets it deleted rather than left in the keychain.
            None => state.release(&park.service),
        }
    }
    if !repair.landed {
        return;
    }
    match state
        .by_id(journal.provider, &journal.to_id)
        .map(Account::owner)
    {
        Some(owner) => {
            let installed = InUse {
                owner: Some(owner),
                login: seen.login,
                known_at: at,
                named: seen.named,
            };
            state.identified(journal.provider, installed, at);
            state.discard(&journal.incoming_service, ParkKind::Vault);
        }
        // The destination was forgotten since, whichever account holds its label now, and an
        // id alone does not say whose its login is as the service names one. What the record
        // said before the switch is past.
        None => {
            state.in_use.remove(journal.provider.code());
        }
    }
}

fn read_park(ctx: &Context, service: &str) -> Option<Option<Value>> {
    match store::vault_read(ctx, service) {
        Ok(raw) => Some(raw.and_then(|r| serde_json::from_str(&r).ok())),
        Err(_) => None,
    }
}

/// Whose the live login is, as far as the record and the login itself can say.
enum Owner {
    /// The account's under this id.
    Is(String),
    /// Nobody can say, for this reason.
    Unknown(String),
    /// The record cannot say whose this login is, and the service has not been asked.
    Unasked(Value),
}

/// Whose the live login is, read off the record and the login without asking anybody, and
/// that login's fingerprint, empty where it could not be read.
///
/// The fingerprints settle it without a round trip whenever they can, which is what makes
/// an interrupted switch recoverable with no network at all.
fn live_owner(ctx: &Context, tool: &'static dyn Provider, journal: &Journal) -> (Owner, String) {
    match tool.read_live(ctx) {
        Err(e) => (Owner::Unknown(e.to_string()), String::new()),
        Ok(None) => (Owner::Unknown("nothing is signed in".into()), String::new()),
        Ok(Some(live)) => {
            let login = tool.fingerprint(&live.raw);
            let owner = match live_owner_by_fingerprint(journal, &login) {
                Some(id) => Owner::Is(id),
                None => Owner::Unasked(live.raw),
            };
            (owner, login)
        }
    }
}

/// The id of the account whose the live login is, with the service asked where only it
/// can say.
fn ask(
    ctx: &Context,
    state: &State,
    tool: &'static dyn Provider,
    owner: Owner,
) -> std::result::Result<String, String> {
    match owner {
        Owner::Is(id) => Ok(id),
        Owner::Unknown(why) => Err(why),
        Owner::Unasked(live) => identify_document(ctx, tool, &live)
            .map(|owner| state.id_of(tool.id(), &owner))
            .map_err(|e| e.to_string()),
    }
}

/// Who owns the live login, answered from the record rather than from Anthropic, where the
/// record is enough to answer it.
///
/// Recovery needs to know which side of the switch the live credential came from, and
/// asking Anthropic is the only answer that survives Claude Code rotating a token. But the
/// two candidates are both Pitboard's own documents and their refresh tokens were
/// fingerprinted when the record was written, so the common case is a comparison and not a
/// round trip. That is what lets a switch be recovered on a plane.
///
/// It narrows the network dependency rather than removing it. A rotation inside the seconds
/// of an interrupted switch leaves a fingerprint matching neither side, which is exactly
/// when this says nothing and Anthropic is asked after all.
fn live_owner_by_fingerprint(journal: &Journal, found: &str) -> Option<String> {
    if journal.from_fingerprint.is_empty() || journal.to_fingerprint.is_empty() {
        return None;
    }
    if journal.from_fingerprint == journal.to_fingerprint {
        return None;
    }
    if found.is_empty() {
        return None;
    }
    if found == journal.to_fingerprint {
        Some(journal.to_id.clone())
    } else if found == journal.from_fingerprint {
        Some(journal.from_id.clone())
    } else {
        None
    }
}

/// What abandoning an unfinishable record decided to keep.
#[derive(Debug)]
pub struct Abandoned {
    pub from: String,
    pub to: String,
    /// Copies kept rather than deleted, because which one is live is now unknown.
    pub kept: usize,
}

/// Throws away a record that cannot be finished, keeping every copy it names.
///
/// Recovery needs the service to say who owns the live login. Offline, or with a session
/// the service no longer accepts, it cannot, and every command that changes anything stops
/// at that. This is the way out: nothing is installed and nothing that might be the only
/// copy is deleted, so the worst case is a copy that outlives its use, which `status` shows
/// and `doctor` reports.
///
/// One exception, for a tool whose park may never be a copy: a park whose refresh token is
/// the live login's own is a second copy for certain, whoever owns it, and is dropped
/// rather than kept.
pub(super) fn abandon(
    ctx: &Context,
    permit: Permit,
    state: &mut State,
) -> Result<Option<Abandoned>> {
    let path = journal_path(ctx);
    let raw = match std::fs::read_to_string(&path) {
        Ok(r) => r,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
        Err(source) => return Err(Error::RecoveryFailed { path, source }),
    };
    let journal =
        serde_json::from_str::<Journal>(&raw).map_err(|source| Error::RecoveryRecordCorrupt {
            path: path.clone(),
            source,
        })?;
    let tool = match provider::of(journal.provider) {
        LoginKind::Document(tool) => tool,
        LoginKind::Folder(_) => {
            return Err(Error::RecoveryRecordCorrupt {
                path,
                source: serde::de::Error::custom(
                    "it names a tool whose login no switch records here",
                ),
            });
        }
    };

    // The copy the interrupted run parked is recorded against the account it came from, so
    // nothing holds a keychain item that no file names.
    let mut kept = 0;
    if let Some(Some(document)) = read_park(ctx, &journal.park_service)
        && park::is_live_twin(ctx, tool, &document)
    {
        state.discard(&journal.park_service, ParkKind::Vault);
    } else if let Some(Some(document)) = read_park(ctx, &journal.park_service)
        && let Some(key) = state
            .by_id(journal.provider, &journal.from_id)
            .map(Account::key)
    {
        state.park(
            &key,
            park::describe(tool, &journal.park_service, ctx.now(), &document),
        );
        kept += 1;
    }
    let incoming = read_park(ctx, &journal.incoming_service).flatten();
    if incoming.is_some_and(|document| park::is_live_twin(ctx, tool, &document)) {
        state.discard(&journal.incoming_service, ParkKind::Vault);
    } else if state
        .by_id(journal.provider, &journal.to_id)
        .and_then(|a| a.parked.as_ref())
        .is_some()
    {
        kept += 1;
    }
    state::save(ctx, permit, state)?;
    clear_journal(ctx, permit);
    Ok(Some(Abandoned {
        from: state.typed(&journal.from()),
        to: state.typed(&journal.to()),
        kept,
    }))
}

/// The record of an interrupted switch, with every fact recovery decides it from that can be
/// read without asking anybody.
struct Waiting {
    tool: &'static dyn Provider,
    journal: Journal,
    /// The park the record reserved: written, never written, or `None` if unreadable.
    parked: Option<Option<Value>>,
    owner: Owner,
    seen: Seen,
}

/// The record of an interrupted switch, where one is waiting, and what recovery decides it
/// from. Reads, and writes nothing whatever it finds.
fn read(ctx: &Context, state: &State) -> Result<Option<Waiting>> {
    let path = journal_path(ctx);
    let raw = match std::fs::read_to_string(&path) {
        Ok(r) => r,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
        Err(source) => return Err(Error::RecoveryFailed { path, source }),
    };
    // Written atomically, so a record that does not parse was damaged afterwards and says
    // nothing about how far its switch got.
    let journal =
        serde_json::from_str::<Journal>(&raw).map_err(|source| Error::RecoveryRecordCorrupt {
            path: path.clone(),
            source,
        })?;
    let tool = match provider::of(journal.provider) {
        LoginKind::Document(tool) => tool,
        LoginKind::Folder(_) => {
            return Err(Error::RecoveryRecordCorrupt {
                path,
                source: serde::de::Error::custom(
                    "it names a tool whose login no switch records here",
                ),
            });
        }
    };

    if let Some(slot) = &journal.slot {
        let here = tool.slot(ctx);
        if *slot != here {
            return Err(Error::RecoveryElsewhere {
                tool: journal.provider,
                from: state.typed(&journal.from()),
                to: state.typed(&journal.to()),
                slot: slot.clone(),
            });
        }
    }

    let named = in_use::named(ctx, journal.provider);
    let (owner, login) = live_owner(ctx, tool, &journal);
    Ok(Some(Waiting {
        tool,
        parked: read_park(ctx, &journal.park_service),
        journal,
        owner,
        seen: Seen { named, login },
    }))
}

/// What finishes or undoes the switch, or, where the facts do not settle what it did, the
/// refusal of the change that found them so.
fn decide(
    state: &State,
    tool: &'static dyn Provider,
    journal: &Journal,
    parked: Option<Option<Value>>,
    owner: std::result::Result<String, String>,
) -> Result<Repair> {
    let found = Found {
        parked,
        live_owner: owner.as_ref().ok().cloned(),
    };
    repair_for(state, tool, journal, &found).ok_or_else(|| Error::RecoveryUndetermined {
        tool: journal.provider,
        from: state.typed(&journal.from()),
        to: state.typed(&journal.to()),
        detail: owner
            .err()
            .unwrap_or_else(|| "its parked login could not be read".into()),
    })
}

pub(super) fn reconcile(
    ctx: &Context,
    permit: Permit,
    state: &mut State,
) -> Result<Option<Recovered>> {
    let Some(Waiting {
        tool,
        journal,
        parked,
        owner,
        seen,
    }) = read(ctx, state)?
    else {
        return Ok(None);
    };
    let owner = ask(ctx, state, tool, owner);
    let repair = decide(state, tool, &journal, parked, owner)?;
    let finished = repair.landed;
    apply(state, &journal, repair, seen, ctx.now());
    state::save(ctx, permit, state)?;
    clear_journal(ctx, permit);

    Ok(Some(Recovered {
        from: state.typed(&journal.from()),
        to: state.typed(&journal.to()),
        finished,
    }))
}

/// Whether working out what an interrupted switch did may ask the service whose the live
/// login is, where the record cannot say. A change asks, and so does `status`, which asks
/// the service about every account anyway; `doctor` and `status_offline` send no request.
/// A tool whose login names its own account is identified from the login either way, which
/// asks nobody.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Asking {
    Service,
    Nobody,
}

/// The refusal the next change would make over the interrupted switch waiting here, worked
/// out by reading what [`reconcile`] reads and deciding as it decides, and changing nothing.
///
/// `None` where no switch is waiting, where the next change finishes or undoes it, and
/// where telling which would need the service and `asking` says not to ask it. A record
/// that cannot be read, or that was written for another slot, is refused by the next
/// change for that reason and not for this one, and is not this function's to say.
pub(super) fn refusal(ctx: &Context, state: &State, asking: Asking) -> Option<Error> {
    let Waiting {
        tool,
        journal,
        parked,
        owner,
        ..
    } = read(ctx, state).ok()??;
    if asking == Asking::Nobody
        && matches!(owner, Owner::Unasked(_))
        && !tool.identifies_by_itself()
    {
        return None;
    }
    let owner = ask(ctx, state, tool, owner);
    decide(state, tool, &journal, parked, owner).err()
}

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

    const NOW: i64 = 1_700_000_100;
    const PARK: &str = "pitboard-park-from-uuid-1700000000000";
    const INCOMING: &str = "pitboard-park-to-uuid-1690000000000";

    /// A record as 0.8.0 writes it. An account enrolled then kept its account uuid as its
    /// id, so what the record names is still each account's id.
    #[test]
    fn a_record_0_8_0_wrote_names_each_side_by_its_id() {
        let written: Journal = serde_json::from_value(serde_json::json!({
            "provider": "claude",
            "started_at": 1_700_000_000,
            "from_label": "from",
            "from_uuid": "from-uuid",
            "to_label": "to",
            "to_uuid": "to-uuid",
            "park_service": PARK,
            "incoming_service": INCOMING,
            "from_fingerprint": "f",
            "to_fingerprint": "t",
            "slot": "Claude Code-credentials"
        }))
        .expect("still read");
        assert_eq!(
            (written.from_id.as_str(), written.to_id.as_str()),
            ("from-uuid", "to-uuid")
        );
    }

    fn journal() -> Journal {
        Journal {
            provider: ProviderId::Claude,
            started_at: 1_700_000_000,
            from_label: "from".into(),
            from_id: "from-uuid".into(),
            to_label: "to".into(),
            to_id: "to-uuid".into(),
            park_service: PARK.into(),
            incoming_service: INCOMING.into(),
            from_fingerprint: "ffffffffffffffff".into(),
            to_fingerprint: "0000000000000000".into(),
            slot: None,
        }
    }

    /// A record written before fingerprints existed simply asks, which is what it always
    /// did. Reading an old record must never be a reason to refuse.
    #[test]
    fn a_record_from_before_the_fingerprints_falls_back_to_asking() {
        let mut j = journal();
        j.from_fingerprint = String::new();
        j.to_fingerprint = String::new();
        assert_eq!(live_owner_by_fingerprint(&j, &fingerprint("refresh")), None);
    }

    /// Two sides that fingerprint the same are not two sides. Nothing can be read off that,
    /// not even from a login that matches both.
    #[test]
    fn identical_fingerprints_settle_nothing() {
        let mut j = journal();
        j.from_fingerprint = fingerprint("refresh");
        j.to_fingerprint = j.from_fingerprint.clone();
        assert_eq!(live_owner_by_fingerprint(&j, &fingerprint("refresh")), None);
    }

    /// The fingerprint of a Claude Code login on `refresh`.
    fn fingerprint(refresh: &str) -> String {
        let live =
            serde_json::json!({"claudeAiOauth": {"refreshToken": refresh, "accessToken": "a"}});
        provider::document(ProviderId::Claude).fingerprint(&live)
    }

    /// The store holding the login fingerprinted `login`, with the tool's own record naming
    /// nobody.
    fn seen(login: &str) -> Seen {
        Seen {
            named: None,
            login: login.into(),
        }
    }

    /// What a switch's head records before anything moves: the store holds `from`'s login,
    /// as Anthropic said.
    fn identified_from(s: &mut State) {
        let from = InUse {
            owner: Some(account("from", None).owner()),
            login: journal().from_fingerprint,
            known_at: NOW - 60,
            named: None,
        };
        s.identified(ProviderId::Claude, from, NOW - 60);
    }

    fn account(label: &str, parked: Option<&str>) -> Account {
        Account {
            last_used_at: None,
            replaced_at: None,
            plan: None,
            label: label.into(),
            id: format!("{label}-uuid"),
            account_uuid: format!("{label}-uuid"),
            email: format!("{label}@example.com"),
            detail: state::Detail::Claude {
                organization_uuid: format!("{label}-org"),
                oauth_account: serde_json::json!({}),
            },
            parked: parked.map(|s| Park {
                service: s.into(),
                parked_at: 1_699_000_000,
                kind: ParkKind::Vault,
                login: "f".into(),
                access_expires_at: None,
                refresh_expires_at: None,
                session_expires_at: None,
            }),
        }
    }

    /// `from` signed in with nothing parked, `to` parked: the state before a switch.
    fn before() -> State {
        State {
            accounts: vec![account("from", None), account("to", Some(INCOMING))],
            ..State::default()
        }
    }

    fn written() -> Option<Option<Value>> {
        Some(Some(
            serde_json::json!({"refreshToken": "outgoing", "accessToken": "a"}),
        ))
    }

    fn found(parked: Option<Option<Value>>, owner: Option<&str>) -> Found {
        Found {
            parked,
            live_owner: owner.map(str::to_owned),
        }
    }

    /// Killed after reserving the park name but before writing it.
    #[test]
    fn nothing_parked_and_nothing_installed_changes_nothing() {
        let repair = repair_for(
            &before(),
            provider::document(ProviderId::Claude),
            &journal(),
            &found(Some(None), Some("from-uuid")),
        );
        assert_eq!(repair, Some(Repair::default()));
    }

    /// Killed after the park was written, before the install. `from` is still signed in, so
    /// the park is a second copy of a live login and Claude Code will rotate past it.
    #[test]
    fn a_park_of_a_login_still_signed_in_is_dropped_not_kept() {
        for s in [before(), {
            let mut recorded = before();
            recorded.park(
                &Key::new(ProviderId::Claude, "from"),
                account("x", Some(PARK)).parked.unwrap(),
            );
            recorded
        }] {
            let repair = repair_for(
                &s,
                provider::document(ProviderId::Claude),
                &journal(),
                &found(written(), Some("from-uuid")),
            )
            .unwrap();
            assert!(repair.drop && repair.hold.is_none() && !repair.landed);

            let mut applied = s;
            apply(
                &mut applied,
                &journal(),
                repair,
                seen(&journal().from_fingerprint),
                NOW,
            );
            assert!(!applied.references(PARK));
            assert!(applied.discarded.iter().any(|d| d.service == PARK));
        }
    }

    /// Killed after the install, before state recorded it. Claude Code may already have
    /// rotated the token.
    #[test]
    fn a_landed_switch_holds_the_outgoing_login_and_consumes_the_incoming_one() {
        let mut s = before();
        identified_from(&mut s);
        let repair = repair_for(
            &s,
            provider::document(ProviderId::Claude),
            &journal(),
            &found(written(), Some("to-uuid")),
        )
        .unwrap();
        let (uuid, park) = repair.hold.clone().expect("the orphan must be recovered");
        assert_eq!(uuid, "from-uuid", "held by account id, never by a label");
        assert_eq!(park.service, PARK);
        assert!(repair.landed);

        let rotated = fingerprint("rotated-since");
        apply(&mut s, &journal(), repair, seen(&rotated), NOW);
        assert_eq!(
            s.account_in_use(ProviderId::Claude)
                .map(|a| a.label.as_str()),
            Some("to")
        );
        assert_eq!(
            s.in_use(ProviderId::Claude)
                .map(|r| (r.login.as_str(), r.known_at)),
            Some((rotated.as_str(), NOW)),
            "the login the store holds, which Claude Code may have rotated since the install"
        );
        let from = s.get(&Key::new(ProviderId::Claude, "from")).unwrap();
        assert_eq!(from.parked.as_ref().unwrap().service, PARK);
        assert_eq!(
            from.replaced_at, None,
            "its login is parked, so nothing of it was lost"
        );
        assert!(
            s.get(&Key::new(ProviderId::Claude, "to"))
                .unwrap()
                .parked
                .is_none(),
            "the copy now live must never be offered again"
        );
        assert!(s.discarded.iter().any(|d| d.service == INCOMING));
    }

    /// Someone signed in as a third account since: the orphan may be the only copy of
    /// `from`'s login, and the destination's park may still be good.
    #[test]
    fn a_third_account_signed_in_since_keeps_both_parks() {
        let mut s = before();
        let repair = repair_for(
            &s,
            provider::document(ProviderId::Claude),
            &journal(),
            &found(written(), Some("other-uuid")),
        )
        .unwrap();
        apply(&mut s, &journal(), repair, seen(&fingerprint("other")), NOW);
        assert!(s.references(PARK) && s.references(INCOMING));
        assert!(s.discarded.is_empty());
    }

    #[test]
    fn an_already_recorded_park_is_not_held_twice() {
        let mut s = before();
        s.park(
            &Key::new(ProviderId::Claude, "from"),
            account("x", Some(PARK)).parked.unwrap(),
        );
        let repair = repair_for(
            &s,
            provider::document(ProviderId::Claude),
            &journal(),
            &found(written(), Some("to-uuid")),
        )
        .unwrap();
        assert_eq!(repair.hold, None);
    }

    #[test]
    fn an_unknown_outcome_changes_nothing_and_keeps_the_record() {
        for unknown in [found(written(), None), found(None, Some("to-uuid"))] {
            assert_eq!(
                repair_for(
                    &before(),
                    provider::document(ProviderId::Claude),
                    &journal(),
                    &unknown
                ),
                None,
                "could-not-tell must never be read as nothing-there"
            );
        }
    }

    #[test]
    fn a_park_whose_account_was_forgotten_is_not_filed_under_another() {
        let mut s = State {
            accounts: vec![account("other", None)],
            ..State::default()
        };
        identified_from(&mut s);
        let repair = repair_for(
            &s,
            provider::document(ProviderId::Claude),
            &journal(),
            &found(written(), Some("to-uuid")),
        )
        .unwrap();
        apply(
            &mut s,
            &journal(),
            repair,
            seen(&journal().to_fingerprint),
            NOW,
        );
        assert!(
            !s.references(PARK),
            "a park must never be filed under whatever account happens to hold a label"
        );
        assert_eq!(
            s.in_use(ProviderId::Claude),
            None,
            "the store no longer holds `from`'s login, and nobody here says whose it holds"
        );
    }

    /// The destination forgotten and its label given to another account since. That account
    /// is not the one whose login the switch installed, and the destination's park is not
    /// its to consume.
    #[test]
    fn a_label_given_to_another_account_since_is_not_the_destination() {
        const THEIRS: &str = "pitboard-park-someone-uuid-1695000000000";
        let someone = Account {
            id: "someone-uuid".into(),
            account_uuid: "someone-uuid".into(),
            ..account("to", Some(THEIRS))
        };
        let mut s = State {
            accounts: vec![account("from", None), someone],
            ..State::default()
        };
        identified_from(&mut s);
        let repair = repair_for(
            &s,
            provider::document(ProviderId::Claude),
            &journal(),
            &found(written(), Some("to-uuid")),
        )
        .unwrap();
        apply(
            &mut s,
            &journal(),
            repair,
            seen(&journal().to_fingerprint),
            NOW,
        );

        assert_eq!(
            s.in_use(ProviderId::Claude),
            None,
            "the login installed is not the account that holds the label now"
        );
        let to = s.get(&Key::new(ProviderId::Claude, "to")).unwrap();
        assert_eq!(to.last_used_at, None, "never in use");
        assert_eq!(to.parked.as_ref().map(|p| p.service.as_str()), Some(THEIRS));
        assert!(
            !s.discarded.iter().any(|d| d.service == INCOMING),
            "the destination's park is no account's here to consume"
        );
    }
}