pitboard-core 0.10.0

The engine behind Pitboard: parking and restoring Claude Code and Codex logins. 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
//! Every way Pitboard can fail. Each variant has a message naming the cause and an action,
//! a stable code for programs to branch on, and an exit code.

use crate::provider::ProviderId;
use crate::state::Key;
use std::path::PathBuf;

/// The labels an account list holds, rendered for a message: " Enrolled: `a`, `b`." or
/// nothing at all when none are.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Enrolled(pub Vec<String>);

impl std::fmt::Display for Enrolled {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if self.0.is_empty() {
            return write!(f, " Nothing is enrolled yet.");
        }
        let labels: Vec<String> = self.0.iter().map(|l| format!("`{l}`")).collect();
        write!(f, " Enrolled: {}.", labels.join(", "))
    }
}

/// How far putting away the file behind a tool's store had gone when something stopped it.
/// Never as far as deleting the file, and never further than keeping the login it held.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Partway {
    /// Nothing was changed.
    Nothing,
    /// The login the file held was renewed, which spent its refresh token, and the renewed
    /// one could not be written back there.
    RenewedUnwritten,
    /// The login in the file was renewed, and the renewed one written back there.
    Renewed,
    /// The login in the file was parked for `label`.
    Parked { label: String },
}

impl std::fmt::Display for Partway {
    /// What Pitboard did, after "Pitboard".
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Partway::Nothing => write!(f, "changed nothing"),
            Partway::RenewedUnwritten => write!(
                f,
                "deleted nothing. It renewed the login the file held and could not write the \
                 renewed login back there, so that login no longer works"
            ),
            Partway::Renewed => write!(
                f,
                "deleted nothing, having renewed the login in the file and written it back there"
            ),
            Partway::Parked { label } => write!(
                f,
                "deleted nothing, having parked the login in the file for `{label}`"
            ),
        }
    }
}

/// Why a request to Anthropic did not produce an answer Pitboard could use.
///
/// The code on an error says what Pitboard was doing; this says what went wrong underneath
/// it, and whether trying again is worth anything. Without it every failure that was not a
/// 401 arrived at a front end as one code with a sentence of prose, so neither the command
/// line nor the app could tell being offline from being rate limited from a login Anthropic
/// has finished with.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum Cause {
    /// Anthropic could not be reached at all.
    Unreachable,
    /// Anthropic asked for less traffic.
    RateLimited,
    /// Anthropic answered, badly, and may answer well later.
    ServerError,
    /// Anthropic answered something Pitboard does not understand, which means its shape
    /// moved. Trying again will produce the same thing.
    AnswerNotUnderstood,
    /// This login is finished: revoked, or already used somewhere else.
    LoginRefused,
    /// The token has expired. For the signed-in login that is ordinary and Claude Code
    /// renews it; for a parked one it means the park needs renewing first.
    TokenExpired,
}

impl Cause {
    pub fn of(error: &crate::api::ApiError) -> Cause {
        use crate::api::ApiError;
        match error {
            ApiError::Unauthorized => Cause::TokenExpired,
            ApiError::RateLimited { .. } => Cause::RateLimited,
            ApiError::Network(_) => Cause::Unreachable,
            ApiError::Unexpected { .. } => Cause::ServerError,
            ApiError::Malformed(_) => Cause::AnswerNotUnderstood,
            ApiError::InvalidGrant => Cause::LoginRefused,
        }
    }

    /// The same question asked of a provider rather than of Anthropic directly.
    pub fn of_provider(error: &crate::provider::ProviderError) -> Cause {
        use crate::provider::ProviderError as P;
        match error {
            P::Unauthorized => Cause::TokenExpired,
            P::RateLimited { .. } => Cause::RateLimited,
            P::Network { .. } => Cause::Unreachable,
            P::Unexpected { .. } => Cause::ServerError,
            P::Malformed { .. }
            | P::ShapeUnexpected { .. }
            | P::Unsupported { .. }
            | P::NoLogin { .. } => Cause::AnswerNotUnderstood,
            P::InvalidGrant { .. } => Cause::LoginRefused,
        }
    }

    /// Stable, for a program to branch on; the same as its JSON form.
    pub fn code(self) -> &'static str {
        match self {
            Cause::Unreachable => "unreachable",
            Cause::RateLimited => "rate_limited",
            Cause::ServerError => "server_error",
            Cause::AnswerNotUnderstood => "answer_not_understood",
            Cause::LoginRefused => "login_refused",
            Cause::TokenExpired => "token_expired",
        }
    }

    /// Whether the same request, later, could answer differently. A front end deciding
    /// whether to back off or to give up reads this and nothing else.
    pub fn worth_retrying(self) -> bool {
        match self {
            Cause::Unreachable | Cause::RateLimited | Cause::ServerError => true,
            Cause::AnswerNotUnderstood | Cause::LoginRefused | Cause::TokenExpired => false,
        }
    }
}

#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
    #[error(
        "{path} looks like it is inside {marker}, which syncs to other machines. \
         Parked logins belong to one machine; set PITBOARD_HOME to a local folder."
    )]
    StateOnSyncedDrive { path: PathBuf, marker: String },

    /// A home the environment names is empty or relative, so what it leads to would depend
    /// on the folder each program runs in. `variable` is the one that named it.
    #[error("{}", not_absolute(variable, path))]
    HomeNotAbsolute {
        variable: &'static str,
        path: PathBuf,
    },

    #[error(
        "the login for `{label}` needs {bytes} bytes and `security` reads {limit} from \
         stdin, so it can only be written on the argument line, which PITBOARD_NO_ARGV \
         forbids. {}",
        smaller(*tool)
    )]
    CredentialTooLarge {
        tool: ProviderId,
        label: String,
        bytes: usize,
        limit: usize,
    },

    #[error(
        "`{program}` is not on this machine, and Pitboard signs in with {}'s own sign-in. \
         Install {}, or point Pitboard at it.",
        tool.name(),
        tool.name()
    )]
    ProgramMissing { tool: ProviderId, program: String },

    #[error(
        "CLAUDE_CODE_CUSTOM_OAUTH_URL is set, so Claude Code keeps its login under a \
         different name than the one Pitboard reads. Unset it to use Pitboard."
    )]
    CustomOauthEndpoint,

    #[error("could not read Pitboard's account list at {path}: {source}")]
    StateUnreadable {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },

    #[error(
        "Pitboard's account list at {path} is corrupt ({source}). \
         Delete it and enroll your accounts again; parked logins will be lost."
    )]
    StateCorrupt {
        path: PathBuf,
        #[source]
        source: serde_json::Error,
    },

    #[error(
        "{path} was written by a newer Pitboard (its format is {found}, this one reads \
         {expected}). Update this Pitboard the way you installed it. The app, and the command \
         line inside it, update with the app's Check for Updates."
    )]
    StateFromNewerVersion {
        path: PathBuf,
        found: u32,
        expected: u32,
    },

    #[error(
        "{path} is in a format ({found}) no version of Pitboard has ever written. Delete it \
         and enroll your accounts again."
    )]
    StateVersionUnknown { path: PathBuf, found: u32 },

    #[error(
        "{path} has an account for `{tool}`, a tool this Pitboard does not know, so it was \
         written by a newer one. Update this Pitboard the way you installed it. The app, and \
         the command line inside it, update with the app's Check for Updates."
    )]
    StateNamesUnknownTool { path: PathBuf, tool: String },

    #[error(
        "{path} was written on another computer. Parked logins do not move between \
         machines, because two machines taking turns presenting one refresh token ends the \
         login for both. Run `pitboard adopt` to keep your accounts here and drop the \
         logins they came with; each then needs one `pitboard enroll <label> --sign-in`."
    )]
    StateWrongMachine { path: PathBuf },

    #[error(
        "this platform has no scheduler Pitboard knows how to write. Keeping parked logins \
         alive here means running `pitboard` yourself from time to time."
    )]
    ScheduleUnsupported,

    #[error("the scheduler refused: {detail}")]
    ScheduleRefused { detail: String },

    /// The schedule renews the default home alone, so it is installed only where
    /// `PITBOARD_HOME` names that home or nothing. `home` is the directory it names, and
    /// `default` the default home, `~/.pitboard`.
    #[error(
        "the renewal schedule renews only the parked logins in {}, not those in {}, which \
         PITBOARD_HOME names. Nothing was scheduled. To schedule it for {}, unset \
         PITBOARD_HOME and install it again.",
        default.display(),
        home.display(),
        default.display()
    )]
    ScheduleNotDefaultHome { home: PathBuf, default: PathBuf },

    #[error("the renewal schedule would run {path}, which is not there. Nothing was scheduled.")]
    ScheduleProgramMissing { path: PathBuf },

    /// macOS runs an app opened where it was downloaded from a copy it makes somewhere
    /// temporary, which is there while the app runs and gone once it quits.
    #[error(
        "the renewal schedule would run {path}, which is in a temporary copy macOS made of \
         the app and is gone once the app quits. Move Pitboard to your Applications folder, \
         open it from there, and turn on daily renewal again."
    )]
    ScheduleProgramTemporary { path: PathBuf },

    /// An app that names no command line for the schedule, where the only other thing to
    /// schedule is the app itself, which renews nothing.
    #[error("this copy of Pitboard has no command line inside it for the renewal schedule to run.")]
    ScheduleProgramUnnamed,

    #[error("could not write to Pitboard's directory at {path}: {source}")]
    HomeUnwritable {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },

    #[error("could not save Pitboard's account list at {path}: {source}")]
    StateWriteFailed {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },

    #[error(
        "Claude Code has not run on this machine yet ({path} does not exist). \
         Run `claude` once, sign in, then try again."
    )]
    ClaudeConfigMissing { path: PathBuf },

    #[error("could not read Claude Code's config at {path}: {source}")]
    ClaudeConfigUnreadable {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },

    #[error(
        "Claude Code's config at {path} is not valid JSON right now ({source}). \
         It may be mid-write; wait a few seconds and try again."
    )]
    ClaudeConfigNotJson {
        path: PathBuf,
        #[source]
        source: serde_json::Error,
    },

    #[error(
        "nothing is signed in to {} right now. Run `{}`, sign in, then try again.",
        tool.name(),
        tool.login_command()
    )]
    LiveCredentialAbsent { tool: ProviderId },

    #[error(
        "Claude Code's config says {email} is signed in, but Pitboard cannot find that \
         login in the keychain or in the file it also reads. It will not write a login \
         where nobody reads it. This usually means Claude Code has started keeping logins \
         somewhere Pitboard does not know about yet: check for a Pitboard update, and \
         report it with `pitboard doctor --json` if there is none."
    )]
    LiveCredentialElsewhere { email: String },

    #[error(
        "the signed-in credential is not shaped like a {} login ({detail}). \
         Run `pitboard doctor` before switching again.",
        tool.name()
    )]
    LiveCredentialShapeUnexpected { tool: ProviderId, detail: String },

    /// The tool is configured to keep its login somewhere Pitboard does not handle.
    #[error("{reason}.")]
    LiveStoreUnsupported { tool: ProviderId, reason: String },

    #[error(
        "no account is enrolled as `{label}`.{enrolled} Run `pitboard enroll {label} \
         --sign-in` to add it."
    )]
    AccountUnknown {
        label: String,
        /// The labels that do exist, so a typo costs no second command.
        enrolled: Enrolled,
    },

    #[error(
        "`{label}` has no parked login to switch to: the last one went back into use and \
         {} has moved on from it. Run `pitboard enroll {label} --sign-in` to sign in to it \
         again.",
        tool.name()
    )]
    NothingParked { tool: ProviderId, label: String },

    #[error(
        "the parked login for `{label}` has expired. Run `pitboard enroll {label} --sign-in` \
         to sign in to it again."
    )]
    ParkedLoginExpired { label: String },

    #[error(
        "{who} is signed in but not enrolled, so it cannot be parked. \
         Run `pitboard enroll {}` for it first.",
        Key::new(*tool, "<label>").typed()
    )]
    LiveAccountNotEnrolled { tool: ProviderId, who: String },

    #[error(
        "{email} is already enrolled as `{label}`. To add a different account, run \
         `pitboard enroll {} --sign-in`.",
        Key::new(*tool, "<label>").typed()
    )]
    AlreadyEnrolled {
        tool: ProviderId,
        email: String,
        label: String,
    },

    #[error("`{label}` already refers to {who}. Choose a different label.")]
    LabelTaken { label: String, who: String },

    #[error(
        "`{typed}` is not a tool Pitboard knows. It knows: {}.",
        known.join(", ")
    )]
    ProviderUnknown { typed: String, known: Vec<String> },

    #[error(
        "`{label}` is enrolled for more than one tool: {}. Say which one.",
        matches.iter().map(|m| format!("`{m}`")).collect::<Vec<_>>().join(", ")
    )]
    LabelAmbiguous { label: String, matches: Vec<String> },

    #[error("`{label}` is signed in; switch to another account before forgetting it.")]
    CannotForgetActiveAccount { label: String },

    /// Asked to write an account into its tool's config as the one in use, once another
    /// account's login is stored, as after a switch made since somebody asked.
    #[error(
        "`{label}` is not signed in now, so Pitboard left {}'s config as it is. A switch \
         writes the account it puts in use there.",
        tool.name()
    )]
    AccountNotInUse { tool: ProviderId, label: String },

    #[error("could not find a free place to park this login. Run `pitboard doctor`.")]
    ParkSlotExhausted,

    #[error(
        "the parked login for `{label}` is missing. Run `pitboard enroll {label} --sign-in` \
         to sign in to it again."
    )]
    ParkedCredentialMissing { label: String },

    #[error(
        "the parked login for `{label}` is not the one Pitboard recorded ({detail}). Run \
         `pitboard enroll {label} --sign-in` to replace it."
    )]
    ParkedCredentialCorrupt { label: String, detail: String },

    #[error("could not back up Claude Code's config ({path}): {source}. Nothing was changed.")]
    ConfigBackupFailed {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },

    /// Claude Code fetches its profile again only once the config's is a day old (the
    /// register's `config_identity_is_the_last_writers`), so this does not correct itself
    /// sooner.
    #[error(
        "Claude Code's config at {path} could not be updated ({detail}), so Claude Code may \
         show another account's name than the one in use. `pitboard use` with the account in \
         use writes it there."
    )]
    ConfigWriteFailed { path: PathBuf, detail: String },

    #[error(
        "{}'s session has expired, so Pitboard cannot confirm which account is signed in. \
         Run `{}` once so it refreshes, then try again.",
        tool.name(),
        tool.program()
    )]
    SessionExpired { tool: ProviderId },

    #[error(
        "Pitboard could not confirm with {} which account is signed in ({detail}), and will \
         not move a login it cannot identify. Check the connection and try again.",
        tool.service()
    )]
    IdentityUnverifiable {
        tool: ProviderId,
        cause: Cause,
        detail: String,
    },

    #[error("the signed-in account changed while switching. Nothing was moved; try again.")]
    SignedInAccountChanged,

    #[error(
        "an earlier switch from `{from}` to `{to}` was interrupted, and Pitboard cannot yet \
         tell whether it finished ({detail}). Nothing was changed. Run `{}` once so its \
         session is current, then try again.",
        tool.program()
    )]
    RecoveryUndetermined {
        tool: ProviderId,
        from: String,
        to: String,
        detail: String,
    },

    #[error(
        "could not sign in as `{to}` ({detail}); `{from}` is still signed in, nothing was lost."
    )]
    SwitchRolledBack {
        from: String,
        to: String,
        detail: String,
    },

    #[error(
        "{} no longer accepts `{label}`'s parked login, so Pitboard did not move anything. \
         The copy has been dropped; sign in to that account again with \
         `pitboard enroll {label} --sign-in`.",
        tool.service()
    )]
    ParkedLoginRefused { tool: ProviderId, label: String },

    #[error(
        "`{label}`'s parked login belongs to {who}, not to the account Pitboard has \
         under that label. Nothing was moved. Run `pitboard doctor`, then \
         `pitboard enroll {label} --sign-in` to replace it."
    )]
    ParkedLoginBelongsElsewhere { label: String, who: String },

    #[error(
        "signed in as `{to}`, and the login was gone again before Pitboard finished. {}",
        after_it_did_not_hold(*tool, from, to)
    )]
    SwitchDidNotHold {
        tool: ProviderId,
        from: String,
        to: String,
    },

    #[error(
        "could not sign in as `{to}` ({detail}), and could not read the credential store \
         back to find out whether anything changed. Nothing has been deleted and both \
         logins are still here. {} and run `pitboard use {to}` again; it finishes or \
         undoes this before doing anything else.",
        make_readable(*tool)
    )]
    SwitchUnverified {
        tool: ProviderId,
        from: String,
        to: String,
        detail: String,
    },

    #[error(
        "could not sign in as `{to}`, and could not put `{from}` back either ({detail}). \
         `{from}`'s login is still parked: run `{}` and sign in to any enrolled account, \
         then `pitboard use {from}`.",
        tool.login_command()
    )]
    SwitchCorrupted {
        tool: ProviderId,
        from: String,
        to: String,
        detail: String,
    },

    #[error(
        "signed in to `{label}` again, and Pitboard could not confirm that its new login \
         took the place of the one in use ({detail}), so {} may have no login for it now. {}",
        tool.name(),
        not_in_use(*tool, label, *parked)
    )]
    SignInNotInstalled {
        tool: ProviderId,
        label: String,
        detail: String,
        /// Whether the new login was parked instead, which keeps the one copy of it.
        parked: bool,
        /// What writing it and parking it warned about, which is still true of a change
        /// that failed afterwards. Taken out by the service and reported beside the error.
        warnings: Vec<crate::service::Warning>,
    },

    #[error(
        "the new login for `{label}` could not be put in use ({detail}), so it was not \
         kept, and {} keeps the login it has. Run `pitboard enroll {label} --sign-in` to \
         sign in again.",
        tool.name()
    )]
    SignInNotKept {
        tool: ProviderId,
        label: String,
        detail: String,
    },

    #[error(
        "the record of an interrupted switch at {path} is damaged ({source}), so Pitboard \
         cannot tell what that switch did. Nothing was changed. Check that `pitboard status` \
         shows the account you expect, then delete the file to continue."
    )]
    RecoveryRecordCorrupt {
        path: PathBuf,
        #[source]
        source: serde_json::Error,
    },

    #[error(
        "an earlier switch of {} from `{from}` to `{to}` was interrupted while its login was \
         at {slot}, and this run reads it from somewhere else, so it cannot tell what that \
         switch did. Nothing was changed. Run Pitboard with {} pointing where it did to \
         finish it, or `pitboard abandon` to keep every login it names and move on.",
        tool.name(),
        tool.home_variable()
    )]
    RecoveryElsewhere {
        tool: ProviderId,
        from: String,
        to: String,
        slot: String,
    },

    #[error("could not read or write Pitboard's recovery record at {path}: {source}")]
    RecoveryFailed {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },

    #[error(
        "`{}` was not found on PATH. Install {}, run it once, then try again.",
        tool.program(),
        tool.name()
    )]
    ProgramNotFound { tool: ProviderId },

    #[error(
        "could not renew the parked login for `{label}` ({detail}); its last reading is shown \
         instead. Run `pitboard doctor` if this keeps happening."
    )]
    RenewalFailed {
        label: String,
        cause: Option<Cause>,
        detail: String,
    },

    #[error("the sign-in did not finish, so nothing was enrolled.")]
    SignInIncomplete,

    /// The file behind the store in use holds something else than what putting it away was
    /// confirmed for, or is gone.
    #[error(
        "{} has changed since putting it away was confirmed. Putting it away again says first \
         what it holds now.",
        path.display()
    )]
    LeftLoginChanged { path: PathBuf },

    /// The login stored changed before the file behind it could go, where it was going
    /// because of that login: the file held that very login, or another of the same account.
    #[error(
        "the login {} has stored changed while {} was being put away, and whether the file's \
         login is kept somewhere depended on it. Putting it away again says first what it does \
         now.",
        ProviderId::Claude.name(),
        path.display()
    )]
    StoredLoginChanged { path: PathBuf },

    /// The login left in the file is an account's nobody enrolled, so there is no account to
    /// keep it for, and deleting the file would lose it.
    #[error(
        "{} holds {email}'s login{}, an account not enrolled here, so Pitboard has no account to \
         keep it for. Enrol that account first, with `pitboard enroll <label> --sign-in`, or \
         with `pitboard enroll <label>` while Claude Code is signed in to it, then run \
         `pitboard stow` again.",
        path.display(),
        crate::words::in_organisation(organization)
    )]
    LeftLoginNotEnrolled {
        path: PathBuf,
        email: String,
        organization: String,
    },

    #[error(
        "Pitboard could not ask {} whose the login left in {} is ({detail}). Check the \
         connection and try again.",
        ProviderId::Claude.service(),
        path.display()
    )]
    LeftLoginUnidentified {
        path: PathBuf,
        cause: Cause,
        detail: String,
    },

    /// What stopped putting away the file behind a tool's store, said with how far that had
    /// gone, which is never as far as deleting the file. Its code, cause and exit status are
    /// `error`'s, so a program branches on what stopped it.
    #[error("{} Pitboard {partway}.", sentence(error))]
    StowStopped {
        partway: Partway,
        /// What parking the login warned about, where it was parked first. Taken out by the
        /// service and reported beside the error.
        warnings: Vec<crate::service::Warning>,
        error: Box<Error>,
    },

    /// Signing in to a second account works by pointing the tool's own login at a scratch
    /// directory. Where that does not isolate it from the live login, running one would
    /// write over the account somebody is using, so Pitboard will not.
    #[error(
        "Pitboard will not sign in to a second account on this machine: {reason} Signing \
         in would write over the login you are using."
    )]
    SignInNotIsolated { reason: String },

    #[error(
        "another `pitboard enroll --sign-in` is already waiting for its sign-in. Finish or \
         cancel that one first."
    )]
    SignInInProgress,

    /// This process runs as root or under sudo, or elevated on Windows, or the system could
    /// not say whether it does, so Pitboard changes nothing: the one gate every change passes
    /// refused it. `why` is how it runs, as the host said it, and `None` where the host could
    /// not say.
    #[error("{}", crate::words::elevated(crate::host::OS, *why).refusal)]
    Elevated { why: Option<&'static str> },

    #[error("{}", crate::words::too_old(*build).refusal)]
    SystemTooOld { build: Option<u32> },

    /// This is a Windows build of a release made before Pitboard for Windows is released, so
    /// it does nothing ([`crate::release`]). Kept once Windows is released, where it never
    /// occurs.
    #[error("Pitboard for Windows is not released yet. This build changes nothing.")]
    WindowsNotReleased,

    /// The command line itself was wrong; the message is clap's.
    #[error("{0}")]
    Usage(String),

    #[error(transparent)]
    Store(#[from] crate::store::Error),

    #[error(transparent)]
    Lock(#[from] crate::lock::LockError),
}

impl Error {
    /// A stable identifier a program can branch on. Adding one is safe; renaming one is not.
    pub fn code(&self) -> &'static str {
        use Error::*;
        match self {
            StateOnSyncedDrive { .. } => "state_on_synced_drive",
            HomeNotAbsolute { .. } => "home_not_absolute",
            ProgramMissing { tool, .. } => match tool {
                ProviderId::Claude => "claude_program_missing",
                ProviderId::Codex => "codex_program_missing",
            },
            CredentialTooLarge { .. } => "credential_too_large",
            CustomOauthEndpoint => "custom_oauth_endpoint",
            StateUnreadable { .. } => "state_unreadable",
            StateCorrupt { .. } => "state_corrupt",
            StateFromNewerVersion { .. } => "state_from_newer_version",
            StateVersionUnknown { .. } => "state_version_unknown",
            StateNamesUnknownTool { .. } => "state_names_unknown_tool",
            StateWrongMachine { .. } => "state_wrong_machine",
            StateWriteFailed { .. } => "state_write_failed",
            ScheduleUnsupported => "schedule_unsupported",
            ScheduleRefused { .. } => "schedule_refused",
            ScheduleNotDefaultHome { .. } => "schedule_not_default_home",
            ScheduleProgramMissing { .. } => "schedule_program_missing",
            ScheduleProgramTemporary { .. } => "schedule_program_temporary",
            ScheduleProgramUnnamed => "schedule_program_unnamed",
            HomeUnwritable { .. } => "home_unwritable",
            ClaudeConfigMissing { .. } => "claude_config_missing",
            ClaudeConfigUnreadable { .. } => "claude_config_unreadable",
            ClaudeConfigNotJson { .. } => "claude_config_not_json",
            LiveCredentialAbsent { .. } => "live_credential_absent",
            LiveStoreUnsupported { .. } => "live_store_unsupported",
            LiveCredentialElsewhere { .. } => "live_credential_elsewhere",
            LiveCredentialShapeUnexpected { .. } => "live_credential_shape_unexpected",
            AccountUnknown { .. } => "account_unknown",
            NothingParked { .. } => "nothing_parked",
            ParkedLoginExpired { .. } => "parked_login_expired",
            ParkedLoginRefused { .. } => "parked_login_refused",
            ParkedLoginBelongsElsewhere { .. } => "parked_login_belongs_elsewhere",
            LiveAccountNotEnrolled { .. } => "live_account_not_enrolled",
            AlreadyEnrolled { .. } => "already_enrolled",
            LabelTaken { .. } => "label_taken",
            ProviderUnknown { .. } => "provider_unknown",
            LabelAmbiguous { .. } => "label_ambiguous",
            CannotForgetActiveAccount { .. } => "cannot_forget_active_account",
            AccountNotInUse { .. } => "account_not_in_use",
            ParkSlotExhausted => "park_slot_exhausted",
            ParkedCredentialMissing { .. } => "parked_credential_missing",
            ParkedCredentialCorrupt { .. } => "parked_credential_corrupt",
            ConfigBackupFailed { .. } => "config_backup_failed",
            ConfigWriteFailed { .. } => "config_write_failed",
            SwitchRolledBack { .. } => "switch_rolled_back",
            SwitchDidNotHold { .. } => "switch_did_not_hold",
            SwitchUnverified { .. } => "switch_unverified",
            SwitchCorrupted { .. } => "switch_corrupted",
            SignInNotInstalled { .. } => "sign_in_not_installed",
            SignInNotKept { .. } => "sign_in_not_kept",
            RecoveryFailed { .. } => "recovery_failed",
            RecoveryRecordCorrupt { .. } => "recovery_record_corrupt",
            SessionExpired { .. } => "session_expired",
            IdentityUnverifiable { .. } => "identity_unverifiable",
            SignedInAccountChanged => "signed_in_account_changed",
            RecoveryUndetermined { .. } => "recovery_undetermined",
            RecoveryElsewhere { .. } => "recovery_elsewhere",
            ProgramNotFound { tool } => match tool {
                ProviderId::Claude => "claude_not_found",
                ProviderId::Codex => "codex_not_found",
            },
            SignInIncomplete => "sign_in_incomplete",
            LeftLoginChanged { .. } => "left_login_changed",
            StoredLoginChanged { .. } => "stored_login_changed",
            LeftLoginNotEnrolled { .. } => "left_login_not_enrolled",
            LeftLoginUnidentified { .. } => "left_login_unidentified",
            StowStopped { error, .. } => error.code(),
            SignInNotIsolated { .. } => "sign_in_not_isolated",
            RenewalFailed { .. } => "renewal_failed",
            SignInInProgress => "sign_in_in_progress",
            Elevated { .. } => "elevated",
            SystemTooOld { .. } => "system_too_old",
            WindowsNotReleased => "windows_not_released",
            Usage(_) => "usage",
            Store(e) => e.code(),
            Lock(e) => e.code(),
        }
    }

    /// What went wrong underneath, where the failure came from a request to Anthropic.
    /// `None` where nothing was asked.
    pub fn cause(&self) -> Option<Cause> {
        use Error::*;
        match self {
            IdentityUnverifiable { cause, .. } | LeftLoginUnidentified { cause, .. } => {
                Some(*cause)
            }
            RenewalFailed { cause, .. } => *cause,
            SessionExpired { .. } => Some(Cause::TokenExpired),
            StowStopped { error, .. } => error.cause(),
            _ => None,
        }
    }

    /// Warnings a failed change carries in itself, for the caller to report beside it. Only
    /// a failure that happened after something worth warning about was done carries any.
    pub(crate) fn take_warnings(&mut self) -> Vec<crate::service::Warning> {
        match self {
            Error::SignInNotInstalled { warnings, .. } | Error::StowStopped { warnings, .. } => {
                std::mem::take(warnings)
            }
            _ => Vec::new(),
        }
    }

    /// 1 when a request could not be met; 2 when the command line was wrong; 3 when a login
    /// or Claude Code's files are in a state Pitboard cannot safely act on: an unexpected
    /// format, or a login that could not be put back.
    pub fn exit_code(&self) -> u8 {
        use Error::*;
        match self {
            // A login or Claude Code's files in a state Pitboard will not act on, which is
            // what exit 3 means: not a failure of the attempt, a refusal to attempt.
            LiveCredentialShapeUnexpected { .. }
            | LiveStoreUnsupported { .. }
            | ClaudeConfigNotJson { .. }
            | SwitchCorrupted { .. }
            | SwitchUnverified { .. }
            | SwitchDidNotHold { .. }
            | SignInNotInstalled { .. }
            | LiveCredentialElsewhere { .. }
            | CredentialTooLarge { .. }
            | CustomOauthEndpoint
            | RecoveryRecordCorrupt { .. } => 3,
            Usage(_) => 2,
            Store(e) => e.exit_code(),
            StowStopped { error, .. } => error.exit_code(),
            _ => 1,
        }
    }
}

/// `error`'s message as a sentence, ending with a full stop as some do not, for more to be
/// said after it.
fn sentence(error: &Error) -> String {
    let said = error.to_string();
    if said.ends_with('.') {
        said
    } else {
        format!("{said}.")
    }
}

pub type Result<T> = std::result::Result<T, Error>;

/// What Pitboard says of a home that is not a full path: which variable named it, and what
/// it holds.
fn not_absolute(variable: &str, path: &std::path::Path) -> String {
    let holds = if path.as_os_str().is_empty() {
        "empty".to_string()
    } else {
        format!("`{}`, which is not a full path", path.display())
    };
    format!(
        "{variable} is {holds}, so the folder it names would depend on where each program \
         runs. Set it to a full path, or unset it; Pitboard reads and changes nothing until \
         then."
    )
}

/// What makes a tool's live login readable again, where it could not be read.
fn make_readable(tool: ProviderId) -> &'static str {
    match tool {
        ProviderId::Claude => "Unlock the keychain",
        ProviderId::Codex => "Make Codex's auth.json readable to you again",
    }
}

/// What makes a login smaller, where anything does.
fn smaller(tool: ProviderId) -> &'static str {
    match tool {
        ProviderId::Claude => {
            "Unset it, or sign out of MCP servers you no longer use to make the login smaller."
        }
        ProviderId::Codex => "Unset it to let Pitboard write it.",
    }
}

/// Which write took a switched-in login away again, as far as each tool is known to make
/// one, and what that leaves.
fn after_it_did_not_hold(tool: ProviderId, from: &str, to: &str) -> String {
    match tool {
        ProviderId::Claude => format!(
            "Claude Code removes a login without taking the write lock when `/logout` has \
             given up waiting, which is the one write Pitboard cannot exclude. Nothing was \
             lost: both `{from}` and `{to}` are parked. Run `claude` and sign in to any \
             enrolled account, then `pitboard use {to}`."
        ),
        // Not "nothing was lost": the likeliest writer is a codex session refreshing the
        // outgoing account, which spends the token in that account's park, and `codex
        // login` would revoke whatever login is left in auth.json.
        ProviderId::Codex => format!(
            "Codex takes no lock, so a codex session still running from before the switch, \
             refreshing or signing out, rewrote auth.json underneath it. `{to}` is still \
             parked. `{from}`'s park may hold a token that refresh spent. Quit every running \
             codex, then run `pitboard` to see what is signed in; do not run `codex login` \
             or `codex logout` until you have, because either revokes the login they find."
        ),
    }
}

/// Where a new login that could not be put in use went, and the way back from there.
fn not_in_use(tool: ProviderId, label: &str, parked: bool) -> String {
    if parked {
        format!(
            "The new login is parked, so it is not lost. Run `pitboard` to see what is \
             signed in; if nothing is, run `{}` and sign in to any enrolled account, then \
             `pitboard use {label}`.",
            tool.login_command()
        )
    } else {
        format!(
            "It could not be parked either: run `{}` and sign in to `{label}` again.",
            tool.login_command()
        )
    }
}

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

    #[test]
    fn codes_are_unique_so_a_caller_can_branch_on_them() {
        let samples = [
            Error::LiveCredentialAbsent {
                tool: ProviderId::Claude,
            },
            Error::ParkSlotExhausted,
            Error::SignedInAccountChanged,
            Error::AccountUnknown {
                label: "x".into(),
                enrolled: Enrolled::default(),
            },
            Error::NothingParked {
                tool: ProviderId::Claude,
                label: "x".into(),
            },
            Error::ParkedLoginExpired { label: "x".into() },
            Error::AccountNotInUse {
                tool: ProviderId::Claude,
                label: "x".into(),
            },
            Error::LabelTaken {
                label: "x".into(),
                who: "e".into(),
            },
            Error::SwitchRolledBack {
                from: "x".into(),
                to: "y".into(),
                detail: "d".into(),
            },
            Error::SignInNotKept {
                tool: ProviderId::Codex,
                label: "x".into(),
                detail: "d".into(),
            },
            Error::Elevated { why: None },
            Error::SystemTooOld { build: Some(22631) },
            Error::WindowsNotReleased,
            Error::LeftLoginChanged { path: "f".into() },
            Error::StoredLoginChanged { path: "f".into() },
        ];
        let mut codes: Vec<&str> = samples.iter().map(Error::code).collect();
        codes.sort_unstable();
        let before = codes.len();
        codes.dedup();
        assert_eq!(codes.len(), before);
    }

    /// Whatever stops putting the file away is branched on by its own code, cause and exit
    /// status, and says after its own words how far putting it away had gone.
    #[test]
    fn what_stopped_putting_a_file_away_keeps_its_code_and_says_how_far_it_went() {
        let stopped = Error::StowStopped {
            partway: Partway::Parked {
                label: "work".into(),
            },
            warnings: Vec::new(),
            error: Box::new(Error::Store(crate::store::Error::Locked)),
        };

        assert_eq!(stopped.code(), "credential_store_locked");
        assert_eq!(
            stopped.exit_code(),
            Error::Store(crate::store::Error::Locked).exit_code()
        );
        assert!(
            stopped.to_string().ends_with(
                "desktop session. Pitboard deleted nothing, having parked the login in the file \
                 for `work`."
            ),
            "{stopped}"
        );

        let unidentified = Error::StowStopped {
            partway: Partway::Nothing,
            warnings: Vec::new(),
            error: Box::new(Error::LeftLoginUnidentified {
                path: "f".into(),
                cause: Cause::Unreachable,
                detail: "offline".into(),
            }),
        };
        assert_eq!(unidentified.code(), "left_login_unidentified");
        assert_eq!(unidentified.cause(), Some(Cause::Unreachable));
        assert!(
            unidentified
                .to_string()
                .ends_with("try again. Pitboard changed nothing."),
            "{unidentified}"
        );
    }

    #[test]
    fn a_broken_assumption_exits_differently_from_a_bad_request() {
        assert_eq!(
            Error::LiveCredentialShapeUnexpected {
                tool: ProviderId::Claude,
                detail: "x".into()
            }
            .exit_code(),
            3
        );
        assert_eq!(
            Error::AccountUnknown {
                label: "x".into(),
                enrolled: Enrolled::default()
            }
            .exit_code(),
            1
        );
    }

    #[test]
    fn every_message_tells_the_user_something_to_do() {
        // A message that only states a fact leaves the user stuck.
        let actionable = [
            Error::LiveCredentialAbsent {
                tool: ProviderId::Claude,
            }
            .to_string(),
            Error::LiveCredentialAbsent {
                tool: ProviderId::Codex,
            }
            .to_string(),
            Error::AccountUnknown {
                label: "work".into(),
                enrolled: Enrolled(vec!["personal".into()]),
            }
            .to_string(),
            Error::NothingParked {
                tool: ProviderId::Claude,
                label: "work".into(),
            }
            .to_string(),
            Error::ParkedLoginExpired {
                label: "work".into(),
            }
            .to_string(),
            Error::ParkedCredentialMissing {
                label: "work".into(),
            }
            .to_string(),
            Error::LiveAccountNotEnrolled {
                tool: ProviderId::Claude,
                who: "a@b.c".into(),
            }
            .to_string(),
            Error::SignInNotKept {
                tool: ProviderId::Codex,
                label: "codex/work".into(),
                detail: "the keychain is locked".into(),
            }
            .to_string(),
        ];
        for message in actionable {
            assert!(
                message.contains("Run ") || message.contains("Sign in"),
                "no action offered: {message}"
            );
        }
    }

    /// Codex's messages name Codex and the command that signs in to it; Claude Code's name
    /// Claude Code. A message about the wrong tool sends somebody to run the wrong program.
    #[test]
    fn a_message_names_the_tool_it_is_about() {
        let codex = Error::LiveCredentialAbsent {
            tool: ProviderId::Codex,
        }
        .to_string();
        assert!(
            codex.contains("Codex") && codex.contains("`codex login`"),
            "{codex}"
        );
        assert!(!codex.contains("Claude"), "{codex}");

        let unverifiable = Error::IdentityUnverifiable {
            tool: ProviderId::Codex,
            cause: Cause::Unreachable,
            detail: "offline".into(),
        }
        .to_string();
        assert!(unverifiable.contains("OpenAI"), "{unverifiable}");

        let claude = Error::IdentityUnverifiable {
            tool: ProviderId::Claude,
            cause: Cause::Unreachable,
            detail: "offline".into(),
        }
        .to_string();
        assert!(claude.contains("confirm with Anthropic"), "{claude}");
    }

    /// The codes of the two tools' missing programs stay distinct, and Claude Code's keep
    /// the names they were released under.
    #[test]
    fn a_missing_program_keeps_its_released_code() {
        let missing = |tool| Error::ProgramNotFound { tool }.code();
        assert_eq!(missing(ProviderId::Claude), "claude_not_found");
        assert_eq!(missing(ProviderId::Codex), "codex_not_found");
        let absent = |tool| {
            Error::ProgramMissing {
                tool,
                program: "x".into(),
            }
            .code()
        };
        assert_eq!(absent(ProviderId::Claude), "claude_program_missing");
        assert_eq!(absent(ProviderId::Codex), "codex_program_missing");
    }

    /// A Pitboard that finds its files written by a newer one is updated by the route it
    /// came by. The app's Check for Updates moves only the app and the command line inside
    /// it, so it is not offered as another way to update this one.
    #[test]
    fn a_newer_pitboards_files_say_which_update_moves_which_pitboard() {
        let path = PathBuf::from("/home/x/.pitboard/state.json");
        for message in [
            Error::StateFromNewerVersion {
                path: path.clone(),
                found: 9,
                expected: 5,
            }
            .to_string(),
            Error::StateNamesUnknownTool {
                path: path.clone(),
                tool: "gemini".into(),
            }
            .to_string(),
        ] {
            assert!(
                message.contains("Update this Pitboard the way you installed it."),
                "{message}"
            );
            assert!(
                message.contains("The app, and the command line inside it, update with"),
                "{message}"
            );
            assert!(!message.contains("or with the app"), "{message}");
        }
    }

    /// Advice to enrol names the tool the account is for: a bare name would enrol a Claude
    /// Code account for a Codex login.
    #[test]
    fn enrolment_advice_keeps_the_tool() {
        let codex = Error::LiveAccountNotEnrolled {
            tool: ProviderId::Codex,
            who: "a@b.c".into(),
        }
        .to_string();
        assert!(codex.contains("pitboard enroll codex/<label>"), "{codex}");
        let claude = Error::LiveAccountNotEnrolled {
            tool: ProviderId::Claude,
            who: "a@b.c".into(),
        }
        .to_string();
        assert!(claude.contains("pitboard enroll <label>"), "{claude}");
        let already = Error::AlreadyEnrolled {
            tool: ProviderId::Codex,
            email: "a@b.c".into(),
            label: "codex/work".into(),
        }
        .to_string();
        assert!(
            already.contains("pitboard enroll codex/<label> --sign-in"),
            "{already}"
        );
    }

    /// Only a command that changes something finishes an interrupted switch; a plain
    /// `pitboard` reads and leaves it. So the message names the switch to run again, as it
    /// would be typed here.
    #[test]
    fn an_unverified_switch_names_a_command_that_finishes_it() {
        let message = Error::SwitchUnverified {
            tool: ProviderId::Codex,
            from: "codex/personal".into(),
            to: "codex/work".into(),
            detail: "auth.json is not readable".into(),
        }
        .to_string();
        assert!(
            message.contains("run `pitboard use codex/work` again"),
            "{message}"
        );
        assert!(!message.contains("run `pitboard` again"), "{message}");
    }
}