pitboard-core 0.22.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
//! Keeping parked logins alive, so their usage can be asked and they do not lapse. A parked
//! login is held by Pitboard alone, so renewing it puts no second holder on its refresh
//! chain. The login signed in is Claude Code's, and is never renewed here.
//!
//! Anthropic spends the refresh token it is sent as it answers, so what keeps the answer is
//! asked first: its name is written down, the vault takes the login as it is under that name,
//! and `state.json` takes a save. The answer then goes over that item. Where the save after it
//! fails, the next run takes the fresh item back before anything is due.

use super::{journal, purge, try_exclusive};
use crate::context::Context;
use crate::error::{Error, Result};
use crate::permit::Permit;
use crate::provider::{LoginKind, Provider};
use crate::schedule::{Job, StoreAnswer};
use crate::state::{Key, Park, ParkKind, State};
use crate::{park, state};
use serde_json::Value;

/// Renewed this long before its access token expires, so a read just after still answers.
const AHEAD_SECONDS: i64 = 120;

/// What Claude Code asks for when a login records no scopes of its own.
pub(crate) const DEFAULT_SCOPES: [&str; 6] = [
    "user:profile",
    "user:inference",
    "user:sessions:claude_code",
    "user:mcp_servers",
    "user:file_upload",
    "user:plugins",
];

#[derive(Debug)]
#[non_exhaustive]
pub enum Renewal {
    Renewed,
    /// Anthropic refuses the login for good; it has been dropped.
    Refused,
    /// Anthropic could not be reached or asked to slow down; tried again next time.
    Deferred,
    // Nothing was sent: the answer could not have been kept. The park stays as it was.
    Held(Unwritable),
    Failed(Error),
}

impl Renewal {
    pub fn code(&self) -> &'static str {
        match self {
            Renewal::Renewed => "renewed",
            Renewal::Refused => "parked_login_refused",
            Renewal::Deferred => "renewal_deferred",
            Renewal::Held(held) if held.disk_full => "renewal_held_disk_full",
            Renewal::Held(_) => "renewal_held",
            Renewal::Failed(e) => e.code(),
        }
    }
}

// What refused a write before a renewal was sent.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Unwritable {
    pub code: &'static str,
    pub detail: String,
    pub disk_full: bool,
}

impl Unwritable {
    fn of(refused: &Error) -> Unwritable {
        Unwritable {
            code: refused.code(),
            detail: refused.to_string(),
            disk_full: refused.disk_full(),
        }
    }
}

/// Why a parked login is being renewed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Due {
    /// What a reading needs: a park whose access token has lapsed cannot be asked about.
    /// This is the one `status` does, and it is the read path's own requirement rather
    /// than a job it does on the side.
    ToBeAsked,
    /// What keeps a park usable: a refresh token has a finite life, and one that lapses
    /// costs a browser sign-in. Also covers everything `ToBeAsked` covers.
    ToStayAlive,
}

impl Due {
    fn covers(self, held: &Park, now: i64) -> bool {
        if !held.restorable_at(now) {
            return false;
        }
        let access_lapsed = !held.askable_at(now + AHEAD_SECONDS);
        match self {
            Due::ToBeAsked => access_lapsed,
            Due::ToStayAlive => {
                access_lapsed
                    || held
                        .refresh_expires_at
                        .is_some_and(|at| state::renewal_due(at, now))
            }
        }
    }
}

/// Renew every parked login whose access token has expired or is about to. Nothing is done
/// while another Pitboard run holds the lock or a switch waits to be finished: a renewal
/// replaces the refresh token, and nothing may install the old copy meanwhile. A move of the
/// parks cut short is finished first, as a change finishes it, so no park is written into the
/// form it is leaving, and nothing is renewed where the store refuses that.
pub(crate) fn renew_parked(ctx: &Context, permit: Permit) -> Vec<(Key, Renewal)> {
    renew_due(ctx, permit, Due::ToBeAsked)
}

/// The same, for whichever reason. A run the schedule started keeps what the store refused it,
/// the move's finish among it, under the lock ([`crate::schedule::ran`]).
pub(crate) fn renew_due(ctx: &Context, permit: Permit, due: Due) -> Vec<(Key, Renewal)> {
    let Some(_exclusive) = try_exclusive(ctx, permit) else {
        return Vec::new();
    };
    if journal::pending(ctx) {
        return Vec::new();
    }
    let Ok(mut state) = state::load(ctx) else {
        return Vec::new();
    };
    // Where only the schedule runs, no change comes to finish it, and the parks would lapse.
    if state
        .vault
        .as_ref()
        .is_some_and(|vault| vault.moving_to.is_some())
        && let Err(refused) = super::vault::finish(ctx, permit, &mut state)
    {
        crate::schedule::ran(ctx, permit, Job::Renew, StoreAnswer::of(&refused));
        return Vec::new();
    }
    let now = ctx.now();
    let covered = |state: &State| -> Vec<(Key, &'static dyn Provider, Park)> {
        state
            .accounts
            .iter()
            .filter_map(|a| {
                let tool = match crate::provider::of(a.provider()) {
                    LoginKind::Document(tool) => tool,
                    // An app's login is never renewed.
                    LoginKind::Folder(_) => return None,
                };
                // A tool whose own program is run for it is run only to be asked about, never on
                // a schedule of Pitboard's.
                if a.provider().asks() == crate::provider::Asks::ItsProgram
                    && due == Due::ToStayAlive
                {
                    return None;
                }
                let held = a.parked.as_ref()?;
                due.covers(held, now).then(|| (a.key(), tool, held.clone()))
            })
            .collect()
    };
    // A fresh copy an earlier run could not record goes back first, so no spent token is sent.
    let swept = crate::pending::sweep(ctx, permit, &mut state);
    let mut to_renew = covered(&state);
    // A park that copies the login in use holds the refresh token its tool is about to
    // present, and renewing it would spend that token under the tool. It is dropped instead,
    // as the next change would drop it. Looked for only when something is due, because
    // finding one reads each tool's login.
    if !to_renew.is_empty() {
        let _ = super::drop_live_twins(ctx, permit, &mut state);
        to_renew = covered(&state);
    }
    let mut outcomes = Vec::new();
    if let Err(refused) = swept {
        let why = Unwritable::of(&refused);
        outcomes.extend(
            to_renew
                .into_iter()
                .map(|(key, _, _)| (key, Renewal::Held(why.clone()))),
        );
        crate::schedule::ran(ctx, permit, Job::Renew, StoreAnswer::renewing(&outcomes));
        return outcomes;
    }
    let mut ready = Vec::new();
    for (key, tool, held) in to_renew {
        match prepare(ctx, permit, &state, tool, &key, &held) {
            Ok(Prepared::Ready(document, copy)) => ready.push((key, tool, held, document, copy)),
            Ok(Prepared::Held(why)) => outcomes.push((key, Renewal::Held(why))),
            Err(e) => outcomes.push((key, Renewal::Failed(e))),
        }
    }
    crate::fault::point("renew.prepared");
    let saved = match ready.is_empty() {
        true => Ok(()),
        false => state::save(ctx, permit, &state),
    };
    if let Err(refused) = saved {
        let why = Unwritable::of(&refused);
        for (key, _, _, _, copy) in ready {
            let _ = crate::store::vault_delete(ctx, permit, &copy);
            outcomes.push((key, Renewal::Held(why.clone())));
        }
        crate::schedule::ran(ctx, permit, Job::Renew, StoreAnswer::renewing(&outcomes));
        return outcomes;
    }
    // Each renewal is a round trip that can take as long as the request timeout, so they
    // are asked together. What comes back is then written one at a time: the state file is
    // one file, and the order of writes to it is not something to leave to chance.
    let asked: Vec<_> = std::thread::scope(|scope| {
        let handles: Vec<_> = ready
            .into_iter()
            .map(|(key, tool, held, document, copy)| {
                let ctx = &*ctx;
                let handle = scope.spawn({
                    let key = key.clone();
                    move || ask(ctx, permit, tool, &key, document)
                });
                (key, tool, held, copy, handle)
            })
            .collect();
        handles
            .into_iter()
            .map(|(key, tool, held, copy, handle)| {
                let answer = handle.join().unwrap_or_else(|_| {
                    Err(Error::RenewalFailed {
                        label: key.typed(),
                        cause: None,
                        detail: "the renewal thread stopped".into(),
                    })
                });
                (key, tool, held, copy, answer)
            })
            .collect()
    });
    for (key, tool, held, copy, answer) in asked {
        let outcome = apply(ctx, permit, &mut state, tool, &key, &held, &copy, answer)
            .unwrap_or_else(Renewal::Failed);
        outcomes.push((key, outcome));
    }
    // Nothing is deleted that the file on disk still names.
    if !state.discarded.is_empty() && state::save(ctx, permit, &state).is_ok() {
        purge(ctx, permit, &mut state);
    }
    crate::schedule::ran(ctx, permit, Job::Renew, StoreAnswer::renewing(&outcomes));
    outcomes
}

enum Prepared {
    // The login, and the vault item its answer goes into, which holds it as it is for now.
    Ready(Value, String),
    Held(Unwritable),
}

fn prepare(
    ctx: &Context,
    permit: Permit,
    state: &State,
    tool: &'static dyn Provider,
    key: &Key,
    held: &Park,
) -> Result<Prepared> {
    let document = park::load(ctx, tool, key, held)?;
    // On macOS with PITBOARD_NO_ARGV, every Codex park is past what the vault takes.
    park::price(ctx, key.provider, &key.typed(), &held.service, &document)?;
    let id = state.get(key).map(|a| a.id.clone()).unwrap_or_default();
    let copy = match park::reserve(ctx, permit, &id) {
        Ok(copy) => copy,
        Err(refused) => return Ok(Prepared::Held(Unwritable::of(&refused))),
    };
    // A renewed login is this one with new tokens of the same length.
    if let Err(refused) = park::store_at(ctx, permit, tool, &copy, &document) {
        let _ = crate::store::vault_delete(ctx, permit, &copy);
        return Ok(Prepared::Held(Unwritable::of(&refused)));
    }
    Ok(Prepared::Ready(document, copy))
}

/// What one round trip produced, before anything is written down.
struct Asked {
    /// The parked document with fresh tokens already folded in, the way the tool that owns
    /// it stores its own after renewing, so it reads the same once restored.
    renewed: Option<Value>,
    /// The service refuses this login for good.
    refused: bool,
}

/// The part of a renewal that talks to Anthropic. Touches no shared state, so several run
/// at once.
fn ask(
    ctx: &Context,
    permit: Permit,
    tool: &'static dyn Provider,
    key: &Key,
    document: Value,
) -> Result<Asked> {
    let credential = crate::provider::Credential::new(key.provider, document);
    match tool.renew(ctx, permit, &credential) {
        Ok(fresh) => Ok(Asked {
            renewed: Some(fresh.raw),
            refused: false,
        }),
        Err(crate::provider::ProviderError::InvalidGrant { .. }) => Ok(Asked {
            renewed: None,
            refused: true,
        }),
        // Kept, as Claude Code keeps it: the login works again once the hold ends.
        Err(crate::provider::ProviderError::OnHold { link, .. }) => Err(Error::AccountOnHold {
            tool: key.provider,
            login: crate::error::Unidentified::Parked { label: key.typed() },
            link,
        }),
        // Unreachable or asked to slow down: nothing is written and the next run tries.
        Err(
            crate::provider::ProviderError::Network { .. }
            | crate::provider::ProviderError::RateLimited { .. },
        ) => Ok(Asked {
            renewed: None,
            refused: false,
        }),
        Err(e) => Err(Error::RenewalFailed {
            label: key.typed(),
            cause: Some(crate::error::Cause::of_provider(&e)),
            detail: e.to_string(),
        }),
    }
}

/// Renew one parked login now, for a caller that needs it usable rather than merely
/// present. Returns the park that replaces it, or `None` when Anthropic could not be
/// reached or asked for less traffic, which is a reason to stop and not a reason to act.
pub(super) fn renew_one(
    ctx: &Context,
    permit: Permit,
    state: &mut State,
    tool: &'static dyn Provider,
    key: &Key,
    held: &Park,
) -> Result<Option<Park>> {
    let (document, copy) = match prepare(ctx, permit, state, tool, key, held)? {
        Prepared::Ready(document, copy) => (document, copy),
        Prepared::Held(why) => return Err(held_error(key, why)),
    };
    if let Err(refused) = state::save(ctx, permit, state) {
        let _ = crate::store::vault_delete(ctx, permit, &copy);
        return Err(refused);
    }
    let asked = ask(ctx, permit, tool, key, document);
    match apply(ctx, permit, state, tool, key, held, &copy, asked)? {
        Renewal::Renewed => Ok(state.get(key).and_then(|a| a.parked.clone())),
        Renewal::Refused => Err(Error::ParkedLoginRefused {
            tool: key.provider,
            label: state.typed(key),
        }),
        Renewal::Deferred => Ok(None),
        Renewal::Held(why) => Err(held_error(key, why)),
        Renewal::Failed(e) => Err(e),
    }
}

// The copy holds the login as it was, which the park holds too, and no file names it.
fn drop_copy(ctx: &Context, permit: Permit, state: &mut State, copy: &str) {
    if crate::store::vault_delete(ctx, permit, copy).is_err() {
        state.discard(copy, ParkKind::Vault);
    }
}

fn held_error(key: &Key, why: Unwritable) -> Error {
    Error::RenewalFailed {
        label: key.typed(),
        cause: None,
        detail: why.detail,
    }
}

/// The part that writes: one at a time, in the order the accounts are listed.
#[allow(clippy::too_many_arguments)]
fn apply(
    ctx: &Context,
    permit: Permit,
    state: &mut State,
    tool: &'static dyn Provider,
    key: &Key,
    held: &Park,
    copy: &str,
    asked: Result<Asked>,
) -> Result<Renewal> {
    let asked = match asked {
        Ok(asked) => asked,
        Err(e) => {
            drop_copy(ctx, permit, state, copy);
            return Err(e);
        }
    };
    if asked.refused {
        // Refused, not spent: nothing was taken from it. One `repair` gave back is left for
        // the Pitboard that wrote it, which will be refused the same way.
        state.release(&held.service);
        drop_copy(ctx, permit, state, copy);
        state::save(ctx, permit, state)?;
        return Ok(Renewal::Refused);
    }
    let Some(next) = asked.renewed else {
        drop_copy(ctx, permit, state, copy);
        return Ok(Renewal::Deferred);
    };
    // A copy `repair` gave back is left for the Pitboard that wrote it only while it is
    // unused, and the service has just spent it. Saved as used before the answer is
    // written, so a run killed between writing the answer and recording it leaves a spent
    // copy the next change deletes, rather than one it lets go for a Pitboard that would
    // present a spent token. A save that fails here must not stop the answer being written:
    // that is the account's only working login now.
    if state.is_foreign(&held.service) {
        state.used_here(&held.service);
        let _ = state::save(ctx, permit, state);
    }
    crate::fault::point("renew.answered");
    // The vault took the login under this name a moment ago, so once more if it refuses now.
    let store = || park::store_at(ctx, permit, tool, copy, &next);
    let parked = match store().or_else(|_| store()) {
        Ok(parked) => parked,
        Err(e) => {
            // Anthropic has already spent the old refresh token, so the copy Pitboard holds
            // is dead whatever happens next. Dropping it now means status stops offering a
            // login that cannot work and says to sign in again instead.
            state.discard(&held.service, ParkKind::Vault);
            drop_copy(ctx, permit, state, copy);
            let _ = state::save(ctx, permit, state);
            return Err(Error::RenewalFailed {
                label: state.typed(key),
                // The service answered; it is this machine that could not keep the answer.
                cause: None,
                detail: e.to_string(),
            });
        }
    };
    crate::fault::point("renew.park_stored");
    // The renewal spent the copy it replaces, whoever wrote it, so that one is discarded
    // rather than merely replaced.
    state.discard(&held.service, ParkKind::Vault);
    state.park(key, parked);
    // A save that fails leaves the fresh copy on Pitboard's list, and the next run takes it back.
    state::save(ctx, permit, state)?;
    Ok(Renewal::Renewed)
}

#[cfg(test)]
#[allow(
    clippy::disallowed_methods,
    reason = "a test sets up its scratch files as a person or a tool would"
)]
mod tests {
    use super::*;
    use crate::api::scripted::{Asked as Question, ScriptedApi, Trouble};
    use crate::context::ScratchMachine;
    use crate::host::memory::MemoryHost;
    use crate::provider::claude::api::Renewed;
    use crate::state::Account;
    use crate::store::memory::Fault;
    use crate::time::FixedClock;
    use serde_json::json;
    use std::sync::Arc;

    const NOW: i64 = 1_760_000_000;

    struct Scratch {
        ctx: Context,
        mem: Arc<MemoryHost>,
        api: Arc<ScriptedApi>,
        home: tempfile::TempDir,
    }

    fn machine(name: &str) -> Scratch {
        let home = tempfile::Builder::new()
            .prefix(&format!("pitboard-renew-{name}-"))
            .tempdir()
            .expect("a scratch home");
        let ScratchMachine {
            ctx,
            host: mem,
            api,
        } = ScratchMachine::at(home.path(), |ctx| {
            ctx.with_pitboard_home(home.path().to_path_buf())
                .with_clock(Arc::new(FixedClock::at(NOW)) as Arc<dyn crate::time::Clock>)
        });
        Scratch {
            ctx,
            mem,
            api,
            home,
        }
    }

    fn oauth(refresh: &str, access_expires_at: i64) -> Value {
        json!({
            "refreshToken": refresh,
            "accessToken": "a",
            "expiresAt": access_expires_at * 1000,
            "refreshTokenExpiresAt": (NOW + 30 * 86_400) * 1000
        })
    }

    /// One account holding one park, written the way a switch would have written it.
    fn with_park(m: &Scratch, label: &str, refresh: &str, access_expires_at: i64) -> Park {
        park_in(&m.ctx, label, refresh, access_expires_at)
    }

    /// The same, in the Pitboard directory `ctx` names.
    fn park_in(ctx: &Context, label: &str, refresh: &str, access_expires_at: i64) -> Park {
        let service = park::reserve(ctx, Permit::for_a_test(), "acc").expect("a free name");
        let park = park::store_at(
            ctx,
            Permit::for_a_test(),
            crate::provider::document(crate::provider::ProviderId::Claude),
            &service,
            &oauth(refresh, access_expires_at),
        )
        .expect("parked");
        let mut state = State::default();
        state.accounts.push(Account {
            last_used_at: None,
            replaced_at: None,
            plan: None,
            label: label.into(),
            id: "acc".into(),
            account_uuid: "acc".into(),
            email: "me@example.com".into(),
            detail: state::Detail::Claude {
                organization_uuid: "org".into(),
                oauth_account: json!({}),
            },
            parked: Some(park.clone()),
        });
        state::save(ctx, Permit::for_a_test(), &state).expect("saved");
        park
    }

    fn fresh(refresh: &str) -> Renewed {
        Renewed {
            access_token: "new-access".into(),
            refresh_token: Some(refresh.into()),
            expires_in: 3600,
            refresh_token_expires_in: Some(30 * 86_400),
            scopes: None,
            at: None,
            owner: None,
        }
    }

    fn outcome(outcomes: &[(Key, Renewal)], label: &str) -> String {
        outcomes
            .iter()
            .find(|(key, _)| key.label == label)
            .map(|(_, r)| r.code().to_string())
            .unwrap_or_else(|| "not attempted".into())
    }

    /// The lifetimes a renewal answers with are relative, so what they are added to decides
    /// when the login expires. A machine whose clock is wrong must not get an expiry to
    /// match, or every status renews the park again and rotates the refresh chain on a loop.
    #[test]
    fn a_renewed_expiry_is_measured_from_anthropics_clock_not_this_machines() {
        let m = machine("anchored");
        with_park(&m, "work", "old", NOW - 1);
        // This machine believes it is two hours later than it is.
        let server_now = NOW - 7200;
        m.api.renews(
            "old",
            Renewed {
                access_token: "new-access".into(),
                refresh_token: Some("new".into()),
                expires_in: 3600,
                refresh_token_expires_in: Some(30 * 86_400),
                scopes: None,
                at: Some(server_now),
                owner: None,
            },
        );

        renew_parked(&m.ctx, Permit::for_a_test());

        let park = state::load(&m.ctx)
            .expect("state")
            .get(&Key::new(crate::provider::ProviderId::Claude, "work"))
            .expect("account")
            .parked
            .clone()
            .expect("renewed");
        assert_eq!(
            park.access_expires_at,
            Some(server_now + 3600),
            "an hour after the answer, not an hour after this machine's idea of now"
        );
        assert_eq!(park.refresh_expires_at, Some(server_now + 30 * 86_400));
    }

    /// An answer with no `Date` leaves the local clock as all there is, which is what it
    /// always was.
    #[test]
    fn an_answer_with_no_clock_of_its_own_falls_back_to_this_machines() {
        let m = machine("unanchored");
        with_park(&m, "work", "old", NOW - 1);
        m.api.renews("old", fresh("new"));

        renew_parked(&m.ctx, Permit::for_a_test());

        let park = state::load(&m.ctx)
            .expect("state")
            .get(&Key::new(crate::provider::ProviderId::Claude, "work"))
            .expect("account")
            .parked
            .clone()
            .expect("renewed");
        assert_eq!(park.access_expires_at, Some(NOW + 3600));
    }

    /// The budget question, asked of the code rather than of a stopwatch: a park whose
    /// access token is still good is not a reason to talk to Anthropic at all.
    #[test]
    fn a_park_that_is_not_due_is_not_asked_about() {
        let m = machine("not-due");
        with_park(&m, "work", "r", NOW + 3600);

        let outcomes = renew_parked(&m.ctx, Permit::for_a_test());

        assert!(outcomes.is_empty());
        assert_eq!(m.api.calls(), 0, "nothing was due, so nothing was asked");
    }

    #[test]
    fn a_due_park_is_renewed_and_the_spent_copy_is_dropped() {
        let m = machine("renewed");
        let before = with_park(&m, "work", "old", NOW - 1);
        m.api.renews("old", fresh("new"));

        let outcomes = renew_parked(&m.ctx, Permit::for_a_test());

        assert_eq!(outcome(&outcomes, "work"), "renewed");
        assert_eq!(m.api.asked(), vec![Question::Renew("old".into())]);
        let state = state::load(&m.ctx).expect("state");
        let now = state
            .get(&Key::new(crate::provider::ProviderId::Claude, "work"))
            .expect("account")
            .parked
            .clone()
            .expect("park");
        assert_ne!(now.service, before.service, "a renewal takes a new name");
        assert_eq!(
            m.mem.vault().services(),
            vec![now.service],
            "the spent copy is deleted, not left behind"
        );
    }

    /// The answer that ends a park. The account keeps its label and its email, so the way
    /// back is one sign-in rather than an enrolment.
    #[test]
    fn a_login_anthropic_no_longer_accepts_is_dropped() {
        let m = machine("refused");
        with_park(&m, "work", "old", NOW - 1);
        m.api.renew_trouble("old", Trouble::InvalidGrant);

        let outcomes = renew_parked(&m.ctx, Permit::for_a_test());

        assert_eq!(outcome(&outcomes, "work"), "parked_login_refused");
        let state = state::load(&m.ctx).expect("state");
        assert!(
            state
                .get(&Key::new(crate::provider::ProviderId::Claude, "work"))
                .expect("account")
                .parked
                .is_none()
        );
        assert!(m.mem.vault().services().is_empty());
    }

    #[test]
    fn a_login_of_an_account_on_hold_is_kept() {
        let m = machine("on-hold");
        let before = with_park(&m, "work", "old", NOW - 1);
        m.api.renew_trouble("old", Trouble::OnHold);

        let outcomes = renew_parked(&m.ctx, Permit::for_a_test());

        assert_eq!(outcome(&outcomes, "work"), "account_on_hold");
        let state = state::load(&m.ctx).expect("state");
        let kept = state
            .get(&Key::new(crate::provider::ProviderId::Claude, "work"))
            .expect("account")
            .parked
            .clone();
        assert_eq!(kept.as_ref().map(|p| &p.service), Some(&before.service));
        assert_eq!(m.mem.vault().services(), vec![before.service]);
    }

    /// Being unreachable, or being asked to slow down, must change nothing at all: the park
    /// that is still there is the one thing standing between the user and a browser.
    #[test]
    fn a_renewal_that_could_not_happen_leaves_the_park_alone() {
        for trouble in [Trouble::Offline, Trouble::RateLimited] {
            let m = machine(&format!("deferred-{trouble:?}"));
            let before = with_park(&m, "work", "old", NOW - 1);
            m.api.renew_trouble("old", trouble);

            let outcomes = renew_parked(&m.ctx, Permit::for_a_test());

            assert_eq!(outcome(&outcomes, "work"), "renewal_deferred");
            let state = state::load(&m.ctx).expect("state");
            assert_eq!(
                state
                    .get(&Key::new(crate::provider::ProviderId::Claude, "work"))
                    .expect("account")
                    .parked,
                Some(before.clone()),
                "{trouble:?} must not spend or drop anything"
            );
            assert_eq!(m.mem.vault().services(), vec![before.service.clone()]);
        }
    }

    /// With the argument line forbidden, a login past the keychain's standard input cannot
    /// be written back, and the service spends the old refresh token as it answers. It is
    /// not asked: the park stays as it was, and the reason is said. It used to be asked,
    /// and the login was lost.
    #[test]
    fn a_park_that_could_not_be_written_back_is_not_renewed() {
        let mut m = machine("no-argv");
        m.ctx = m.ctx.clone().with_argv_fallback(false);
        let before = with_park(&m, "work", "old", NOW - 1);
        m.mem.vault().takes_on_stdin(16);
        m.api.renews("old", fresh("new"));

        let outcomes = renew_parked(&m.ctx, Permit::for_a_test());

        assert_eq!(outcome(&outcomes, "work"), "credential_too_large");
        assert_eq!(
            m.api.calls(),
            0,
            "the service was not asked, so nothing was spent"
        );
        let state = state::load(&m.ctx).expect("state");
        assert_eq!(
            state
                .get(&Key::new(crate::provider::ProviderId::Claude, "work"))
                .expect("account")
                .parked,
            Some(before.clone())
        );
        assert_eq!(m.mem.vault().services(), vec![before.service]);
    }

    /// The same login with the argument line allowed is renewed as usual.
    #[test]
    fn a_park_past_the_ceiling_is_renewed_where_the_argument_line_is_allowed() {
        let m = machine("argv");
        with_park(&m, "work", "old", NOW - 1);
        m.mem.vault().takes_on_stdin(16);
        m.api.renews("old", fresh("new"));

        let outcomes = renew_parked(&m.ctx, Permit::for_a_test());

        assert_eq!(outcome(&outcomes, "work"), "renewed");
    }

    /// The schedule belongs to the default home, and `launchctl setenv` or a systemd user
    /// environment can still give its job a `PITBOARD_HOME`. A run the schedule started
    /// renews the default home's parked logins and no other's, and a run by hand renews the
    /// ones in the home `PITBOARD_HOME` names. It renewed that home on every run, and on
    /// Linux nothing told a run of the schedule apart. Told both ways it is told: by the
    /// job the scheduler says started this process, which a test says here as launchd's
    /// `XPC_SERVICE_NAME` or systemd's unit would name it, and by the marker the systemd
    /// unit runs Pitboard with.
    #[test]
    fn a_run_the_schedule_started_renews_the_default_home_whatever_pitboard_home_says() {
        use crate::host::{OS, Os};
        use crate::service::Pitboard;
        let job = match OS {
            Os::MacOs => "com.datlechin.pitboard.renew".to_string(),
            Os::Linux => "pitboard-renew.service".to_string(),
            Os::Windows => {
                crate::host::task::path(Job::Renew, &crate::host::user::sid().expect("a SID"))
            }
        };
        let job = job.as_str();
        type Told = fn(Context, &str) -> Context;
        let ways: [(&str, Told); 2] = [
            ("as the scheduler says", |ctx, job| {
                ctx.with_scheduled_job(job.into())
            }),
            ("by the marker", |ctx, _| ctx.started_by_the_schedule()),
        ];
        for (way, scheduled) in ways {
            let m = machine(&format!("scheduled-{}", way.len()));
            let default = m
                .ctx
                .clone()
                .with_pitboard_home(m.ctx.default_pitboard_home());
            let elsewhere = m
                .ctx
                .clone()
                .with_pitboard_home(m.home.path().join("elsewhere"));
            park_in(&default, "work", "default-old", NOW - 1);
            park_in(&elsewhere, "other", "elsewhere-old", NOW - 1);
            m.api.renews("default-old", fresh("default-new"));
            m.api.renews("elsewhere-old", fresh("elsewhere-new"));
            let renewed = |outcomes: Vec<(Key, Renewal)>| -> Vec<(String, String)> {
                outcomes
                    .into_iter()
                    .map(|(key, outcome)| (key.label, outcome.code().to_string()))
                    .collect()
            };

            let run = Pitboard::new(scheduled(elsewhere.clone(), job))
                .renew()
                .expect("a run");
            assert_eq!(renewed(run), [("work".into(), "renewed".into())], "{way}");
            assert_eq!(
                m.api.asked(),
                [Question::Renew("default-old".into())],
                "{way}"
            );
            assert_eq!(
                crate::audit::read(&default, 10)
                    .iter()
                    .map(|e| (e.verb.as_str(), e.outcome.as_str()))
                    .collect::<Vec<_>>(),
                [("renew", "renewed")],
                "{way}: recorded in the home it renewed"
            );

            let by_hand = Pitboard::new(elsewhere).renew().expect("a run");
            assert_eq!(
                renewed(by_hand),
                [("other".into(), "renewed".into())],
                "{way}"
            );
        }
    }

    /// A run of the schedule takes no notice of a `PITBOARD_HOME` that is empty or relative
    /// either, which every other run refuses: it renews the default home, and the gate it
    /// asks is asked of that home. By hand, the same `PITBOARD_HOME` is refused with
    /// `home_not_absolute`, having asked nobody.
    #[test]
    fn a_run_the_schedule_started_renews_the_default_home_where_pitboard_home_is_not_full() {
        use crate::service::Pitboard;
        for named in ["", "relative"] {
            let m = machine(&format!("scheduled-not-full-{}", named.len()));
            let default = m
                .ctx
                .clone()
                .with_pitboard_home(m.ctx.default_pitboard_home());
            park_in(&default, "work", "default-old", NOW - 1);
            m.api.renews("default-old", fresh("default-new"));
            let given = m.ctx.clone().with_pitboard_home(named.into());

            let by_hand = Pitboard::new(given.clone()).renew();
            assert!(
                matches!(by_hand, Err(Error::HomeNotAbsolute { .. })),
                "{named:?}: {by_hand:?}"
            );
            assert_eq!(m.api.asked(), [], "{named:?}");

            let run = Pitboard::new(given.started_by_the_schedule())
                .renew()
                .expect("a run");
            assert_eq!(
                run.iter()
                    .map(|(key, outcome)| (key.label.as_str(), outcome.code()))
                    .collect::<Vec<_>>(),
                [("work", "renewed")],
                "{named:?}"
            );
        }
    }

    /// A build for tests that runs as the schedule with this account's own home is stopped
    /// before it reads anything, since it would renew the real Pitboard directory: a test
    /// gives a run of the schedule a home of its own. Nothing here reads or writes the home;
    /// the context is all that is made.
    #[test]
    #[should_panic(expected = "with this account's own home")]
    fn a_run_the_schedule_started_in_a_build_for_tests_never_renews_the_real_home() {
        let own = {
            let _real = crate::host::user::testing::reaching_the_real_home();
            crate::host::user::home().expect("this account has a home")
        };
        let ctx = Context::new(own)
            .with_memory_stores(MemoryHost::new())
            .started_by_the_schedule();
        let _ = crate::schedule::for_its_run(&ctx, Job::Renew);
    }

    // The vault refuses the answer after Anthropic spent the old token: the park is dropped.
    #[test]
    fn a_renewal_whose_answer_cannot_be_stored_drops_the_spent_park() {
        let m = machine("write-lost");
        let before = with_park(&m, "work", "old", NOW - 1);
        m.api.renews("old", fresh("new"));
        let mem = Arc::clone(&m.mem);

        let outcomes = crate::fault::meanwhile(
            "renew.answered",
            move || {
                mem.vault()
                    .fault_all(Fault::FailWrite("the keychain refused".into()))
            },
            || renew_parked(&m.ctx, Permit::for_a_test()),
        );
        m.mem.vault().heal_all();

        assert_eq!(outcome(&outcomes, "work"), "renewal_failed");
        let state = state::load(&m.ctx).expect("state");
        assert!(
            state
                .get(&Key::new(crate::provider::ProviderId::Claude, "work"))
                .expect("account")
                .parked
                .is_none(),
            "a park whose refresh token Anthropic has spent must not stay on offer"
        );
        assert!(
            !m.mem.vault().services().contains(&before.service),
            "the dead copy is deleted in the same run, not left behind unnamed"
        );
        assert!(
            state.discarded.is_empty(),
            "and nothing is left listed for a later run to retry"
        );
    }

    fn work() -> Key {
        Key::new(crate::provider::ProviderId::Claude, "work")
    }

    fn parked(m: &Scratch) -> Option<Park> {
        state::load(&m.ctx)
            .expect("state")
            .get(&work())
            .expect("account")
            .parked
            .clone()
    }

    // What a full disk does to a file Pitboard writes: here a folder stands in its way.
    struct InTheWay {
        file: std::path::PathBuf,
        kept: std::path::PathBuf,
    }

    impl InTheWay {
        fn of(file: std::path::PathBuf) -> InTheWay {
            let kept = file.with_extension("kept");
            if file.exists() {
                std::fs::rename(&file, &kept).expect("moved aside");
            }
            std::fs::create_dir_all(file.join("in the way")).expect("a folder in its place");
            InTheWay { file, kept }
        }

        fn cleared(self) {
            std::fs::remove_dir_all(&self.file).expect("taken out of the way");
            if self.kept.exists() {
                std::fs::rename(&self.kept, &self.file).expect("put back");
            }
        }
    }

    fn home_file(m: &Scratch, name: &str) -> std::path::PathBuf {
        crate::home::dir(&m.ctx).join(name)
    }

    // On 2026-11-24 a full disk lost three parks: Anthropic was asked and nothing could be kept.
    #[test]
    fn a_home_that_cannot_be_written_holds_the_renewal_before_anything_is_sent() {
        let m = machine("home-full");
        let before = with_park(&m, "work", "old", NOW - 1);
        m.api.renews("old", fresh("new"));
        let blocked = InTheWay::of(home_file(&m, "pending"));

        let outcomes = renew_parked(&m.ctx, Permit::for_a_test());

        blocked.cleared();
        assert_eq!(outcome(&outcomes, "work"), "renewal_held");
        assert_eq!(m.api.calls(), 0, "nothing was sent, so nothing was spent");
        assert_eq!(parked(&m), Some(before.clone()));
        assert_eq!(m.mem.vault().services(), vec![before.service]);
    }

    #[test]
    fn an_account_list_that_cannot_be_saved_holds_the_renewal_before_anything_is_sent() {
        let m = machine("state-full");
        let before = with_park(&m, "work", "old", NOW - 1);
        m.api.renews("old", fresh("new"));
        let file = home_file(&m, "state.json");
        let blocked = std::rc::Rc::new(std::cell::RefCell::new(None));

        let outcomes = crate::fault::meanwhile(
            "renew.prepared",
            {
                let (file, blocked) = (file.clone(), std::rc::Rc::clone(&blocked));
                move || *blocked.borrow_mut() = Some(InTheWay::of(file))
            },
            || renew_parked(&m.ctx, Permit::for_a_test()),
        );

        blocked.take().expect("blocked").cleared();
        assert_eq!(outcome(&outcomes, "work"), "renewal_held");
        assert_eq!(m.api.calls(), 0, "nothing was sent, so nothing was spent");
        assert_eq!(parked(&m), Some(before.clone()));
        assert_eq!(
            m.mem.vault().services(),
            vec![before.service],
            "the copy written to prove the vault is gone"
        );
    }

    #[test]
    fn a_vault_that_refuses_a_write_holds_the_renewal_before_anything_is_sent() {
        let m = machine("vault-full");
        let before = with_park(&m, "work", "old", NOW - 1);
        m.api.renews("old", fresh("new"));
        m.mem
            .vault()
            .fault_all(Fault::FailWrite("the keychain refused".into()));

        let outcomes = renew_parked(&m.ctx, Permit::for_a_test());

        assert_eq!(outcome(&outcomes, "work"), "renewal_held");
        assert_eq!(m.api.calls(), 0, "nothing was sent, so nothing was spent");
        assert_eq!(parked(&m), Some(before.clone()));
        assert_eq!(m.mem.vault().services(), vec![before.service]);
    }

    // The answer is in the vault and `state.json` could not record it: the next run takes it back.
    #[test]
    fn a_renewal_whose_record_could_not_be_saved_is_finished_by_the_next_run() {
        let m = machine("save-lost");
        let before = with_park(&m, "work", "old", NOW - 1);
        m.api.renews("old", fresh("new"));
        let file = home_file(&m, "state.json");
        let blocked = std::rc::Rc::new(std::cell::RefCell::new(None));

        let first = crate::fault::meanwhile(
            "renew.park_stored",
            {
                let (file, blocked) = (file.clone(), std::rc::Rc::clone(&blocked));
                move || *blocked.borrow_mut() = Some(InTheWay::of(file))
            },
            || renew_parked(&m.ctx, Permit::for_a_test()),
        );
        blocked.take().expect("blocked").cleared();

        assert_eq!(outcome(&first, "work"), "state_write_failed");
        assert_eq!(
            parked(&m),
            Some(before.clone()),
            "the file could not change"
        );
        assert!(
            m.mem.vault().services().contains(&before.service),
            "nothing the file names is deleted while the file cannot say otherwise"
        );

        let second = renew_parked(&m.ctx, Permit::for_a_test());

        assert_eq!(outcome(&second, "work"), "not attempted");
        assert_eq!(
            m.api.asked(),
            vec![Question::Renew("old".into())],
            "the spent refresh token is never sent again"
        );
        let now = parked(&m).expect("a park");
        assert_eq!(now.login, crate::store::fingerprint("new"));
        assert_eq!(m.mem.vault().services(), vec![now.service]);
    }
}