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
//! A machine to run changes against: two accounts of one tool, stores in memory, services
//! that answer from a script, a clock that stands still, and Claude Code's locks given up on
//! at once.
//!
//! Shared by the tests that kill a change partway ([`super::crash`]), the tests that make
//! one refuse ([`super::refusals`]), the tests of what a sign-in enrols ([`super::enroll`]),
//! and the tests of what a change refused over its name still settles ([`crate::service`]),
//! because all of them need the same starting shape:
//! one account signed in, one parked and ready, and the tool's own files where the engine
//! expects them. There is one for each tool, and the invariants in [`hold`] are asked of
//! every one of them through the provider boundary, because what must be true after a
//! crash is a fact about parking a login and not about any one tool's.

use super::*;
use crate::api::scripted::ScriptedApi;
use crate::provider::Owner;
use crate::provider::ProviderId;
use crate::provider::claude::api::Renewed;
use crate::provider::claude::paths as claude;
use crate::service::Permit;

use crate::host::memory::MemoryHost;
use crate::state::Account;
use crate::time::{Clock, FixedClock};
use serde_json::json;
use std::collections::HashSet;
use std::sync::Arc;
use std::sync::mpsc::RecvTimeoutError;

pub(crate) const NOW: i64 = 1_760_000_000;

/// Every place a change can be killed, named the way the code names it.
pub(crate) const POINTS: [&str; 6] = [
    "switch.journal_written",
    "switch.park_stored",
    "switch.park_recorded",
    "switch.installed",
    "switch.recorded",
    "switch.config_updated",
];

// Every place a move of an app's login can be killed, by the name the code gives it.
pub(crate) const FOLDER_POINTS: [&str; 30] = [
    "leave.recorded",
    "leave.keys_kept",
    "leave.keys_out",
    "leave.jar_out",
    "leave.item_out",
    "leave.verified",
    "leave.done",
    "arrive.recorded",
    "arrive.aside_kept",
    "arrive.keys_cleared",
    "arrive.item_aside",
    "arrive.item_in",
    "arrive.jar_in",
    "arrive.keys_in",
    "arrive.verified",
    "arrive.done",
    "settings.temp_written",
    "settle.keys_back",
    "settle.aside_named",
    "settle.aside_kept",
    "settle.keys_cleared",
    "settle.item_back",
    "settle.item_aside",
    "settle.saved",
    "give_up.aside_named",
    "give_up.item_aside",
    "give_up.done",
    "start.aside_kept",
    "start.keys_cleared",
    "start.saved",
];

// The tools whose login is a document, for a test's match on a document machine.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Tool {
    Claude,
    Codex,
}

impl Tool {
    pub(crate) fn of(which: ProviderId) -> Tool {
        match which {
            ProviderId::Claude => Tool::Claude,
            ProviderId::Codex => Tool::Codex,
            ProviderId::Desktop => panic!("{which} keeps no login document"),
        }
    }
}

pub(crate) struct Machine {
    pub(crate) ctx: Context,
    pub(crate) mem: Arc<MemoryHost>,
    pub(crate) api: Arc<ScriptedApi>,
    root: PathBuf,
    /// The keychain item Claude Code's login is in, on a Claude Code machine.
    pub(crate) service: String,
    /// Which tool's accounts this machine holds.
    pub(crate) which: ProviderId,
}

impl Machine {
    /// Where the tool's own files are, for a test that needs to change one.
    pub(crate) fn ctx_home(&self) -> PathBuf {
        self.root.clone()
    }

    /// The live login, read the way the tool reads it.
    pub(crate) fn live(&self) -> Option<Value> {
        provider::document(self.which)
            .read_live(&self.ctx)
            .ok()
            .flatten()
            .map(|credential| credential.raw)
    }

    /// Replace the live login, the way the tool itself would write it.
    pub(crate) fn sign_in(&self, document: &Value) {
        let live = provider::document(self.which)
            .live(&self.ctx)
            .expect("a store to write to");
        store::write_raw(
            &live.chain,
            Permit::for_a_test(),
            &live.service,
            &document.to_string(),
        )
        .expect("the live login is written");
    }

    pub(crate) fn key(&self, label: &str) -> Key {
        Key::new(self.which, label)
    }

    /// From now on the live login's store misbehaves this way: the keychain item for Claude
    /// Code, the `auth.json` file for Codex.
    pub(crate) fn fault_live(&self, fault: store::memory::Fault) {
        let (store, service) = self.live_store();
        store.fault(&service, fault);
    }

    /// The store the live login is in, and its name there, for a test that has to fault it
    /// from inside a change.
    pub(crate) fn live_store(&self) -> (Arc<store::memory::MemoryStore>, String) {
        let live = provider::document(self.which)
            .live(&self.ctx)
            .expect("a live store");
        let store = match Tool::of(self.which) {
            Tool::Claude => Arc::clone(self.mem.live()),
            Tool::Codex => self
                .mem
                .file_at(provider::codex::paths::auth_file(&self.ctx)),
        };
        (store, live.service)
    }
}

impl Drop for Machine {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.root);
    }
}

pub(crate) fn oauth(refresh: &str, expires_in_days: i64) -> Value {
    json!({
        "accessToken": format!("access-{refresh}"),
        "refreshToken": refresh,
        "expiresAt": (NOW + 3600) * 1000,
        "refreshTokenExpiresAt": (NOW + expires_in_days * 86_400) * 1000,
        "scopes": ["user:profile", "user:inference"],
    })
}

pub(crate) fn document(refresh: &str) -> Value {
    json!({
        "claudeAiOauth": oauth(refresh, 30),
        "organizationUuid": "org-of-the-outgoing-account",
        "mcpOAuth": {"some-server": {"token": "unrelated"}},
    })
}

/// [`document`] with its access token expired a minute ago.
pub(crate) fn lapsed(refresh: &str) -> Value {
    let mut login = document(refresh);
    login["claudeAiOauth"]["expiresAt"] = json!((NOW - 60) * 1000);
    login
}

pub(crate) fn owner(uuid: &str) -> Owner {
    Owner {
        account_uuid: uuid.into(),
        email: format!("{uuid}@example.com"),
        organization_uuid: format!("org-{uuid}"),
    }
}

/// Two accounts: `here` is signed in, `there` is parked and ready. The shape every switch
/// starts from.
pub(crate) fn machine(name: &str) -> Machine {
    let root = std::env::temp_dir().join(format!(
        "pitboard-crash-{name}-{}-{:?}",
        std::process::id(),
        std::thread::current().id()
    ));
    let _ = std::fs::remove_dir_all(&root);
    std::fs::create_dir_all(&root).expect("a scratch home");

    let mem = MemoryHost::new();
    let api = ScriptedApi::new();
    let ctx = Context::new(root.clone())
        .with_pitboard_home(root.join(".pitboard"))
        .with_memory_stores(Arc::clone(&mem))
        .with_scripted_api(Arc::clone(&api))
        .with_clock(Arc::new(FixedClock::at(NOW)) as Arc<dyn Clock>)
        // A test holding one of Claude Code's locks lets go of it at a point, not after a while.
        .with_lock_waiting(1, std::time::Duration::from_millis(1));

    // Claude Code's own files: the live credential, and the config a switch rewrites.
    let service = claude::live_service(&ctx);
    mem.live()
        .plant(&service, &document("here-refresh").to_string());
    std::fs::write(
        root.join(".claude.json"),
        json!({
            "oauthAccount": {
                "accountUuid": "here",
                "emailAddress": "here@example.com",
                "organizationUuid": "org-here",
            },
            "cachedArtifactRoster": {"org": "org-here"},
            "numStartups": 7,
        })
        .to_string(),
    )
    .expect("a config file");

    api.owned_by("access-here-refresh", owner("here"));
    api.owned_by("access-there-refresh", owner("there"));

    // `there` holds a parked login, written the way a switch would have written it.
    std::fs::create_dir_all(root.join(".pitboard")).expect("a Pitboard home");
    let parked_service = park::reserve(&ctx, Permit::for_a_test(), "there").expect("a free name");
    let parked = park::store_at(
        &ctx,
        Permit::for_a_test(),
        provider::document(crate::provider::ProviderId::Claude),
        &parked_service,
        &oauth("there-refresh", 30),
    )
    .expect("parked");

    let mut state = State::default();
    state.accounts.push(account("here", "here", None));
    state.accounts.push(account("there", "there", Some(parked)));
    record_in_use(
        &ctx,
        &mut state,
        ProviderId::Claude,
        &document("here-refresh"),
    );
    state::save(&ctx, Permit::for_a_test(), &state).expect("saved");

    Machine {
        ctx,
        mem,
        api,
        root,
        service,
        which: ProviderId::Claude,
    }
}

/// [`machine`], where `elsewhere`, enrolled with nothing parked, has since signed in to
/// Claude Code outside Pitboard over `here`, whose only login that was, as `/login` does:
/// its login in the keychain and its account in the config.
pub(crate) fn signed_in_outside(name: &str) -> Machine {
    let m = machine(name);
    m.api
        .owned_by("access-elsewhere-refresh", owner("elsewhere"));
    let mut state = state::load(&m.ctx).expect("state");
    state.accounts.push(account("elsewhere", "elsewhere", None));
    state::save(&m.ctx, Permit::for_a_test(), &state).expect("saved");
    m.sign_in(&document("elsewhere-refresh"));
    config_names(&m, "elsewhere");
    m
}

/// Claude Code's config naming `who`, as another Claude Code process that started or signed
/// in on `who`'s login writes it, with the login in the keychain left as it was.
pub(crate) fn config_names(m: &Machine, who: &str) {
    let path = m.root.join(".claude.json");
    let mut config: Value =
        serde_json::from_str(&std::fs::read_to_string(&path).expect("a config")).expect("JSON");
    let owner = owner(who);
    config["oauthAccount"] = json!({
        "accountUuid": owner.account_uuid,
        "emailAddress": owner.email,
        "organizationUuid": owner.organization_uuid,
    });
    std::fs::write(&path, config.to_string()).expect("the config is written");
}

/// The activity log's lines of `verb`, as subject and outcome.
pub(crate) fn audit_lines(m: &Machine, verb: &str) -> Vec<(String, String)> {
    crate::audit::read(&m.ctx, 100)
        .into_iter()
        .filter(|entry| entry.verb == verb)
        .map(|entry| (entry.subject, entry.outcome))
        .collect()
}

/// `state.json` as it is on disk, with when it was last written.
pub(crate) fn state_file(m: &Machine) -> (Vec<u8>, std::time::SystemTime) {
    let path = home::dir(&m.ctx).join("state.json");
    let written = std::fs::metadata(&path)
        .and_then(|meta| meta.modified())
        .expect("a state file");
    (std::fs::read(&path).expect("a state file"), written)
}

/// Where OpenAI puts its own claims in a standard token.
const OPENAI: &str = "https://api.openai.com/auth";

/// A Codex login as `codex login` writes one, for the account `who`.
///
/// The access token is unique to the refresh token so every login has its own, which is
/// what the scripted usage answers are keyed by.
pub(crate) fn codex_login(who: &str, refresh: &str) -> Value {
    json!({
        "auth_mode": "chatgpt",
        "OPENAI_API_KEY": null,
        "tokens": {
            "id_token": provider::jwt::unsigned(&json!({
                "email": format!("{who}@example.com"),
                "exp": NOW + 3600,
                OPENAI: {
                    "chatgpt_account_id": who,
                    "chatgpt_user_id": format!("user-{who}"),
                    "chatgpt_plan_type": "pro",
                },
            })),
            "access_token": codex_access(refresh),
            "refresh_token": refresh,
            "account_id": who,
        },
        "last_refresh": "2025-10-09T08:00:00Z",
    })
}

/// The identity Codex's own claims give the account `who`: the ChatGPT account with the
/// person inside it.
pub(crate) fn codex_id(who: &str) -> String {
    format!("{who}_user-{who}")
}

/// The access token [`codex_login`] carries for this refresh token.
pub(crate) fn codex_access(refresh: &str) -> String {
    provider::jwt::unsigned(&json!({"exp": NOW + 10 * 86_400, "for": refresh}))
}

/// `who`'s Codex account, as enrolling it from [`codex_login`] writes one: its ChatGPT
/// account is its workspace, as Codex's own claims give it.
pub(crate) fn codex_account(label: &str, who: &str, parked: Option<Park>) -> Account {
    Account {
        last_used_at: None,
        replaced_at: None,
        plan: Some("Pro".into()),
        label: label.into(),
        id: codex_id(who),
        account_uuid: codex_id(who),
        email: format!("{who}@example.com"),
        parked,
        detail: state::Detail::Codex {
            workspace_id: Some(who.into()),
        },
    }
}

pub(crate) use crate::desktop_testing::{HOME, WORK};

pub(crate) const STRANGER: crate::desktop_testing::Person = crate::desktop_testing::Person {
    uuid: "0b7e2c44-2222-4d1f-8a35-91c0de77aa01",
    session: "stranger-session",
};

// Claude's data folder on a machine `desktop_machine` made.
pub(crate) fn data(m: &Machine) -> PathBuf {
    m.ctx_home().join("claude/data")
}

pub(crate) fn settled(m: &Machine) -> Settled {
    settle(&m.ctx, Permit::for_a_test(), Some(ProviderId::Desktop))
        .expect("nothing of a document to recover")
        .0
}

// Every entry under `root`, by its path from there, with each file's bytes.
pub(crate) fn tree(root: &std::path::Path) -> Vec<(PathBuf, Option<Vec<u8>>)> {
    fn walk(
        root: &std::path::Path,
        dir: &std::path::Path,
        out: &mut Vec<(PathBuf, Option<Vec<u8>>)>,
    ) {
        let Ok(entries) = std::fs::read_dir(dir) else {
            return;
        };
        for entry in entries.flatten() {
            let path = entry.path();
            let within = path
                .strip_prefix(root)
                .expect("under the root")
                .to_path_buf();
            let kind = std::fs::symlink_metadata(&path).expect("metadata");
            if kind.is_symlink() {
                let target = std::fs::read_link(&path).expect("a link");
                out.push((within, Some(target.to_string_lossy().as_bytes().to_vec())));
            } else if kind.is_dir() {
                out.push((within, None));
                walk(root, &path, out);
            } else {
                out.push((within, Some(std::fs::read(&path).expect("a file"))));
            }
        }
    }
    let mut found = Vec::new();
    walk(root, root, &mut found);
    found.sort();
    found
}

pub(crate) type Stat = (PathBuf, Option<u64>, u64, Option<std::time::SystemTime>);

pub(crate) type Snapshot = (
    Vec<u8>,
    Vec<u8>,
    Vec<(PathBuf, Option<Vec<u8>>)>,
    Vec<String>,
    Vec<Stat>,
);

// Claude's folder and each entry under it, links not followed: inode, size and when changed.
pub(crate) fn stats(root: &std::path::Path) -> Vec<Stat> {
    let stat = |within: PathBuf| {
        let found = std::fs::symlink_metadata(root.join(&within)).ok();
        let inode = crate::host::fs::testing::inode(&root.join(&within)).ok();
        let size = found.as_ref().map_or(0, std::fs::Metadata::len);
        (
            within,
            inode,
            size,
            found.and_then(|kind| kind.modified().ok()),
        )
    };
    let mut found = vec![stat(PathBuf::new())];
    found.extend(tree(root).into_iter().map(|(within, _)| stat(within)));
    found
}

// What a refusal must leave as it was: the index, `pending`, Claude's folder and `parks`.
pub(crate) fn snapshot(m: &Machine) -> Snapshot {
    let home = home::dir(&m.ctx);
    (
        std::fs::read(home.join("state.json")).unwrap_or_default(),
        std::fs::read(home.join("pending")).unwrap_or_default(),
        tree(&data(m)),
        store::folder::list(&m.ctx)
            .expect("parks")
            .unwrap_or_default(),
        stats(&data(m)),
    )
}

pub(crate) fn unchanged(m: &Machine, before: &Snapshot, why: &str) {
    let now = snapshot(m);
    assert!(now.0 == before.0, "{why}: state.json changed");
    assert!(now.1 == before.1, "{why}: `pending` changed");
    assert!(now.2 == before.2, "{why}: Claude's folder changed");
    assert!(now.3 == before.3, "{why}: `parks` changed");
    assert!(
        now.4 == before.4,
        "{why}: an entry of Claude's folder was touched"
    );
}

// Claude closed and signed in to `work`, enrolled as `desktop/work` by the real `enroll`.
pub(crate) fn desktop_machine(name: &str) -> Machine {
    let root = std::env::temp_dir().join(format!(
        "pitboard-desktop-{name}-{}-{:?}",
        std::process::id(),
        std::thread::current().id()
    ));
    let _ = std::fs::remove_dir_all(&root);
    std::fs::create_dir_all(&root).expect("a scratch home");
    let mem = MemoryHost::new();
    let api = ScriptedApi::new();
    let ctx = Context::new(root.clone())
        .with_pitboard_home(root.join(".pitboard"))
        .with_memory_stores(Arc::clone(&mem))
        .with_scripted_api(Arc::clone(&api))
        .with_clock(Arc::new(FixedClock::at(NOW)) as Arc<dyn Clock>)
        .with_awaited_every(std::time::Duration::from_millis(2))
        .with_scratch_claude(root.join("claude"));
    let m = Machine {
        ctx,
        mem,
        api,
        root,
        service: String::new(),
        which: ProviderId::Desktop,
    };
    m.claude().signed_in_as(&WORK);
    let (settled, _) = settle(&m.ctx, Permit::for_a_test(), Some(ProviderId::Desktop))
        .expect("nothing to recover");
    enroll(settled, &m.key("work"), None).expect("`work` enrolled");
    m
}

// `work` in use and `home` parked, by the real sign-in inside Claude and the real switch.
pub(crate) fn desktop_pair(name: &str) -> Machine {
    let m = desktop_machine(name);
    sign_in_inside(&m, "home", &HOME).expect("`home` added, `work` parked");
    let (settled, _) = settle(&m.ctx, Permit::for_a_test(), Some(ProviderId::Desktop))
        .expect("nothing to recover");
    switch(settled, &m.key("work")).expect("back to `work`");
    m
}

// `pitboard enroll desktop/<label> --sign-in`, with Claude opened, signed in to `who` and quit
// once the wait has said it saw Claude open.
pub(crate) fn sign_in_inside(
    m: &Machine,
    label: &str,
    who: &crate::desktop_testing::Person,
) -> Result<(Enrolled, Vec<Warning>)> {
    let typed = format!("desktop/{label}");
    let pitboard = crate::service::Pitboard::new(m.ctx.clone());
    let watched = pitboard
        .sign_in_watched(&typed)
        .map_err(|failed| failed.error)?;
    let said = watched.said();
    let claude = m.claude();
    claude.opens();
    let wait = std::time::Duration::from_secs(10);
    loop {
        match said.within(wait) {
            Ok(line) if line == "Claude is open.\n" => break,
            Ok(_) => {}
            Err(why) => panic!("the wait never said Claude is open: {why}"),
        }
    }
    claude.signs_in(who);
    claude.reports();
    claude.quits();
    // Its lines end with its thread, which `finish` would otherwise wait for without end.
    loop {
        match said.within(wait) {
            Ok(_) => {}
            Err(RecvTimeoutError::Disconnected) => break,
            Err(RecvTimeoutError::Timeout) => panic!("the wait never ended once Claude quit"),
        }
    }
    let login = watched.finish()?;
    pitboard
        .enroll_signed_in(&typed, login)
        .map(|done| (done.value, done.warnings))
        .map_err(|failed| failed.error)
}

// A kill is a panic here, so a temporary it left is this process's own, which a sweep
// leaves alone: renamed to a dead process's, as the one a killed run leaves is.
pub(crate) fn as_a_dead_runs(m: &Machine) {
    let data = m.root.join("claude/data");
    for entry in std::fs::read_dir(&data).into_iter().flatten().flatten() {
        let name = entry.file_name().to_string_lossy().into_owned();
        if crate::atomic::temp_owner(&name) == Some(std::process::id()) {
            let dead = name.replace(
                &format!(".{}.", std::process::id()),
                &format!(".{}.", i32::MAX - 1),
            );
            std::fs::rename(entry.path(), data.join(dead)).expect("renamed");
        }
    }
}

// Every folder that holds `who`'s session: Claude's, or one under `parks`.
pub(crate) fn whereabouts(m: &Machine, who: &crate::desktop_testing::Person) -> Vec<String> {
    sessions(m)
        .into_iter()
        .filter(|(_, login)| *login == who.login())
        .map(|(place, _)| place)
        .collect()
}

fn sessions(m: &Machine) -> Vec<(String, String)> {
    let LoginKind::Folder(app) = provider::of(m.which) else {
        return Vec::new();
    };
    let mut places = vec![("Claude".to_string(), m.root.join("claude/data/Cookies"))];
    for name in store::folder::list(&m.ctx)
        .ok()
        .flatten()
        .unwrap_or_default()
    {
        let jar = store::folder::item(&m.ctx, &name, app.items()[0]);
        places.push((name, jar));
    }
    places
        .into_iter()
        .filter(|(_, jar)| jar.exists())
        .filter_map(|(place, jar)| Some((place, app.session(&m.ctx, &jar).ok()??.login)))
        .collect()
}

// A resting state: no move recorded, no temporary of Pitboard's in Claude's folder, no
// `pending` line for a folder the index names, and Claude's folder holding nobody, or one
// account whole under its own name.
pub(crate) fn rested(m: &Machine, after: &str) {
    let LoginKind::Folder(app) = provider::of(m.which) else {
        panic!("{after}: a folder tool");
    };
    // The next command's sweep, which drops each `pending` line the index has taken up.
    recover(m).unwrap_or_else(|e| panic!("{after}: {e}"));
    let state = state::load(&m.ctx).expect("state");
    assert!(
        state.moving(m.which).is_none(),
        "{after}: a move still waits"
    );
    // One session, one place: Claude's folder or one folder under `parks`.
    let mut seen = HashSet::new();
    for (place, login) in sessions(m) {
        assert!(
            seen.insert(login),
            "{after}: the session in {place} is also somewhere else"
        );
    }
    let data = m.root.join("claude/data");
    for entry in std::fs::read_dir(&data).into_iter().flatten().flatten() {
        let name = entry.file_name().to_string_lossy().into_owned();
        assert!(
            crate::atomic::temp_owner(&name).is_none(),
            "{after}: {name} was left in Claude's folder"
        );
    }
    let pending = std::fs::read_to_string(home::dir(&m.ctx).join("pending")).unwrap_or_default();
    for line in pending.lines() {
        let name = line.strip_prefix("folder ").unwrap_or(line);
        assert!(!state.names(name), "{after}: `pending` still lists {name}");
    }
    if !data.exists() {
        return;
    }
    let settings = app.settings(&data).expect("settings");
    let jar = data.join(app.items()[0]);
    if !jar.exists() {
        let left: Vec<String> = app
            .items()
            .iter()
            .filter(|item| data.join(item).exists())
            .map(|item| (*item).to_string())
            .collect();
        let listed = store::folder::list(&m.ctx)
            .ok()
            .flatten()
            .unwrap_or_default()
            .into_iter()
            .filter_map(|name| store::folder::manifest(&m.ctx, &name).ok().flatten())
            .any(|manifest| !left.is_empty() && manifest.left_in_folder == left);
        assert!(
            left.is_empty() && settings.account_keys(app).is_empty() || listed,
            "{after}: Claude's folder has no jar and holds {left:?}"
        );
        return;
    }
    let Some(session) = app.session(&m.ctx, &jar).expect("the jar reads") else {
        return;
    };
    let named = settings.named(app);
    for account in state.accounts.iter().filter(|a| a.provider() == m.which) {
        let holds_it = state
            .in_use(m.which)
            .is_some_and(|record| record.login == session.login)
            && state
                .account_in_use(m.which)
                .is_some_and(|a| a.id == account.id);
        if holds_it {
            assert_eq!(
                named.as_deref(),
                Some(account.account_uuid.as_str()),
                "{after}: {}'s session beside another name",
                account.label
            );
        }
    }
}

impl Machine {
    pub(crate) fn claude(&self) -> crate::desktop_testing::FakeClaude {
        crate::desktop_testing::FakeClaude::on(
            Arc::clone(&self.mem),
            &self.ctx,
            crate::desktop_testing::JarAs::StandIn,
        )
    }
}

/// The same shape for Codex: `here` is signed in, `there` is parked and ready, and OpenAI
/// answers for both.
pub(crate) fn codex_machine(name: &str) -> Machine {
    let root = std::env::temp_dir().join(format!(
        "pitboard-crash-codex-{name}-{}-{:?}",
        std::process::id(),
        std::thread::current().id()
    ));
    let _ = std::fs::remove_dir_all(&root);
    std::fs::create_dir_all(root.join(".codex")).expect("a scratch codex home");

    let mem = MemoryHost::new();
    let api = ScriptedApi::new();
    let ctx = Context::new(root.clone())
        .with_pitboard_home(root.join(".pitboard"))
        .with_codex_home(root.join(".codex").to_string_lossy().into_owned())
        .with_memory_stores(Arc::clone(&mem))
        .with_scripted_api(Arc::clone(&api))
        .with_clock(Arc::new(FixedClock::at(NOW)) as Arc<dyn Clock>);
    let machine = Machine {
        ctx,
        mem,
        api,
        root,
        service: String::new(),
        which: ProviderId::Codex,
    };
    machine.sign_in(&codex_login("here", "here-refresh"));
    for refresh in ["here-refresh", "there-refresh"] {
        machine.api.using(
            &codex_access(refresh),
            crate::usage::Snapshot {
                windows: Vec::new(),
                observed_at: Some(NOW),
                answered_at: Some(NOW),
                lists_every_limit: false,
                source: crate::usage::Source::Live,
            },
        );
    }

    std::fs::create_dir_all(machine.root.join(".pitboard")).expect("a Pitboard home");
    let parked_service =
        park::reserve(&machine.ctx, Permit::for_a_test(), &codex_id("there")).expect("a free name");
    let parked = park::store_at(
        &machine.ctx,
        Permit::for_a_test(),
        provider::document(ProviderId::Codex),
        &parked_service,
        &codex_login("there", "there-refresh"),
    )
    .expect("parked");

    let mut state = State::default();
    state.accounts.push(codex_account("here", "here", None));
    state
        .accounts
        .push(codex_account("there", "there", Some(parked)));
    record_in_use(
        &machine.ctx,
        &mut state,
        ProviderId::Codex,
        &codex_login("here", "here-refresh"),
    );
    state::save(&machine.ctx, Permit::for_a_test(), &state).expect("saved");
    machine
}

/// `here`'s login on `login`, recorded as its service said it now, with what the tool's own
/// record names: what enrolling `here` while signed in records. When `here` came to be in use
/// stays unrecorded, so no test starts inside the minutes the automatic switch leaves an
/// account to settle.
pub(crate) fn record_in_use(ctx: &Context, state: &mut State, which: ProviderId, login: &Value) {
    let here = state
        .get(&Key::new(which, "here"))
        .expect("`here` is enrolled");
    let found = InUse {
        owner: Some(here.owner()),
        login: provider::document(which).fingerprint(login),
        known_at: NOW,
        named: in_use::named(ctx, which),
    };
    state.in_use.insert(which.code().to_string(), found);
}

/// A login of the account `who` as this machine's tool writes one, with the service taught
/// whose it is where the tool has to ask.
pub(crate) fn login_of(m: &Machine, who: &str, refresh: &str) -> Value {
    match Tool::of(m.which) {
        Tool::Claude => {
            m.api.owned_by(&format!("access-{refresh}"), owner(who));
            document(refresh)
        }
        Tool::Codex => codex_login(who, refresh),
    }
}

/// A sign-in the tool finished as `who`, left where a finished one leaves its login.
pub(crate) fn signed_in(m: &Machine, who: &str, refresh: &str) -> SignIn {
    planted(
        &m.ctx,
        Permit::for_a_test(),
        provider::document(m.which),
        login_of(m, who, refresh),
    )
    .expect("a sign-in")
}

/// The service answers a renewal of the login on `refresh` with one on `renewed`.
pub(crate) fn renews(m: &Machine, refresh: &str, renewed: &str) {
    match Tool::of(m.which) {
        Tool::Claude => {
            m.api.renews(
                refresh,
                Renewed {
                    access_token: format!("access-{renewed}"),
                    refresh_token: Some(renewed.into()),
                    expires_in: 3600,
                    refresh_token_expires_in: Some(30 * 86_400),
                    scopes: None,
                    at: None,
                },
            );
        }
        Tool::Codex => {
            m.api.codex_renews(
                refresh,
                provider::codex::api::Fresh {
                    id_token: None,
                    access_token: Some(codex_access(renewed)),
                    refresh_token: Some(renewed.into()),
                    at: Some(NOW),
                },
            );
        }
    }
}

/// What a Claude Code session did while renewing the login a store holds, as
/// [`renews_meanwhile`] plays it.
#[derive(Default)]
pub(crate) struct Session {
    /// It found Claude Code's refresh lock held, so it waited.
    pub(crate) waited: std::cell::Cell<bool>,
    /// The refresh token it sent, and the login it was renewed to, to save once Claude Code's
    /// write lock is let go of.
    saving: std::cell::RefCell<Option<(String, Value)>>,
}

impl Session {
    pub(crate) fn new() -> std::rc::Rc<Session> {
        std::rc::Rc::new(Session::default())
    }
}

/// Where `target`'s lock is, as [`lock::acquire`] and proper-lockfile make it.
pub(crate) fn lock_dir(target: &std::path::Path) -> PathBuf {
    PathBuf::from(format!("{}.lock", target.display()))
}

/// What Claude Code's write lock guards.
pub(crate) fn write_target(m: &Machine) -> PathBuf {
    provider::document(ProviderId::Claude)
        .write_lock(&m.ctx)
        .expect("Claude Code takes one")
}

/// Takes Claude Code's write lock at the moment it is called, as a session writing its
/// credentials does.
pub(crate) fn takes_the_write_lock(m: &Machine) -> impl FnOnce() + 'static {
    let writing = lock_dir(&write_target(m));
    move || {
        let parent = writing.parent().expect("the storage directory");
        std::fs::create_dir_all(parent).expect("the storage directory is made");
        std::fs::create_dir(&writing).expect("the write lock is free");
    }
}

/// Lets go of Claude Code's write lock at the moment it is called, as a session that has
/// written does.
pub(crate) fn lets_go_of_the_write_lock(m: &Machine) -> impl FnOnce() + 'static {
    let writing = lock_dir(&write_target(m));
    move || std::fs::remove_dir(&writing).expect("the session lets go")
}

/// A session renewing the login `store` holds at the moment it is called, as Claude Code
/// 2.1.294 does (the register's `refresh_lock`): the keychain's, or the file's for a session
/// that signed in with the file. It takes the refresh lock, as a directory, without waiting
/// here: held, it waits, which is all that happens. Taken, it sends the refresh token stored,
/// which spends it, then saves the renewed login, with an access token good for an hour,
/// under the write lock where it can take it, and otherwise once [`saves`] says it is let go
/// of.
pub(crate) fn renews_meanwhile(
    m: &Machine,
    store: Arc<store::memory::MemoryStore>,
    session: &std::rc::Rc<Session>,
) -> impl FnOnce() + 'static {
    let (service, api) = (m.service.clone(), Arc::clone(&m.api));
    let refreshing = lock_dir(&claude::refresh_lock(&m.ctx));
    let writing = lock_dir(&write_target(m));
    let session = std::rc::Rc::clone(session);
    move || {
        let parent = refreshing.parent().expect("the storage directory");
        std::fs::create_dir_all(parent).expect("the storage directory is made");
        match std::fs::create_dir(&refreshing) {
            Ok(()) => {}
            Err(held) if held.kind() == std::io::ErrorKind::AlreadyExists => {
                session.waited.set(true);
                return;
            }
            Err(error) => panic!("the refresh lock: {error}"),
        }
        let held = store.peek(&service).expect("a login is stored");
        let mut login: Value = serde_json::from_str(&held).expect("JSON");
        let sent = login["claudeAiOauth"]["refreshToken"]
            .as_str()
            .expect("a refresh token")
            .to_string();
        api.renew_trouble(&sent, crate::api::scripted::Trouble::InvalidGrant);
        login["claudeAiOauth"]["refreshToken"] = json!(format!("{sent}-by-a-session"));
        login["claudeAiOauth"]["accessToken"] = json!(format!("access-{sent}-by-a-session"));
        login["claudeAiOauth"]["expiresAt"] = json!((NOW + 3600) * 1000);
        *session.saving.borrow_mut() = Some((sent, login));
        if std::fs::create_dir(&writing).is_ok() {
            save(&store, &service, &session);
            let _ = std::fs::remove_dir(&writing);
            let _ = std::fs::remove_dir(&refreshing);
        }
    }
}

/// The session's save, held up by Claude Code's write lock, once that is let go of: only
/// where `store` still holds the refresh token it sent, as Claude Code's save compares it, so
/// nothing where that login has gone.
pub(crate) fn saves(m: &Machine, store: &store::memory::MemoryStore, session: &Session) {
    if session.saving.borrow().is_none() {
        return;
    }
    save(store, &m.service, session);
    let _ = std::fs::remove_dir(lock_dir(&claude::refresh_lock(&m.ctx)));
}

fn save(store: &store::memory::MemoryStore, service: &str, session: &Session) {
    let Some((sent, login)) = session.saving.borrow_mut().take() else {
        return;
    };
    let holds = store
        .peek(service)
        .and_then(|held| serde_json::from_str::<Value>(&held).ok())
        .is_some_and(|held| held["claudeAiOauth"]["refreshToken"] == sent.as_str());
    if holds {
        store.plant(service, &login.to_string());
    }
}

/// A limit of `kind`, `percent` used, resetting an hour from now: what Anthropic answers of
/// one, for the tests of what Pitboard switches by itself.
pub(crate) fn window(kind: &str, percent: f64) -> crate::usage::Window {
    crate::usage::Window {
        kind: kind.into(),
        scope: None,
        percent,
        resets_at: Some(NOW + 3600),
        is_active: true,
        severity: None,
        length_seconds: crate::usage::anthropic_window_length(kind),
    }
}

/// Anthropic's usage answer for a five-hour limit `percent` used, resetting an hour from now,
/// in the shape `GET /api/oauth/usage` gives it and Claude Code caches it.
pub(crate) fn usage_answer(percent: f64) -> Value {
    let resets_at = jiff::Timestamp::from_second(NOW + 3600).expect("a time");
    json!({"limits": [{"kind": "session", "percent": percent, "resets_at": resets_at.to_string()}]})
}

/// Claude Code's usage cache, put in its config as 2.1.294 writes one: stamped with `here`,
/// the account the config names, whichever login `answer` was asked with.
pub(crate) fn cache_usage(m: &Machine, answer: Value) {
    let path = m.root.join(".claude.json");
    let mut config: Value =
        serde_json::from_str(&std::fs::read_to_string(&path).expect("a config")).expect("JSON");
    config["cachedUsageUtilization"] = json!({
        "fetchedAtMs": NOW * 1000,
        "accountUuid": "here",
        "utilization": answer,
    });
    std::fs::write(&path, config.to_string()).expect("the config is written");
}

pub(crate) fn account(label: &str, uuid: &str, parked: Option<Park>) -> Account {
    Account {
        last_used_at: None,
        replaced_at: None,
        plan: None,
        label: label.into(),
        id: uuid.into(),
        account_uuid: uuid.into(),
        email: format!("{uuid}@example.com"),
        parked,
        detail: state::Detail::Claude {
            organization_uuid: format!("org-{uuid}"),
            oauth_account: json!({
                "accountUuid": uuid,
                "emailAddress": format!("{uuid}@example.com"),
                "organizationUuid": format!("org-{uuid}"),
            }),
        },
    }
}

/// `who`'s login to the organisation `org`, enrolled as `label` by this version.
pub(crate) fn in_organisation(label: &str, who: &str, org: &str, parked: Option<Park>) -> Account {
    let owner = Owner {
        organization_uuid: org.into(),
        ..owner(who)
    };
    Account {
        last_used_at: None,
        replaced_at: None,
        plan: None,
        label: label.into(),
        id: state::new_id(ProviderId::Claude, &owner),
        account_uuid: owner.account_uuid,
        email: owner.email,
        parked,
        detail: state::Detail::Claude {
            organization_uuid: owner.organization_uuid,
            oauth_account: json!({"accountUuid": who, "organizationUuid": org}),
        },
    }
}

/// Everything that must be true after a killed change has been recovered, whatever the
/// change was and wherever it died.
pub(crate) fn hold(m: &Machine, after: &str) {
    let state = state::load(&m.ctx)
        .unwrap_or_else(|e| panic!("{after}: the state file must still parse, got {e}"));
    match provider::of(m.which) {
        LoginKind::Document(_) => {}
        LoginKind::Folder(app) => {
            return hold_folder(m, after, &state, app, Holds::all());
        }
    }

    // Nothing in the vault that the state does not name. An item nobody names holds a live
    // refresh token that no command will ever renew or delete, and on macOS nothing can
    // even list it.
    let named: HashSet<&str> = state
        .accounts
        .iter()
        .filter_map(|a| a.parked.as_ref())
        .map(|p| p.service.as_str())
        .chain(state.discarded.iter().map(|d| d.service.as_str()))
        .collect();
    for service in m.mem.vault().services() {
        assert!(
            named.contains(service.as_str()),
            "{after}: {service} holds a login nothing on this machine names"
        );
    }

    // One refresh token, one place. A token in two places is a token one holder will rotate
    // past, which ends the login for the other; for a tool whose sign-out revokes what it
    // finds, it is a token the person's own next sign-out kills in both.
    let tool = provider::document(m.which);
    let mut seen: HashSet<String> = HashSet::new();
    let mut fingerprints = Vec::new();
    for service in m.mem.vault().services() {
        let raw = m.mem.vault().peek(&service).expect("just listed");
        let value: Value = serde_json::from_str(&raw).expect("a park is JSON");
        fingerprints.push((service, tool.fingerprint(&value)));
    }
    let live = m.live();
    if let Some(document) = &live {
        fingerprints.push(("the live slot".into(), tool.fingerprint(document)));
    }
    for (place, fingerprint) in fingerprints {
        assert!(
            seen.insert(fingerprint.clone()),
            "{after}: the login in {place} is also somewhere else"
        );
    }

    // Every account can still be got back to. Signed in, or holding a login that can be
    // restored, or holding nothing and saying so, but never holding one that has expired.
    let live_uuid = live
        .and_then(|document| {
            tool.identify(&m.ctx, &provider::Credential::new(m.which, document))
                .ok()
        })
        .map(|found| found.account_uuid);
    for a in &state.accounts {
        if Some(&a.account_uuid) == live_uuid.as_ref() {
            continue;
        }
        if let Some(park) = &a.parked {
            assert!(
                park.restorable_at(NOW),
                "{after}: {} holds a login that can no longer be restored",
                a.label
            );
            assert!(
                m.mem.vault().peek(&park.service).is_some(),
                "{after}: {} names a park that is not in the vault",
                a.label
            );
        }
    }
}

// `hold`, for a test where `forget`, `uninstall` or the test itself deleted what was planted.
pub(crate) fn hold_where_deleted(m: &Machine, after: &str) {
    let state = state::load(&m.ctx)
        .unwrap_or_else(|e| panic!("{after}: the state file must still parse, got {e}"));
    let LoginKind::Folder(app) = provider::of(m.which) else {
        panic!("{after}: a folder tool");
    };
    let holds = Holds {
        nothing_deleted: false,
        ..Holds::all()
    };
    hold_folder(m, after, &state, app, holds);
}

// `hold`, for a test that puts one session in two places on purpose (rows 14 to 20).
pub(crate) fn hold_where_twice(m: &Machine, after: &str) {
    let state = state::load(&m.ctx)
        .unwrap_or_else(|e| panic!("{after}: the state file must still parse, got {e}"));
    let LoginKind::Folder(app) = provider::of(m.which) else {
        panic!("{after}: a folder tool");
    };
    let holds = Holds {
        one_place: false,
        beside_its_name: false,
        ..Holds::all()
    };
    hold_folder(m, after, &state, app, holds);
}

// The checks of `hold` a test may leave out, each for what the test itself does.
#[derive(Clone, Copy)]
struct Holds {
    // check 3: each session in one place
    one_place: bool,
    // check 5: no session in Claude's folder beside another account's name
    beside_its_name: bool,
    // check 8: nothing planted was deleted
    nothing_deleted: bool,
}

impl Holds {
    fn all() -> Holds {
        Holds {
            one_place: true,
            beside_its_name: true,
            nothing_deleted: true,
        }
    }
}

// What must hold of a tool whose login is its app's files, after every step of a change.
fn hold_folder(
    m: &Machine,
    after: &str,
    state: &State,
    app: &'static dyn provider::folder::Folder,
    holds: Holds,
) {
    // Every folder under `parks` is named, and no folder's name reaches the vault.
    let parks = store::folder::list(&m.ctx)
        .expect("parks listed")
        .unwrap_or_default();
    let pending = std::fs::read_to_string(home::dir(&m.ctx).join("pending")).unwrap_or_default();
    for name in &parks {
        let named =
            state.names(name) || pending.lines().any(|line| line == format!("folder {name}"));
        assert!(named, "{after}: {name} under parks is named by nothing");
    }
    for dropped in &state.discarded {
        if parks.contains(&dropped.service) {
            assert_eq!(
                dropped.kind,
                ParkKind::Folder,
                "{after}: {}",
                dropped.service
            );
        }
    }
    for touch in m.mem.trail() {
        assert!(
            !(touch.store == "vault"
                && (touch.service.starts_with("pitboard-park-desktop_")
                    || touch.service.starts_with("pitboard-aside-"))),
            "{after}: {touch:?} asked the vault of a folder"
        );
    }

    // Every account is in use, holds a park whose folder holds its session, or holds nothing.
    let in_use = state.account_in_use(m.which).map(Account::key);
    for account in state.accounts.iter().filter(|a| a.provider() == m.which) {
        let Some(park) = &account.parked else {
            continue;
        };
        if in_use.as_ref() == Some(&account.key()) {
            continue;
        }
        // A move under way holds this park: where its jar is, recovery reads.
        if state
            .moving(m.which)
            .is_some_and(|moving| moving.park == park.service)
        {
            continue;
        }
        let manifest = store::folder::manifest(&m.ctx, &park.service)
            .ok()
            .flatten()
            .unwrap_or_else(|| panic!("{after}: {} names a park with no manifest", account.label));
        assert_eq!(
            manifest.login.as_deref(),
            Some(park.login.as_str()),
            "{after}"
        );
        let jar = store::folder::item(&m.ctx, &park.service, app.items()[0]);
        let session = app.session(&m.ctx, &jar).expect("its jar reads");
        assert_eq!(
            session.map(|s| s.login),
            Some(park.login.clone()),
            "{after}"
        );
    }

    // One session, one place: Claude's folder or one folder under `parks`.
    if holds.one_place {
        let mut seen = HashSet::new();
        for (place, login) in sessions(m) {
            assert!(
                seen.insert(login),
                "{after}: the session in {place} is also somewhere else"
            );
        }
    }

    // Nothing was deleted: Claude makes a store only where one is missing, so never these bytes.
    let data = m.root.join("claude/data");
    if holds.nothing_deleted {
        for (store, file) in crate::desktop_testing::STORES {
            let within = std::path::Path::new(store).join(file);
            let places = std::iter::once(data.join(&within)).chain(
                parks
                    .iter()
                    .map(|name| store::folder::item(&m.ctx, name, store).join(file)),
            );
            let found = places
                .filter(|place| {
                    std::fs::read(place).is_ok_and(|held| held == WORK.session.as_bytes())
                })
                .count();
            assert_eq!(
                found,
                1,
                "{after}: `work`'s {} is in {found} places",
                within.display()
            );
        }
    }

    // What is not an account's, in the settings and in the folder, is as `plant` wrote it.
    if !data.exists() {
        return;
    }
    let config = data.join("config.json");
    assert!(config.exists(), "{after}: config.json is gone");
    let settings = app
        .settings(&data)
        .unwrap_or_else(|e| panic!("{after}: config.json: {e:?}"));

    // The name key, where there is one, names every account the index records the session in
    // Claude's folder for: in use, parked, or moving.
    let jar = data.join(app.items()[0]);
    let session = jar
        .exists()
        .then(|| app.session(&m.ctx, &jar).ok().flatten())
        .flatten();
    if holds.beside_its_name
        && let (Some(session), Some(named)) = (session, settings.named(app))
    {
        let tool = m.which;
        let in_use = state
            .in_use(tool)
            .filter(|record| record.login == session.login)
            .and_then(|_| state.account_in_use(tool));
        let parked = state.accounts.iter().filter(|a| {
            a.provider() == tool
                && a.parked
                    .as_ref()
                    .is_some_and(|park| park.login == session.login)
        });
        let moving = state
            .moving(tool)
            .filter(|moving| moving.login == session.login)
            .and_then(|moving| state.by_id(tool, &moving.id));
        for account in in_use.into_iter().chain(parked).chain(moving) {
            assert_eq!(
                account.account_uuid, named,
                "{after}: {}'s session beside another name",
                account.label
            );
        }
    }
    let others: Vec<(&str, &str)> = settings
        .body
        .iter()
        .filter(|(key, _)| !app.keys().contains(&key.as_str()))
        // Claude's own while it runs.
        .filter(|(key, _)| key != "updaterRunningInstance")
        .map(|(key, value)| (key.as_str(), value.get()))
        .collect();
    assert_eq!(
        others,
        [("locale", "\"en-US\""), ("userThemeMode", "\"dark\"")],
        "{after}"
    );
    assert!(
        crate::host::fs::testing::is_private(&config).expect("its mode"),
        "{after}: config.json's mode changed"
    );
    for (stays, held) in [
        ("Preferences", "{}"),
        ("Cache/Cache_Data/index", WORK.session),
    ] {
        assert_eq!(
            std::fs::read_to_string(data.join(stays)).ok().as_deref(),
            Some(held),
            "{after}: {stays}"
        );
    }
}

/// Recovery, run the way the next command runs it.
pub(crate) fn recover(m: &Machine) -> Result<()> {
    settle(&m.ctx, Permit::for_a_test(), None).map(|_| ())
}