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
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
use crate::provider;
use crate::provider::{LoginKind, Provider, ProviderId};
mod adopt;
mod auto;
#[cfg(test)]
mod crash;
pub(crate) mod enroll;
pub(crate) mod folder;
#[cfg(test)]
mod foreign;
mod forget;
#[cfg(test)]
pub(crate) mod harness;
pub(crate) mod identify;
mod journal;
#[cfg(test)]
mod pinned;
mod refresh;
#[cfg(test)]
mod refusals;
mod rename;
pub(crate) mod renew;
mod stow;
#[cfg(test)]
mod two_tools;
mod uninstall;
pub mod warm;

pub use crate::pending::Reclaimed;
pub use adopt::Adopted;
pub(crate) use adopt::adopt;
pub(crate) use auto::automatically;
pub(crate) use enroll::enroll;
#[cfg(any(test, feature = "test-support"))]
pub(crate) use enroll::planted;
pub use enroll::{Enrolled, Said, SignIn, Steps, WatchedSignIn};
#[cfg(any(test, feature = "test-support"))]
pub use enroll::{ScriptedSignIn, SignInScript};
pub(crate) use enroll::{one_at_a_time, sign_in, sign_in_watched_as};
pub use folder::awaited::WaitStep;
pub use folder::{Ended, GivenUp, MoveSettled};
pub(crate) use forget::forget;
pub use journal::{Abandoned, Recovered};
pub(crate) use journal::{Asking, interrupted_tool, pending as interrupted};
pub(crate) use rename::rename;
pub use renew::Renewal;
pub(crate) use renew::{Due, renew_due, renew_parked};
pub(crate) use stow::find as left_login;
pub(crate) use stow::stow;
pub use stow::{Foreseen, Kept, Left, Stowed};
pub use uninstall::Removed;
pub(crate) use uninstall::uninstall;

use crate::context::Context;
use crate::error::{Error, Result};
use crate::in_use::{self, InUse};
use crate::service::{Permit, Warning};
use crate::state::{Account, Key, Park, ParkKind, State};
use crate::{fault, holder, home, lock, park, pending, state, store};
use journal::{Journal, clear_journal, reconcile, write_journal};
use refresh::Refreshing;
use serde_json::Value;
use std::path::PathBuf;

/// Claude Code serves the credential from a 30 second cache, so a session already running
/// picks up a swap within about 33 seconds, wherever no `.credentials.json` sits behind the
/// keychain (the register's `credential_cache`). Measured over three runs on one machine
/// with 2.1.278: swapping at t+8, t+20 and t+28 seconds took effect at t+32.3, t+33.5 and
/// t+32.95 from process start.
pub const ADOPTION_CEILING_SECONDS: u32 = 33;

#[derive(Debug)]
pub enum Outcome {
    Switched {
        /// Which tool's login moved.
        provider: ProviderId,
        from: String,
        to: String,
        parked: Park,
        /// When a session already running will be using the incoming login, as this tool
        /// answers it on this machine once the switch is made. Carried rather than read from
        /// a constant, because the honest answer for two of the three tools is that nothing
        /// follows until they are restarted, and for Claude Code it turns on what sits
        /// behind the keychain.
        adoption: provider::Adoption,
    },
    // Put in use where the tool held nobody's login, so no account was parked for it.
    Installed {
        provider: ProviderId,
        to: String,
        adoption: provider::Adoption,
    },
    /// Not a failure: the state the caller asked for already holds.
    AlreadyActive {
        label: String,
        /// The tool's own record named another account, and now names this one again, as a
        /// switch to it writes it.
        config_updated: bool,
    },
}

/// Pitboard's state, held exclusively, with any interrupted switch already finished. Every
/// command that changes state starts from one, so none acts on what a crash left behind,
/// and it carries the [`Permit`] it was settled with, which is what lets the change write.
#[derive(Debug)]
pub(crate) struct Settled {
    _exclusive: std::fs::File,
    state: State,
    ctx: Context,
    permit: Permit,
}

// What giving up came to, of both kinds of change.
#[derive(Debug, Default)]
pub struct GaveUp {
    pub switch: Option<Abandoned>,
    pub moves: Vec<GivenUp>,
    // what settling said, and each move abandon could not give up after giving up a switch
    pub warnings: Vec<Warning>,
}

// Gives up an interrupted switch, and each move that cannot be settled, keeping every copy
// they name. Under a custom Claude Code endpoint only a Claude Code switch is refused.
pub fn abandon(ctx: &Context, permit: Permit) -> Result<GaveUp> {
    // With no switch waiting the endpoint is not asked: it never stops an app's give-up.
    if let Some(tool) = interrupted_tool(ctx) {
        refuse_custom_oauth(ctx, Some(tool))?;
    }
    let _exclusive = exclusive(ctx, permit)?;
    let mut state = state::load(ctx)?;
    // Whatever an app's state: no Claude Code or Codex change waits on an app's move.
    let mut gave_up = GaveUp {
        switch: journal::abandon(ctx, permit, &mut state)?,
        ..GaveUp::default()
    };
    // A move that can be settled is settled and said: only one that cannot is given up.
    for &tool in ProviderId::ALL {
        let LoginKind::Folder(app) = provider::of(tool) else {
            continue;
        };
        let Some(label) = state
            .moving(tool)
            .map(|moving| state.typed(&Key::new(tool, moving.label.clone())))
        else {
            continue;
        };
        let done =
            gave_up.switch.is_some() || !gave_up.moves.is_empty() || !gave_up.warnings.is_empty();
        match folder::abandon(ctx, permit, &mut state, app) {
            Ok((given_up, said)) => {
                gave_up.moves.extend(given_up);
                gave_up.warnings.extend(said);
            }
            // Said beside what was done, whose "nothing has changed" would be false.
            Err(why) if done => {
                gave_up
                    .warnings
                    .push(Warning::MoveNotGivenUp { tool, label, why });
                // A refusal can leave in memory what it never saved, and the next save would.
                state = state::load(ctx)?;
            }
            Err(refused) => return Err(refused),
        }
    }
    Ok(gave_up)
}

/// Under a custom OAuth endpoint Claude Code's live login is in "Claude Code-custom-oauth-
/// credentials", not the item Pitboard reads. Acting on it would park nothing and restore
/// into an item nobody reads, so Pitboard does not act on Claude Code at all: not a change
/// to one of its accounts, not a change that could touch every tool's, and not the
/// recovery of an interrupted Claude Code switch. A change to another tool's account goes
/// ahead; its login is somewhere this setting does not move.
fn refuse_custom_oauth(ctx: &Context, tool: Option<ProviderId>) -> Result<()> {
    if !crate::settings::custom_oauth(ctx) {
        return Ok(());
    }
    let claude = Some(ProviderId::Claude);
    if tool.is_none() || tool == claude || interrupted_tool(ctx) == claude {
        return Err(Error::CustomOauthEndpoint);
    }
    Ok(())
}

/// What recovery found is returned apart from the `Settled`, so it can be reported whether
/// or not the command that follows succeeds.
///
/// `tool` is the tool the change that follows is about, where it is about one.
pub(crate) fn settle(
    ctx: &Context,
    permit: Permit,
    tool: Option<ProviderId>,
) -> Result<(Settled, Option<Recovered>)> {
    refuse_custom_oauth(ctx, tool)?;
    let exclusive = exclusive(ctx, permit)?;
    let mut state = state::load(ctx)?;
    let recovered = reconcile(ctx, permit, &mut state)?;
    // A copy that cannot be saved yet stops what acts on its slot's login, where that asks
    // again (`refresh::finished`), and nothing else.
    let _ = refresh::finish(ctx, permit, &mut state);
    // After the journal has had its say, so a switch's own park is already accounted for.
    pending::sweep(ctx, permit, &mut state)?;
    drop_live_twins(ctx, permit, &mut state)?;
    purge(ctx, permit, &mut state);
    Ok((
        Settled {
            _exclusive: exclusive,
            state,
            ctx: ctx.clone(),
            permit,
        },
        recovered,
    ))
}

/// Why the next change would stop at an interrupted switch it cannot finish: the refusal
/// that change would make, in its words. `None` where no switch is waiting, where the next
/// change finishes or undoes it by itself, and where telling which would need the service
/// and `asking` says not to ask it.
///
/// Worked out the way [`settle`] works it out, from the same reads and the same decision,
/// and only read: no lock is taken, nothing is written, and the record stays for whatever
/// finishes it or gives up on it. A switch under way in another run has a record too, and
/// what it leaves at every step is what the next change could settle, ordinarily from the
/// fingerprints alone, so it does not read as stuck.
pub(crate) fn stuck(ctx: &Context, state: &State, asking: Asking) -> Option<Error> {
    if !journal::pending(ctx) {
        return None;
    }
    // Under a custom Claude Code endpoint no change comes to a Claude Code switch: each is
    // refused over the endpoint first, as settling it and giving up on it are. A Codex
    // switch is settled there, and given up on, as anywhere.
    refuse_custom_oauth(ctx, interrupted_tool(ctx)).ok()?;
    journal::refusal(ctx, state, asking)
}

/// Ask the store itself what parked logins are on this machine, and resolve every one the
/// state does not name. `settle` already does this from Pitboard's own list of names on
/// every change; this is the thorough version, for a machine whose list was lost with its
/// state file, or written by a version that kept no list.
pub(crate) fn repair(settled: Settled) -> Result<(Reclaimed, Vec<Warning>)> {
    let Settled {
        _exclusive,
        mut state,
        ctx,
        permit,
    } = settled;
    // Nothing of an app is read but where a move of its login waits.
    let mut warnings = Vec::new();
    for &tool in ProviderId::ALL {
        match provider::of(tool) {
            LoginKind::Document(_) => {}
            LoginKind::Folder(app) => {
                warnings.extend(folder::settle_for_repair(&ctx, permit, &mut state, app));
            }
        }
    }
    let mut reclaimed = pending::reclaim(&ctx, permit, &mut state)?;
    give_back_asides(&ctx, permit, &mut state, &mut reclaimed)?;
    purge(&ctx, permit, &mut state);
    Ok((reclaimed, warnings))
}

// A folder set aside goes back to its account where its manifest, keys and jar agree.
fn give_back_asides(
    ctx: &Context,
    permit: Permit,
    state: &mut State,
    reclaimed: &mut Reclaimed,
) -> Result<()> {
    let folders = park::parks(ParkKind::Folder);
    let names: Vec<String> = state.aside.iter().map(|aside| aside.name.clone()).collect();
    let mut given = false;
    for name in names {
        let park::Orphan::Login { id, park, .. } = folders.orphan(ctx, state, &name) else {
            continue;
        };
        let Some(key) = pending::takes(ctx, state, &id) else {
            continue;
        };
        state.drop_aside(&name);
        pending::give_back(ctx, permit, state, &key, *park, reclaimed);
        given = true;
    }
    if given {
        state::save(ctx, permit, state)?;
    }
    Ok(())
}

/// Drop every park that is a copy of the login its tool has in use now, and say so in the
/// state before anything deletes it. The journal records the one copy a switch makes on
/// purpose; this finds the one nothing records, which a new login leaves when it was put in
/// use and could not be read back, and was parked as well.
fn drop_live_twins(ctx: &Context, permit: Permit, state: &mut State) -> Result<()> {
    let twins = park::live_twins(ctx, state);
    if twins.is_empty() {
        return Ok(());
    }
    for service in &twins {
        state.discard(service, ParkKind::Vault);
    }
    state::save(ctx, permit, state)
}

/// Delete what no account refers to any more. A failed save only leaves deleted names
/// listed, and deleting a missing item succeeds, so a later run clears them.
fn purge(ctx: &Context, permit: Permit, state: &mut State) -> usize {
    let listed = state.discarded.len();
    let remaining = park::purge(ctx, permit, state);
    if remaining != listed {
        let _ = state::save(ctx, permit, state);
    }
    remaining
}

/// Makes Pitboard runs exclusive of each other. A kernel lock, unlike the directory lock
/// Claude Code's protocol requires around its own writes: the operating system releases it
/// when a process ends, so there is no staleness rule for two runs to both satisfy.
fn exclusive(ctx: &Context, permit: Permit) -> Result<std::fs::File> {
    let (file, path) = lock_file(ctx, permit)?;
    file.lock()
        .map_err(|source| Error::HomeUnwritable { path, source })?;
    Ok(file)
}

/// `exclusive` without waiting: `None` while another Pitboard run holds it.
fn try_exclusive(ctx: &Context, permit: Permit) -> Option<std::fs::File> {
    let (file, _) = lock_file(ctx, permit).ok()?;
    file.try_lock().ok()?;
    Some(file)
}

/// A switch's record, as a look that waits on nobody finds it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Unfinished {
    /// Another run holds Pitboard's lock: the switch is that run's to finish or refuse over.
    UnderWay,
    /// No run holds the lock, so the switch waits for the next change.
    Interrupted,
}

/// The record of a switch not finished, where one is there. It only asks whether the lock is
/// held: the lock's file is opened to read, never made, and no file is no holder. The lock is
/// asked for shared, kept over a second look at the record so no run begins or ends a switch
/// between the two, and let go of at once.
pub(crate) fn unfinished(ctx: &Context) -> Option<Unfinished> {
    if !journal::pending(ctx) {
        return None;
    }
    let Ok(lock) = std::fs::File::open(home::dir(ctx).join("state.lock")) else {
        return Some(Unfinished::Interrupted);
    };
    match lock.try_lock_shared() {
        Err(std::fs::TryLockError::WouldBlock) => Some(Unfinished::UnderWay),
        _ => journal::pending(ctx).then_some(Unfinished::Interrupted),
    }
}

fn lock_file(ctx: &Context, permit: Permit) -> Result<(std::fs::File, PathBuf)> {
    let path = home::dir(ctx).join("state.lock");
    let fail = |source| Error::HomeUnwritable {
        path: path.clone(),
        source,
    };
    home::ensure(ctx, permit).map_err(fail)?;
    let file = crate::host::fs::open_private_lock(permit, &path).map_err(fail)?;
    Ok((file, path))
}

/// Whose login this document holds. When this cannot be answered, nothing moves: a login
/// filed under a guessed account takes two accounts with it.
///
/// Through the provider, because the answer costs a network round trip for Claude Code and
/// nothing at all for Codex, whose login carries a signed token naming the account. The
/// caller wants the answer and should not have to know which.
pub(super) fn identify_document(
    ctx: &Context,
    tool: &'static dyn Provider,
    document: &Value,
) -> Result<provider::Owner> {
    let credential = provider::Credential::new(tool.id(), document.clone());
    tool.identify(ctx, &credential)
        .map_err(|e| unidentified(tool.id(), e))
}

/// Why nobody could say whose a login of `which` is, as a change refuses over it.
fn unidentified(which: ProviderId, error: provider::ProviderError) -> Error {
    match error {
        provider::ProviderError::Unauthorized => Error::SessionExpired {
            tool: which,
            refused: false,
        },
        other @ (provider::ProviderError::ShapeUnexpected { .. }
        | provider::ProviderError::Unsupported { .. }) => shape(which, other),
        other => Error::IdentityUnverifiable {
            tool: which,
            cause: crate::error::Cause::of_provider(&other),
            detail: other.to_string(),
        },
    }
}

/// Nothing is signed in to this tool, said the way the tool's own files explain it.
///
/// Nothing in any store Pitboard reads, and the tool's own record naming somebody as signed
/// in, are two different situations. The second means Pitboard is looking in the wrong
/// place, and writing a login there would put it where nobody reads.
pub(super) fn nothing_signed_in(ctx: &Context, tool: &'static dyn Provider) -> Error {
    match tool.own_record(ctx) {
        Some(found) => Error::LiveCredentialElsewhere { email: found.email },
        None => Error::LiveCredentialAbsent {
            tool: tool.id(),
            label: None,
        },
    }
}

/// Where this tool's live login is, or why Pitboard cannot act on it here.
pub(super) fn live_store(
    ctx: &Context,
    tool: &'static dyn Provider,
) -> Result<provider::LiveStore> {
    tool.live(ctx).map_err(|e| shape(tool.id(), e))
}

/// The live login as it is stored, byte for byte, and as a document.
///
/// The bytes are kept because a failed write is judged by whether they changed, and a
/// document read back through a parser would compare equal to one whose bytes had moved.
fn read_live(
    ctx: &Context,
    tool: &'static dyn Provider,
    live: &provider::LiveStore,
) -> Result<(String, Value)> {
    read_stored(tool, live)?.ok_or_else(|| nothing_signed_in(ctx, tool))
}

/// [`read_live`], with `None` where nothing is signed in: nothing stored, or a document with
/// no account's login in it, as Claude Code's `/logout` leaves.
fn read_stored(
    tool: &'static dyn Provider,
    live: &provider::LiveStore,
) -> Result<Option<(String, Value)>> {
    let Some(raw) = store::read_raw(&live.chain, &live.service)? else {
        return Ok(None);
    };
    let document = serde_json::from_str(&raw)
        .map_err(|e| Error::Store(store::Error::Malformed(e.to_string())))?;
    match tool.slice(&document) {
        Err(provider::ProviderError::NoLogin { .. }) => Ok(None),
        Err(other) => Err(shape(tool.id(), other)),
        Ok(_) => Ok(Some((raw, document))),
    }
}

pub(crate) fn switch(settled: Settled, key: &Key) -> Result<(Outcome, Vec<Warning>)> {
    let tool = match provider::of(key.provider) {
        LoginKind::Document(tool) => tool,
        LoginKind::Folder(app) => return folder::switch(settled, key, app),
    };
    let Settled {
        _exclusive,
        mut state,
        ctx,
        permit,
    } = settled;
    let target = enrolled(&state, key)?;
    // Known before taking the tool's own lock so a round trip does not hold up its writes,
    // then confirmed under the lock. Recorded at once, so the record names the account a
    // switch moves out of when it records the one it moves to, whatever it named before.
    let identify::Live::Login(outgoing) = identify::now(&ctx, permit, &mut state, tool)? else {
        return Err(Error::LiveCredentialAbsent {
            tool: key.provider,
            label: None,
        });
    };
    if target.owned_by(&outgoing.owner) {
        let lost = outgoing.lock_warning(key.provider);
        let (outcome, warnings) = already_active(&ctx, permit, &mut state, tool, key, &target);
        return Ok((outcome, lost.into_iter().chain(warnings).collect()));
    }
    let (switched, warnings) = switch_from(state, &ctx, permit, tool, key, outgoing)?;
    Ok((switched.into(), warnings))
}

/// What [`switch`] does for the account in use, for a button drawn while it was: writes it
/// into its tool's own record where that names another account. Refused, moving nothing,
/// where another account's login is stored by then, which [`switch`] would switch back from.
pub(crate) fn update_config(settled: Settled, key: &Key) -> Result<(Outcome, Vec<Warning>)> {
    let tool = match provider::of(key.provider) {
        LoginKind::Document(tool) => tool,
        LoginKind::Folder(app) => return folder::confirm(settled, key, app),
    };
    let Settled {
        _exclusive,
        mut state,
        ctx,
        permit,
    } = settled;
    let target = enrolled(&state, key)?;
    match identify::now(&ctx, permit, &mut state, tool)? {
        identify::Live::Login(stored) if target.owned_by(&stored.owner) => {
            let lost = stored.lock_warning(key.provider);
            let (outcome, warnings) = already_active(&ctx, permit, &mut state, tool, key, &target);
            Ok((outcome, lost.into_iter().chain(warnings).collect()))
        }
        _ => Err(Error::AccountNotInUse {
            tool: key.provider,
            label: state.typed(key),
        }),
    }
}

/// The account enrolled under `key`, or a refusal that lists the labels that are.
fn enrolled(state: &State, key: &Key) -> Result<Account> {
    state
        .get(key)
        .cloned()
        .ok_or_else(|| Error::AccountUnknown {
            label: key.typed(),
            enrolled: state.labels(key.provider),
        })
}

/// A switch made: which tool's login moved, between which accounts, the outgoing login's new
/// park, and when sessions already running take it. What [`Outcome::Switched`] says.
struct Switched {
    provider: ProviderId,
    from: String,
    to: String,
    parked: Park,
    adoption: provider::Adoption,
}

impl From<Switched> for Outcome {
    fn from(switched: Switched) -> Outcome {
        let Switched {
            provider,
            from,
            to,
            parked,
            adoption,
        } = switched;
        Outcome::Switched {
            provider,
            from,
            to,
            parked,
            adoption,
        }
    }
}

/// [`switch`] to `key`'s account from `outgoing`, the login its tool has stored, which the
/// caller told whose it is and recorded under Pitboard's lock, and which is not the target's.
/// The automatic switch decides from that same telling, so nothing comes between what it
/// decided and the login it moves.
fn switch_from(
    mut state: State,
    ctx: &Context,
    permit: Permit,
    tool: &'static dyn Provider,
    key: &Key,
    outgoing: identify::Login,
) -> Result<(Switched, Vec<Warning>)> {
    let label = &key.label;
    let target = enrolled(&state, key)?;
    let identify::Login {
        store: live,
        document: first,
        owner: outgoing,
        lock_lost: renewal_lock_lost,
    } = outgoing;
    let (outgoing_key, outgoing_id) = state
        .account_of(key.provider, &outgoing)
        .map(|account| (account.key(), account.id.clone()))
        .ok_or_else(|| Error::LiveAccountNotEnrolled {
            tool: key.provider,
            who: crate::words::login(
                key.provider,
                &outgoing.email,
                state
                    .accounts
                    .iter()
                    .any(|a| a.provider() == key.provider && a.email == outgoing.email),
            ),
        })?;
    let (from, to) = (state.typed(&outgoing_key), state.typed(key));
    let held = target.parked.clone().ok_or_else(|| Error::NothingParked {
        tool: key.provider,
        label: to.clone(),
    })?;
    if !held.restorable_at(ctx.now()) {
        return Err(Error::ParkedLoginExpired { label: to });
    }
    let incoming = park::load(ctx, tool, key, &held)?;
    // Asked before the tool's lock is taken, like the outgoing question, so the round trip
    // does not hold up its writes.
    let (held, incoming) =
        prove_incoming(ctx, permit, &mut state, tool, key, &target, held, incoming)?;

    // A renewal by a running session spends the refresh token it sends, and the tool's write
    // lock does not keep one from starting. So the lock a renewal takes first is held from
    // before the outgoing login is read for the last time until the login installed in its
    // place is recorded: the copy parked is then never one a session has spent.
    let refreshing = Refreshing::take(ctx, permit, tool)?;
    let guard = write_lock(ctx, permit, tool)?;
    let Readied {
        before_raw,
        before,
        next,
        on_the_command_line,
    } = ready(ctx, tool, &live, &first, &outgoing, &incoming, &to)?;

    // The outgoing login's park has a ceiling of its own on a machine whose vault is the
    // keychain, and it is asked about now, while refusing still changes nothing. The name
    // is the one `reserve` is about to make, give or take the millisecond, which is all
    // the price depends on.
    let parking = park::price(
        ctx,
        key.provider,
        &from,
        &park::service_name(&outgoing_id, ctx.now_millis()),
        &tool.slice(&before).map_err(|e| shape(key.provider, e))?,
    )?;
    let park_service = park::reserve(ctx, permit, &outgoing_id)?;
    write_journal(
        ctx,
        permit,
        &Journal {
            provider: key.provider,
            started_at: ctx.now(),
            from_label: outgoing_key.label.clone(),
            from_id: outgoing_id,
            to_label: label.to_string(),
            to_id: target.id.clone(),
            park_service: park_service.clone(),
            incoming_service: held.service.clone(),
            // Which side the live credential came from, answerable without asking anyone.
            from_fingerprint: tool.fingerprint(&before),
            to_fingerprint: held.login.clone(),
            slot: Some(tool.slot(ctx)),
        },
    )?;
    fault::point("switch.journal_written");

    // Until the incoming login is installed there is nothing for a later run to finish, so
    // a failure here takes the record of intent away with it. A copy that was written but
    // could not be recorded is deleted: nothing that survives would name it.
    let slice = tool.slice(&before).map_err(|e| shape(key.provider, e))?;
    let parked = match park::store_at(ctx, permit, tool, &park_service, &slice) {
        Ok(parked) => parked,
        Err(e) => {
            clear_journal(ctx, permit);
            return Err(e);
        }
    };
    fault::point("switch.park_stored");
    state.park(&outgoing_key, parked.clone());
    if let Err(e) = state::save(ctx, permit, &state) {
        let _ = store::vault_delete(ctx, permit, &parked.service);
        clear_journal(ctx, permit);
        return Err(e);
    }
    fault::point("switch.park_recorded");

    // For a tool whose own sign-out revokes whatever it finds stored, there must never be
    // two usable copies of one account's login at rest. The copy is read back before
    // anything overwrites the original, so a park that did not survive the write is found
    // here, while the login it copies is still where it was.
    if tool.park_semantics() == provider::ParkSemantics::MoveOnly
        && store::vault_read(ctx, &parked.service)?.is_none()
    {
        state.release(&parked.service);
        state::save(ctx, permit, &state)?;
        clear_journal(ctx, permit);
        return Err(Error::ParkedCredentialMissing { label: from });
    }

    // The live login is read once more before it is replaced. A tool that takes no write
    // lock, which is Codex, can have rewritten it since it was read under nothing at all:
    // a session still running from before the switch refreshing its token, which spends
    // the chain just parked and leaves the only live copy of it in the file this write is
    // about to replace. Nothing is installed over a login that moved. Where the one there
    // now is still the outgoing account's, the park is a spent copy of it and is dropped;
    // where it is anybody else's, or cannot be told, the park may be the outgoing account's
    // only login and is kept. The window left is the rename itself.
    let now = store::read_raw(&live.chain, &live.service);
    if !matches!(&now, Ok(Some(now)) if *now == before_raw) {
        let still_outgoing = now
            .ok()
            .flatten()
            .and_then(|raw| serde_json::from_str::<Value>(&raw).ok())
            .and_then(|document| identify_document(ctx, tool, &document).ok())
            .is_some_and(|found| found.same_login(&outgoing));
        if still_outgoing {
            state.discard(&parked.service, ParkKind::Vault);
        }
        state::save(ctx, permit, &state)?;
        clear_journal(ctx, permit);
        purge(ctx, permit, &mut state);
        return Err(Error::SignedInAccountChanged);
    }

    if let Err(e) = install_with(
        key.provider,
        |body| store::write_raw(&live.chain, permit, &live.service, body),
        || store::read_raw(&live.chain, &live.service),
        &next,
        &before_raw,
        &from,
        &to,
    ) {
        // Nobody could say what the slot holds. Keep every copy, and keep the record of
        // intent, so the next run with a store that answers finishes this or undoes it.
        // Everything below deletes something or forgets something, and neither is a thing
        // to do without knowing.
        if matches!(e, Error::SwitchUnverified { .. }) {
            return Err(e);
        }
        if !only_copy_left(&e) {
            state.discard(&parked.service, ParkKind::Vault);
        }
        state::save(ctx, permit, &state)?;
        clear_journal(ctx, permit);
        purge(ctx, permit, &mut state);
        return Err(e);
    }
    fault::point("switch.installed");

    // The write landed. That is not the same as it having held. Measured in Claude Code
    // 2.1.278, a `/logout` that has given up waiting deletes the credential with no lock
    // held at all, which is the one write its lock does not exclude; and a lock that aged
    // out while the machine slept lets the tool reclaim it and write underneath. Both cost
    // one read to notice here, and cost a browser sign-in to discover later.
    //
    // Checked before the incoming copy is discarded, so finding it did not hold leaves both
    // logins parked rather than neither.
    let lock_lost = guard.as_ref().is_some_and(lock::Guard::compromised);
    match holds(tool, &live) {
        Ok(true) => {}
        Ok(false) => {
            clear_journal(ctx, permit);
            return Err(Error::SwitchDidNotHold {
                tool: key.provider,
                from,
                to,
            });
        }
        Err(unreadable) => {
            return Err(Error::SwitchUnverified {
                tool: key.provider,
                from,
                to,
                detail: unreadable.to_string(),
            });
        }
    }

    state.discard(&held.service, ParkKind::Vault);
    let installed = InUse {
        owner: Some(target.owner()),
        login: tool.fingerprint(&incoming),
        known_at: ctx.now(),
        // What the tool's own record named when the store was read, until `write_config`
        // writes `target` there.
        named: state
            .in_use(key.provider)
            .and_then(|known| known.named.clone()),
    };
    state.identified(key.provider, installed, ctx.now());
    state::save(ctx, permit, &state)?;
    fault::point("switch.recorded");
    drop(guard);
    let lock_lost = lock_lost | Refreshing::let_go(refreshing) | renewal_lock_lost;

    let cache_warning = write_config(ctx, permit, &mut state, tool, &target, &outgoing);
    fault::point("switch.config_updated");
    let parks_pending = purge(ctx, permit, &mut state);
    clear_journal(ctx, permit);

    // A tool that never follows a switch on its own goes on using the outgoing account in
    // everything of it already running. Said with what is running, because "restart it"
    // means nothing to somebody who does not know one is open, with what makes each kind
    // take the switch, and with the one thing not to do in any of them. Where nobody could
    // tell what is running, that is said, with the same thing not to do.
    let still_running = match still_holding(ctx, key.provider) {
        StillHolding::Nothing => None,
        StillHolding::These(holding) => Some(Warning::SessionsStillRunning {
            from: from.clone(),
            holding,
        }),
        StillHolding::Unknown => Some(Warning::SessionsUnknown {
            tool: key.provider,
            from: from.clone(),
        }),
    };
    let warnings = on_the_command_line
        .into_iter()
        .chain(parking)
        .chain(still_running)
        .chain(lock_lost.then_some(Warning::LockCompromised { tool: key.provider }))
        .chain(cache_warning)
        .chain((parks_pending > 0).then_some(Warning::ParksPendingRemoval(parks_pending)))
        .collect();
    Ok((
        Switched {
            provider: key.provider,
            adoption: tool.adoption(tool.behind(ctx).as_ref()),
            from,
            to,
            parked,
        },
        warnings,
    ))
}

/// `use` of `target`, the account under `key`, whose login its tool has stored: writes it
/// into the tool's own record where that names another account, as a switch to it does.
fn already_active(
    ctx: &Context,
    permit: Permit,
    state: &mut State,
    tool: &'static dyn Provider,
    key: &Key,
    target: &Account,
) -> (Outcome, Vec<Warning>) {
    let which = key.provider;
    let naming = in_use::naming(which, &target.owner());
    let named = tool
        .own_record(ctx)
        .filter(|named| Some(state::new_id(which, named)) != naming);
    let (config_updated, warnings) = match named {
        None => (false, Vec::new()),
        Some(named) => match write_config(ctx, permit, state, tool, target, &named) {
            None => (true, Vec::new()),
            Some(warning) => (false, vec![warning]),
        },
    };
    (
        Outcome::AlreadyActive {
            label: state.typed(key),
            config_updated,
        },
        warnings,
    )
}

/// Writes `target`, whose login `tool` has stored and is recorded as in use, into the
/// tool's own record over `named`, and records that it names `target` once the write lands.
/// A write that fails is the warning returned, and leaves the record naming what the tool's
/// own record named when the store was read, so every read says it names another account.
fn write_config(
    ctx: &Context,
    permit: Permit,
    state: &mut State,
    tool: &'static dyn Provider,
    target: &Account,
    named: &provider::Owner,
) -> Option<Warning> {
    let which = tool.id();
    if let Err(error) = tool.after_switch(ctx, permit, target, named) {
        return Some(Warning::ConfigNotUpdated(error));
    }
    if let Some(record) = state.in_use(which).cloned() {
        let naming = InUse {
            named: in_use::naming(which, &target.owner()),
            ..record
        };
        // Unsaved, the next read finds the tool's own record naming `target` and records it.
        if state.identified(which, naming, ctx.now()).changed {
            let _ = state::save(ctx, permit, state);
        }
    }
    None
}

/// A write to a tool's live login, made ready under the tool's own lock.
struct Readied {
    /// The login there now, byte for byte and as a document.
    before_raw: String,
    before: Value,
    /// What goes in its place.
    next: String,
    on_the_command_line: Option<Warning>,
}

/// The lock `tool` takes around its own writes to its live login, taken the way it
/// takes it, where it takes one. The caller holds it from before it readies a write until it
/// has recorded what it wrote.
fn write_lock(
    ctx: &Context,
    permit: Permit,
    tool: &'static dyn Provider,
) -> Result<Option<lock::Guard>> {
    Ok(tool
        .write_lock(ctx)
        .map(|dir| lock::acquire(permit, &dir, ctx.locks.write))
        .transpose()?)
}

/// Readies `incoming` to go in place of the login read earlier as `first`, which was
/// `signed_in`'s, with the tool's write lock already held. `label` is the account
/// `incoming` is.
///
/// Refuses, having written nothing, when somebody else is signed in by now, or when what
/// would be written could never be.
fn ready(
    ctx: &Context,
    tool: &'static dyn Provider,
    live: &provider::LiveStore,
    first: &Value,
    signed_in: &provider::Owner,
    incoming: &Value,
    label: &str,
) -> Result<Readied> {
    let which = tool.id();
    let (before_raw, before) = read_live(ctx, tool, live)?;
    // A refresh keeps the account, so an unchanged share of the document needs no second
    // question. A sign-in between the two reads would not keep it.
    if tool.slice(&before).ok() != tool.slice(first).ok()
        && !identify_document(ctx, tool, &before)?.same_login(signed_in)
    {
        return Err(Error::SignedInAccountChanged);
    }

    // Checked before anything is parked or written, so a change that could never be written
    // changes nothing.
    let next = to_body(
        &tool
            .splice(&before, incoming)
            .map_err(|e| shape(which, e))?,
    );
    // Asked once. The answer is about the backend that would take this write, so a login
    // living in a fallback file is not told it has the keychain's ceiling.
    let price = store::cost(&live.chain, &live.service, &next);
    if price.is_some_and(store::Cost::refused) {
        let price = price.expect("refused implies a ceiling");
        return Err(Error::CredentialTooLarge {
            tool: which,
            label: label.to_string(),
            bytes: price.needs,
            limit: price.limit,
        });
    }
    // Said once per write rather than hidden: the same bytes are visible to `ps` for the
    // length of one `security` call, which is the only way to write a login this size.
    let on_the_command_line =
        price
            .filter(|p| p.on_the_second_route())
            .map(|p| Warning::WrittenOnTheCommandLine {
                tool: which,
                bytes: p.needs,
                limit: p.limit,
            });
    Ok(Readied {
        before_raw,
        before,
        next,
        on_the_command_line,
    })
}

/// Whether a login of the tool's shape is in its live slot, read back after a write.
///
/// The tool may have rotated the token it was just given, which keeps the account and
/// changes the bytes: a login of its shape being there at all is the fact.
fn holds(
    tool: &'static dyn Provider,
    live: &provider::LiveStore,
) -> std::result::Result<bool, store::Error> {
    store::read_raw(&live.chain, &live.service).map(|now| {
        now.and_then(|raw| serde_json::from_str::<Value>(&raw).ok())
            .is_some_and(|document| tool.slice(&document).is_ok())
    })
}

/// What is running a tool whose running sessions keep the login they started with, which a
/// change of that login leaves on the login they had.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum StillHolding {
    /// Nothing is: no process runs the tool, or its sessions follow a change by themselves.
    Nothing,
    /// These are, by kind. Never empty.
    These(Vec<holder::Holding>),
    /// The process list could not be read, so nobody can say whether anything is. Said as
    /// such, because taken for nothing it would tell somebody with sessions open that none
    /// are.
    Unknown,
}

/// What is running `which`'s tool with the login it started with, by kind, as the process
/// list says.
pub(crate) fn still_holding(ctx: &Context, which: ProviderId) -> StillHolding {
    // What sits behind a store only delays sessions that follow by themselves, which hold
    // nothing here, so it is not read.
    let tool = match provider::of(which) {
        LoginKind::Document(tool) => tool,
        LoginKind::Folder(app) => {
            return match folder::open(ctx, app) {
                folder::Open::No => StillHolding::Nothing,
                folder::Open::Yes(listed) => StillHolding::These(vec![holder::Holding {
                    holder: *app.holder(),
                    pids: listed.iter().map(|one| one.pid).collect(),
                }]),
                folder::Open::Unknown(_) => StillHolding::Unknown,
            };
        }
    };
    let provider::Adoption::RestartRequired { program, holders } = tool.adoption(None) else {
        return StillHolding::Nothing;
    };
    match holder::find(ctx, program, holders) {
        None => StillHolding::Unknown,
        Some(holding) if holding.is_empty() => StillHolding::Nothing,
        Some(holding) => StillHolding::These(holding),
    }
}

/// Ask the service about the login going in, not only about the one coming out.
///
/// A switch used to ask twice about the login it was throwing away and never once about
/// the one it was installing. If that account's refresh chain had been revoked, signed out
/// elsewhere or refused by the service, the switch installed it, read it back, found a login
/// there and reported success; the person discovered they were signed out the next time
/// they ran the tool, with no login to go back to on either side.
///
/// A lapsed park is renewed rather than refused, which is the whole point of parking one.
/// That is a write, so it happens here, before anything is parked, while both copies are
/// still where they were.
#[allow(clippy::too_many_arguments)]
fn prove_incoming(
    ctx: &Context,
    permit: Permit,
    state: &mut State,
    tool: &'static dyn Provider,
    key: &Key,
    target: &Account,
    held: Park,
    incoming: Value,
) -> Result<(Park, Value)> {
    let label = state.typed(key);
    if held.askable_at(ctx.now()) {
        let credential = provider::Credential::new(key.provider, incoming.clone());
        match tool.verify(ctx, &credential) {
            Ok(found) if target.owned_by(&found) => return Ok((held, incoming)),
            Ok(other) => {
                return Err(Error::ParkedLoginBelongsElsewhere {
                    label,
                    who: crate::words::login(
                        key.provider,
                        &other.email,
                        other.email == target.email,
                    ),
                });
            }
            // The access token has lapsed earlier than the recorded expiry said it would.
            // Renewing settles it either way.
            Err(provider::ProviderError::Unauthorized) => {}
            Err(provider::ProviderError::ShapeUnexpected { detail, .. }) => {
                return Err(Error::ParkedCredentialCorrupt { label, detail });
            }
            Err(e) => {
                return Err(Error::IdentityUnverifiable {
                    tool: key.provider,
                    cause: crate::error::Cause::of_provider(&e),
                    detail: e.to_string(),
                });
            }
        }
    }

    // Lapsed, or refused as lapsed. Renew it and switch to what comes back.
    let Some(fresh) = renew::renew_one(ctx, permit, state, tool, key, &held)? else {
        return Err(Error::IdentityUnverifiable {
            tool: key.provider,
            cause: crate::error::Cause::Unreachable,
            detail: format!(
                "`{label}`'s parked login needs renewing and {} did not answer",
                key.provider.service()
            ),
        });
    };
    let document = park::load(ctx, tool, key, &fresh)?;
    Ok((fresh, document))
}

/// After a failed install, whether the copy just parked is the outgoing account's only login.
/// Once its old login is back in place, the copy is a second holder that Claude Code will
/// rotate past; if it could not be put back, the copy is all that is left of it.
fn only_copy_left(failure: &Error) -> bool {
    matches!(failure, Error::SwitchCorrupted { .. })
}

/// A provider saying a login is not the shape it keeps.
///
/// Only the shape errors reach the switch this way. Anything about the network keeps the
/// code the step it happened in gives it, because "could not reach Anthropic while proving
/// who the incoming login belongs to" and "could not reach Anthropic for usage" are the
/// same failure and not the same problem.
pub(super) fn shape(tool: ProviderId, error: provider::ProviderError) -> Error {
    match error {
        provider::ProviderError::ShapeUnexpected { detail, .. } => {
            Error::LiveCredentialShapeUnexpected { tool, detail }
        }
        provider::ProviderError::Unsupported { reason, .. } => {
            Error::LiveStoreUnsupported { tool, reason }
        }
        other => Error::LiveCredentialShapeUnexpected {
            tool,
            detail: other.to_string(),
        },
    }
}

/// A spliced document as bytes to write.
fn to_body(document: &Value) -> String {
    serde_json::to_string(document).expect("a credential document stays serialisable")
}

/// Write the new login, and if that fails, leave the old one in place.
///
/// A failed write often changes nothing, so the slot is read back before deciding a
/// rollback is needed. That read-back has three answers, not two. It used to have two, and
/// the missing one is the likeliest failure there is: on a machine whose keychain is
/// locked, the write fails, the read-back fails too, "could not read" was taken to mean
/// "the slot changed", a rollback was attempted, that failed as well, and the person was
/// told Pitboard could not put their login back and they should sign in again. Nothing had
/// been written and their login had never moved.
fn install_with(
    tool: ProviderId,
    write: impl Fn(&str) -> std::result::Result<(), store::Error>,
    read: impl Fn() -> std::result::Result<Option<String>, store::Error>,
    next: &str,
    before_raw: &str,
    from: &str,
    to: &str,
) -> Result<()> {
    let Err(failure) = write(next) else {
        return Ok(());
    };
    let rolled_back = |detail: String| Error::SwitchRolledBack {
        from: from.to_string(),
        to: to.to_string(),
        detail,
    };
    match read() {
        // Unchanged. The write never landed and there is nothing to undo.
        Ok(Some(now)) if now == before_raw => return Err(rolled_back(failure.to_string())),
        // Could not tell. Change nothing further and keep every copy: the caller leaves its
        // record of intent in place so a later run, with a store that answers, decides.
        Err(unreadable) => {
            return Err(Error::SwitchUnverified {
                tool,
                from: from.to_string(),
                to: to.to_string(),
                detail: format!("{failure}; {unreadable}"),
            });
        }
        // Changed, or gone. Put back what was there.
        _ => {}
    }
    match write(before_raw) {
        Ok(()) => Err(rolled_back(failure.to_string())),
        Err(rollback) => Err(Error::SwitchCorrupted {
            tool,
            from: from.to_string(),
            to: to.to_string(),
            detail: format!("{failure}; {rollback}"),
        }),
    }
}

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

    use std::cell::RefCell;

    fn failing(message: &str) -> store::Error {
        store::Error::Write(message.into())
    }

    /// After a sign-in outside Pitboard the record can still name the account a switch goes
    /// to. The switch moves the store from the login it found there, so the account it goes
    /// to comes to be in use then, and the login it found is the one parked.
    #[test]
    #[cfg_attr(
        windows,
        ignore = "W23: Claude Code's Credential Manager store, which a machine in memory plays"
    )]
    fn a_switch_after_a_sign_in_outside_puts_the_account_it_goes_to_in_use() {
        let m = harness::machine("records-both-logins");
        let mut state = state::load(&m.ctx).expect("state");
        let before = InUse::of(
            state.get(&m.key("there")).expect("enrolled"),
            "signed-in-over",
            harness::NOW - 3600,
        );
        state
            .in_use
            .insert(ProviderId::Claude.code().into(), before);
        state::save(&m.ctx, Permit::for_a_test(), &state).expect("saved");

        let settled = settle(&m.ctx, Permit::for_a_test(), None)
            .expect("nothing to recover")
            .0;
        switch(settled, &m.key("there")).expect("switched");

        let state = state::load(&m.ctx).expect("state");
        let there = state.get(&m.key("there")).expect("enrolled");
        assert_eq!(
            there.last_used_at,
            Some(harness::NOW),
            "in use from this switch"
        );
        assert_eq!(
            state.in_use(ProviderId::Claude).map(|r| r.login.as_str()),
            Some(
                provider::document(ProviderId::Claude)
                    .fingerprint(&harness::oauth("there-refresh", 30))
                    .as_str()
            )
        );
        assert!(
            state
                .get(&m.key("here"))
                .expect("enrolled")
                .parked
                .is_some()
        );
    }

    /// A session renewing Claude Code's login takes the refresh lock before it sends the
    /// refresh token, and saves the answer only where the login stored still holds the token
    /// it sent (the register's `refresh_lock`). A switch holds that lock from before it reads
    /// the outgoing login until it has recorded the one it installed, so a session renewing
    /// meanwhile waits: the login parked for the account switched from is never one a session
    /// spent, with its renewal lost at a save that found another login stored.
    #[test]
    #[cfg_attr(
        windows,
        ignore = "W23: Claude Code's Credential Manager store, which a machine in memory plays"
    )]
    fn a_session_renewing_the_outgoing_login_during_a_switch_waits_for_it() {
        use harness::{Session, lock_dir, renews_meanwhile, saves};
        let refreshing =
            |m: &harness::Machine| lock_dir(&provider::claude::paths::refresh_lock(&m.ctx));
        for point in ["switch.journal_written", "switch.park_recorded"] {
            let m = harness::machine(&format!("refresh-lock-{point}"));
            let keychain = std::sync::Arc::clone(m.mem.live());
            let session = Session::new();
            let settled = settle(&m.ctx, Permit::for_a_test(), None)
                .expect("nothing to recover")
                .0;

            let done = fault::meanwhile(
                point,
                renews_meanwhile(&m, std::sync::Arc::clone(&keychain), &session),
                || switch(settled, &m.key("there")),
            );
            saves(&m, &keychain, &session);

            assert!(
                session.waited.get(),
                "{point}: a session spent the refresh token Pitboard parked"
            );
            done.expect("switched");
            let state = state::load(&m.ctx).expect("state");
            let parked = state
                .get(&m.key("here"))
                .and_then(|account| account.parked.clone())
                .expect("the outgoing login is parked");
            assert_eq!(parked.login, store::fingerprint("here-refresh"), "{point}");
            assert!(
                !refreshing(&m).exists(),
                "{point}: the refresh lock is let go of"
            );
        }
    }

    #[test]
    fn a_successful_write_needs_no_rollback() {
        let written = RefCell::new(Vec::new());
        let result = install_with(
            ProviderId::Claude,
            |b| {
                written.borrow_mut().push(b.to_string());
                Ok(())
            },
            || unreachable!(),
            "new",
            "old",
            "a",
            "b",
        );
        assert!(result.is_ok());
        assert_eq!(*written.borrow(), vec!["new"]);
    }

    #[test]
    fn a_failed_write_that_changed_nothing_is_not_reported_as_a_lost_login() {
        let result = install_with(
            ProviderId::Claude,
            |_| Err(failing("keychain locked")),
            || Ok(Some("old".into())),
            "new",
            "old",
            "a",
            "b",
        );
        assert!(
            matches!(result, Err(Error::SwitchRolledBack { .. })),
            "the old login never left, so the user must not be told to sign in again"
        );
    }

    #[test]
    fn a_half_write_is_rolled_back() {
        let slot = RefCell::new("old".to_string());
        let result = install_with(
            ProviderId::Claude,
            |b| {
                if b == "new" {
                    *slot.borrow_mut() = "garbled".into();
                    Err(failing("interrupted"))
                } else {
                    *slot.borrow_mut() = b.to_string();
                    Ok(())
                }
            },
            || Ok(Some(slot.borrow().clone())),
            "new",
            "old",
            "a",
            "b",
        );
        assert!(matches!(result, Err(Error::SwitchRolledBack { .. })));
        assert_eq!(
            *slot.borrow(),
            "old",
            "the previous login must be back in place"
        );
    }

    /// The likeliest failure of all, and the one that used to produce the most alarming
    /// message Pitboard has. A locked keychain fails the write, fails the read-back, and
    /// would have failed the rollback too; "could not read" was taken to mean "the slot
    /// changed", so the person was told their login could not be put back. Nothing had been
    /// written and it had never moved.
    #[test]
    fn a_store_that_cannot_be_read_back_is_not_a_lost_login() {
        let writes = RefCell::new(0);
        let result = install_with(
            ProviderId::Claude,
            |_| {
                *writes.borrow_mut() += 1;
                Err(failing("the keychain is locked"))
            },
            || Err(store::Error::Unreadable("the keychain is locked".into())),
            "new",
            "old",
            "a",
            "b",
        );
        assert!(
            matches!(result, Err(Error::SwitchUnverified { .. })),
            "not knowing is its own answer, and must not read as a lost login"
        );
        assert_eq!(
            *writes.borrow(),
            1,
            "and nothing further is written into a store that cannot be read"
        );
    }

    #[test]
    fn only_a_failed_rollback_after_a_change_is_reported_as_corruption() {
        let result = install_with(
            ProviderId::Claude,
            |_| Err(failing("disk full")),
            || Ok(Some("garbled".into())),
            "new",
            "old",
            "a",
            "b",
        );
        assert!(matches!(result, Err(Error::SwitchCorrupted { .. })));
    }

    #[test]
    fn a_copy_is_kept_after_a_failed_install_only_when_it_is_all_that_is_left() {
        let (from, to, detail) = ("a".to_string(), "b".to_string(), String::new());
        assert!(!only_copy_left(&Error::SwitchRolledBack {
            from: from.clone(),
            to: to.clone(),
            detail: detail.clone(),
        }));
        assert!(only_copy_left(&Error::SwitchCorrupted {
            tool: ProviderId::Claude,
            from,
            to,
            detail
        }));
    }
}