Skip to main content

pitboard_core/
error.rs

1//! Every way Pitboard can fail. Each variant has a message naming the cause and an action,
2//! a stable code for programs to branch on, and an exit code.
3
4use crate::host::{Os, SecretStore};
5use crate::provider::ProviderId;
6use crate::state::Key;
7use crate::words::Spelling;
8use std::path::PathBuf;
9
10/// The labels an account list holds, rendered for a message: " Enrolled: `a`, `b`." or
11/// nothing at all when none are.
12#[derive(Debug, Clone, PartialEq, Eq, Default)]
13pub struct Enrolled(pub Vec<String>);
14
15impl std::fmt::Display for Enrolled {
16    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
17        if self.0.is_empty() {
18            return write!(f, " Nothing is enrolled yet.");
19        }
20        let labels: Vec<String> = self.0.iter().map(|l| format!("`{l}`")).collect();
21        write!(f, " Enrolled: {}.", labels.join(", "))
22    }
23}
24
25/// How far putting away the file behind a tool's store had gone when something stopped it.
26/// Never as far as deleting the file, and never further than keeping the login it held.
27#[derive(Debug, Clone, PartialEq, Eq)]
28pub enum Partway {
29    /// Nothing was changed.
30    Nothing,
31    /// The login Claude Code has stored was renewed to tell whose it is, which spent its
32    /// refresh token, and the renewed one waits in Pitboard's vault for the next change to
33    /// save it there.
34    StoredRenewedKept,
35    /// The login the file held was renewed, which spent its refresh token, and the renewed
36    /// one could not be written back there, nor kept.
37    RenewedUnwritten,
38    /// The login the file held was renewed, which spent its refresh token, and the renewed
39    /// one waits in Pitboard's vault for the next change to write it back there.
40    RenewedKept,
41    /// The login in the file was renewed, and the renewed one written back there.
42    Renewed,
43    /// The login in the file was parked for `label`.
44    Parked { label: String },
45}
46
47impl std::fmt::Display for Partway {
48    /// What Pitboard did, after "Pitboard".
49    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
50        match self {
51            Partway::Nothing => write!(f, "changed nothing"),
52            Partway::StoredRenewedKept => write!(
53                f,
54                "deleted nothing. It renewed the login Claude Code has stored and keeps the \
55                 renewed login until the next change saves it there"
56            ),
57            Partway::RenewedUnwritten => write!(
58                f,
59                "deleted nothing. It renewed the login the file held and could not write the \
60                 renewed login back there, so that login no longer works"
61            ),
62            Partway::RenewedKept => write!(
63                f,
64                "deleted nothing. It renewed the login the file held and keeps the renewed login \
65                 until the next change writes it back there"
66            ),
67            Partway::Renewed => write!(
68                f,
69                "deleted nothing, having renewed the login in the file and written it back there"
70            ),
71            Partway::Parked { label } => write!(
72                f,
73                "deleted nothing, having parked the login in the file for `{label}`"
74            ),
75        }
76    }
77}
78
79/// Why a request to Anthropic did not produce an answer Pitboard could use.
80///
81/// The code on an error says what Pitboard was doing; this says what went wrong underneath
82/// it, and whether trying again is worth anything. Without it every failure that was not a
83/// 401 arrived at a front end as one code with a sentence of prose, so neither the command
84/// line nor the app could tell being offline from being rate limited from a login Anthropic
85/// has finished with.
86#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
87#[serde(rename_all = "snake_case")]
88#[non_exhaustive]
89pub enum Cause {
90    /// Anthropic could not be reached at all.
91    Unreachable,
92    /// Anthropic asked for less traffic.
93    RateLimited,
94    /// Anthropic answered, badly, and may answer well later.
95    ServerError,
96    /// Anthropic refused the request, and asked again would refuse it the same way.
97    Refused,
98    /// Anthropic answered something Pitboard does not understand, which means its shape
99    /// moved. Trying again will produce the same thing.
100    AnswerNotUnderstood,
101    /// This login is finished: revoked, or already used somewhere else.
102    LoginRefused,
103    /// The token has expired. For the signed-in login that is ordinary and Claude Code
104    /// renews it; for a parked one it means the park needs renewing first.
105    TokenExpired,
106}
107
108impl Cause {
109    pub(crate) fn of_provider(error: &crate::provider::ProviderError) -> Cause {
110        use crate::provider::ProviderError as P;
111        match error {
112            P::Unauthorized => Cause::TokenExpired,
113            P::RateLimited { .. } => Cause::RateLimited,
114            P::Network { .. } => Cause::Unreachable,
115            P::Unavailable { .. } => Cause::ServerError,
116            // The request is not one the service takes any more, which no sign-in mends.
117            P::Refused { refusal, .. } if matches!(refusal.status, 404 | 405) => {
118                Cause::AnswerNotUnderstood
119            }
120            P::Refused { .. } | P::OnHold { .. } | P::OtherClient { .. } => Cause::Refused,
121            P::Unnamed { error } => Cause::of_provider(error),
122            P::Malformed { .. }
123            | P::ShapeUnexpected { .. }
124            | P::Unsupported { .. }
125            | P::NoLogin { .. }
126            | P::CodexHomeMissing { .. } => Cause::AnswerNotUnderstood,
127            P::InvalidGrant { .. } => Cause::LoginRefused,
128        }
129    }
130
131    /// Stable, for a program to branch on; the same as its JSON form.
132    pub fn code(self) -> &'static str {
133        match self {
134            Cause::Unreachable => "unreachable",
135            Cause::RateLimited => "rate_limited",
136            Cause::ServerError => "server_error",
137            Cause::Refused => "refused",
138            Cause::AnswerNotUnderstood => "answer_not_understood",
139            Cause::LoginRefused => "login_refused",
140            Cause::TokenExpired => "token_expired",
141        }
142    }
143
144    /// Whether the same request, later, could answer differently. A front end deciding
145    /// whether to back off or to give up reads this and nothing else.
146    pub fn worth_retrying(self) -> bool {
147        match self {
148            Cause::Unreachable | Cause::RateLimited | Cause::ServerError => true,
149            Cause::Refused
150            | Cause::AnswerNotUnderstood
151            | Cause::LoginRefused
152            | Cause::TokenExpired => false,
153        }
154    }
155}
156
157/// The login whose account Pitboard could not confirm.
158#[derive(Debug, Clone, PartialEq, Eq)]
159pub enum Unidentified {
160    /// The one its tool has signed in.
161    SignedIn,
162    /// A login whose account its service named, and whose email it would not give.
163    Unnamed,
164    /// The one a sign-in for the account typed as `label` made.
165    SignIn { label: String },
166    /// The one a sign-in for an account not named yet made.
167    NewSignIn,
168    /// The one parked for the account typed as `label`.
169    Parked { label: String },
170}
171
172#[derive(Debug, thiserror::Error)]
173#[non_exhaustive]
174pub enum Error {
175    #[error(
176        "{path} looks like it is inside {marker}, which syncs to other machines. \
177         Parked logins belong to one machine; set PITBOARD_HOME to a local folder."
178    )]
179    StateOnSyncedDrive { path: PathBuf, marker: String },
180
181    /// A home the environment names is empty or relative, so what it leads to would depend
182    /// on the folder each program runs in. `variable` is the one that named it.
183    #[error("{}", not_absolute(variable, path))]
184    HomeNotAbsolute {
185        variable: &'static str,
186        path: PathBuf,
187    },
188
189    #[error("{}.", codex_home_missing(path))]
190    CodexHomeMissing { path: PathBuf },
191
192    #[error("{}", too_large(*store, *tool, label, *bytes, *limit))]
193    CredentialTooLarge {
194        tool: ProviderId,
195        label: String,
196        bytes: usize,
197        limit: usize,
198        // The store whose ceiling `limit` is.
199        store: SecretStore,
200    },
201
202    #[error(
203        "`{program}` is not on this machine, and Pitboard signs in with {}'s own sign-in. \
204         Install {}, or point Pitboard at it.",
205        tool.name(),
206        tool.name()
207    )]
208    ProgramMissing { tool: ProviderId, program: String },
209
210    #[error(
211        "CLAUDE_CODE_CUSTOM_OAUTH_URL is set, so Claude Code keeps its login under a \
212         different name than the one Pitboard reads. Unset it to use Pitboard."
213    )]
214    CustomOauthEndpoint,
215
216    #[error("could not read Pitboard's account list at {path}: {source}")]
217    StateUnreadable {
218        path: PathBuf,
219        #[source]
220        source: std::io::Error,
221    },
222
223    #[error(
224        "Pitboard's account list at {path} is corrupt ({source}). \
225         Delete it and enroll your accounts again; parked logins will be lost."
226    )]
227    StateCorrupt {
228        path: PathBuf,
229        #[source]
230        source: serde_json::Error,
231    },
232
233    #[error(
234        "{path} was written by a newer Pitboard (its format is {found}, this one reads \
235         {expected}). Update this Pitboard the way you installed it. The app, and the command \
236         line inside it, update with the app's Check for Updates."
237    )]
238    StateFromNewerVersion {
239        path: PathBuf,
240        found: u32,
241        expected: u32,
242    },
243
244    #[error(
245        "{path} is in a format ({found}) no version of Pitboard has ever written. Delete it \
246         and enroll your accounts again."
247    )]
248    StateVersionUnknown { path: PathBuf, found: u32 },
249
250    #[error("could not read which accounts Pitboard warms up, at {path}: {source}")]
251    WarmSettingUnreadable {
252        path: PathBuf,
253        #[source]
254        source: std::io::Error,
255    },
256
257    #[error(
258        "which accounts Pitboard warms up, at {path}, cannot be read ({detail}). Delete it, \
259         then turn warm-up on again for each account you want it for."
260    )]
261    WarmSettingCorrupt { path: PathBuf, detail: String },
262
263    #[error("{}", warm_up_unsupported(*tool, label))]
264    WarmUpUnsupported { tool: ProviderId, label: String },
265
266    #[error("`{label}` was not warmed up: {}.", crate::words::warm_failed(.why))]
267    WarmUpFailed {
268        label: String,
269        why: crate::duty::warm::Failure,
270    },
271
272    #[error("`{label}` {why}, so it is not warmed up now.")]
273    WarmUpNotDue {
274        label: String,
275        why: String,
276        code: &'static str,
277    },
278
279    #[error("Pitboard warms up no account now: {}.", crate::words::not_warming(.halt))]
280    WarmUpHalted { halt: crate::duty::warm::Halt },
281
282    #[error("another Pitboard is warming up an account. Try again in a minute.")]
283    WarmUpInProgress,
284
285    #[error(
286        "{path} has an account for `{tool}`, a tool this Pitboard does not know, so it was \
287         written by a newer one. Update this Pitboard the way you installed it. The app, and \
288         the command line inside it, update with the app's Check for Updates."
289    )]
290    StateNamesUnknownTool { path: PathBuf, tool: String },
291
292    #[error(
293        "{path} was written on another computer. Parked logins do not move between \
294         machines, because two machines taking turns presenting one refresh token ends the \
295         login for both. Run `pitboard adopt` to keep your accounts here and drop the \
296         logins they came with; each then needs one `pitboard enroll <label> --sign-in`."
297    )]
298    StateWrongMachine { path: PathBuf },
299
300    #[error("{}", crate::words::no_scheduler(crate::host::OS, *job))]
301    ScheduleUnsupported { job: crate::schedule::Job },
302
303    #[error("the scheduler refused: {detail}")]
304    ScheduleRefused { detail: String },
305
306    /// `pitboard vault move` on a system that keeps parked logins one way, as macOS keeps them
307    /// in the keychain and Windows in sealed files (`Host::vault_forms`). `form` is the one asked.
308    #[error("{}", vault_form_unsupported(*form))]
309    VaultFormUnsupported { form: crate::state::VaultForm },
310
311    /// Each job serves the default home alone, so it is installed only where `PITBOARD_HOME`
312    /// names that home or nothing. `home` is the directory it names, and `default` the
313    /// default home, `~/.pitboard`.
314    #[error("{}", not_default_home(home, default, *job))]
315    ScheduleNotDefaultHome {
316        home: PathBuf,
317        default: PathBuf,
318        job: crate::schedule::Job,
319    },
320
321    #[error("{} would run {}, which is not there. Nothing was {}.", job_named(*job), path.display(), job_done(*job))]
322    ScheduleProgramMissing {
323        path: PathBuf,
324        job: crate::schedule::Job,
325    },
326
327    /// On Windows a task starts `pitboardw.exe` beside `pitboard.exe`, and `path`, where it
328    /// would be, has none: `cargo install` and `cargo binstall` install `pitboard.exe` alone.
329    #[error("{} would start Pitboard through {}, which is not there. Nothing was {}. Install Pitboard from its zip, Scoop, winget or the app, which carry pitboardw.exe beside pitboard.exe, and {} from there.", job_named(*job), path.display(), job_done(*job), turn_on(*job))]
330    ScheduleLauncherMissing {
331        path: PathBuf,
332        job: crate::schedule::Job,
333    },
334
335    /// macOS runs an app opened where it was downloaded from a copy it makes somewhere
336    /// temporary, which is there while the app runs and gone once it quits. Windows' Explorer
337    /// runs a program opened inside a zip from a copy of it.
338    #[error("{}", temporary_copy(.path, *job))]
339    ScheduleProgramTemporary {
340        path: PathBuf,
341        job: crate::schedule::Job,
342    },
343
344    /// On Linux, the user's systemd would not run the job for this home, which `elsewhere`
345    /// says why. Its `UnitPath` and `HOME` are asked before anything is written, and before a
346    /// job is taken away.
347    #[error("{}", manager_elsewhere(elsewhere, *job))]
348    ScheduleManagerElsewhere {
349        elsewhere: crate::schedule::Elsewhere,
350        job: crate::schedule::Job,
351    },
352
353    /// An app that names no command line for the schedule, where the only other thing to
354    /// schedule is the app itself, which renews nothing.
355    #[error("this copy of Pitboard has no command line inside it for the renewal schedule to run.")]
356    ScheduleProgramUnnamed,
357
358    #[error("could not write to Pitboard's directory at {path}: {source}")]
359    HomeUnwritable {
360        path: PathBuf,
361        #[source]
362        source: std::io::Error,
363    },
364
365    #[error("could not save Pitboard's account list at {path}: {source}")]
366    StateWriteFailed {
367        path: PathBuf,
368        #[source]
369        source: std::io::Error,
370    },
371
372    #[error(
373        "Claude Code has not run on this machine yet ({path} does not exist). \
374         Run `{}` once, sign in, then try again.",
375        spelling.of(ProviderId::Claude)
376    )]
377    ClaudeConfigMissing { path: PathBuf, spelling: Spelling },
378
379    #[error("could not read Claude Code's config at {path}: {source}")]
380    ClaudeConfigUnreadable {
381        path: PathBuf,
382        #[source]
383        source: std::io::Error,
384    },
385
386    #[error(
387        "Claude Code's config at {path} is not valid JSON right now ({source}). \
388         It may be mid-write; wait a few seconds and try again."
389    )]
390    ClaudeConfigNotJson {
391        path: PathBuf,
392        #[source]
393        source: serde_json::Error,
394    },
395
396    #[error("{}", crate::words::nothing_signed_in(*tool, spelling.of(*tool), label.as_deref()))]
397    LiveCredentialAbsent {
398        tool: ProviderId,
399        // the label typed, where a sentence names the command to run for it
400        label: Option<String>,
401        spelling: Spelling,
402    },
403
404    #[error("{}", login_elsewhere(crate::host::OS, email))]
405    LiveCredentialElsewhere { email: String },
406
407    #[error(
408        "the signed-in credential is not shaped like a {} login ({detail}). \
409         Run `pitboard doctor` before switching again.",
410        tool.name()
411    )]
412    LiveCredentialShapeUnexpected { tool: ProviderId, detail: String },
413
414    /// The tool is configured to keep its login somewhere Pitboard does not handle.
415    #[error("{reason}.")]
416    LiveStoreUnsupported { tool: ProviderId, reason: String },
417
418    #[error(
419        "{} would not keep `{label}`'s login: {reason}. Pitboard changed nothing. {}",
420        tool.name(),
421        crate::words::restricted_way_out(*tool)
422    )]
423    LoginRestricted {
424        tool: ProviderId,
425        label: String,
426        reason: String,
427    },
428
429    #[error(
430        "no account is enrolled as `{label}`.{enrolled} Run `pitboard enroll {label} \
431         --sign-in` to add it."
432    )]
433    AccountUnknown {
434        label: String,
435        /// The labels that do exist, so a typo costs no second command.
436        enrolled: Enrolled,
437    },
438
439    #[error(
440        "`{label}` has no parked login to switch to: the last one went back into use and \
441         {} has moved on from it. Run `pitboard enroll {label} --sign-in` to sign in to it \
442         again.",
443        tool.name()
444    )]
445    NothingParked { tool: ProviderId, label: String },
446
447    #[error(
448        "the parked login for `{label}` has expired. Run `pitboard enroll {label} --sign-in` \
449         to sign in to it again."
450    )]
451    ParkedLoginExpired { label: String },
452
453    #[error("{}", not_enrolled(*tool, who))]
454    LiveAccountNotEnrolled { tool: ProviderId, who: String },
455
456    #[error("{}", already_enrolled(*tool, email, label, asked, *waited))]
457    AlreadyEnrolled {
458        tool: ProviderId,
459        email: String,
460        label: String,
461        // the label typed
462        asked: String,
463        // a sign-in inside the app was waited for under `asked`
464        waited: bool,
465    },
466
467    #[error("`{label}` already refers to {who}. Choose a different label.")]
468    LabelTaken { label: String, who: String },
469
470    #[error(
471        "`{typed}` is not a tool Pitboard knows. It knows: {}.",
472        known.join(", ")
473    )]
474    ProviderUnknown { typed: String, known: Vec<String> },
475
476    #[error(
477        "`{label}` is enrolled for more than one tool: {}. Say which one.",
478        matches.iter().map(|m| format!("`{m}`")).collect::<Vec<_>>().join(", ")
479    )]
480    LabelAmbiguous { label: String, matches: Vec<String> },
481
482    #[error("`{label}` is signed in; switch to another account before forgetting it.")]
483    CannotForgetActiveAccount { label: String },
484
485    /// Asked to write an account into its tool's config as the one in use, once another
486    /// account's login is stored, as after a switch made since somebody asked.
487    #[error(
488        "`{label}` is not signed in now, so Pitboard left {}'s config as it is. A switch \
489         writes the account it puts in use there.",
490        tool.name()
491    )]
492    AccountNotInUse { tool: ProviderId, label: String },
493
494    #[error("could not find a free place to park this login. Run `pitboard doctor`.")]
495    ParkSlotExhausted,
496
497    #[error(
498        "the parked login for `{label}` is missing. Run `pitboard enroll {label} --sign-in` \
499         to sign in to it again."
500    )]
501    ParkedCredentialMissing { label: String },
502
503    #[error(
504        "the parked login for `{label}` is not the one Pitboard recorded ({detail}). Run \
505         `pitboard enroll {label} --sign-in` to replace it."
506    )]
507    ParkedCredentialCorrupt { label: String, detail: String },
508
509    #[error("could not back up Claude Code's config ({path}): {source}. Nothing was changed.")]
510    ConfigBackupFailed {
511        path: PathBuf,
512        #[source]
513        source: std::io::Error,
514    },
515
516    /// Claude Code fetches its profile again only once the config's is a day old (the
517    /// register's `config_identity_is_the_last_writers`), so this does not correct itself
518    /// sooner.
519    #[error(
520        "Claude Code's config at {path} could not be updated ({detail}), so Claude Code may \
521         show another account's name than the one in use. `pitboard use` with the account in \
522         use writes it there."
523    )]
524    ConfigWriteFailed { path: PathBuf, detail: String },
525
526    /// The service refused the login's access token as expired. `refused` where Pitboard
527    /// tried to renew the login and its service refuses its refresh token for good, or it
528    /// has none, so only signing in again mends it.
529    #[error("{}", session_expired(*tool, spelling.of(*tool), *refused))]
530    SessionExpired {
531        tool: ProviderId,
532        refused: bool,
533        spelling: Spelling,
534    },
535
536    #[error("{}", identity_unverifiable(*tool, spelling.of(*tool), login, *cause, detail))]
537    IdentityUnverifiable {
538        tool: ProviderId,
539        login: Unidentified,
540        cause: Cause,
541        detail: String,
542        spelling: Spelling,
543    },
544
545    #[error("the signed-in account changed while switching. Nothing was moved; try again.")]
546    SignedInAccountChanged,
547
548    /// The service refuses the refresh token of the login in use for good, so that login no
549    /// longer works and cannot be parked, and a switch to `label` asks first to put that
550    /// account's login in its place.
551    #[error("{}", live_login_refused(*tool, label, detail))]
552    LiveLoginRefused {
553        tool: ProviderId,
554        label: String,
555        detail: String,
556    },
557
558    #[error(
559        "could not put `{label}`'s login in place of {}'s refused login ({detail}). `{label}`'s \
560         login is still parked, and nothing was lost.",
561        tool.name()
562    )]
563    ReplaceFailed {
564        tool: ProviderId,
565        label: String,
566        detail: String,
567    },
568
569    #[error(
570        "could not put `{label}`'s login where {} reads it ({detail}). `{label}`'s login is \
571         still parked, and nothing was lost.",
572        tool.name()
573    )]
574    InstallFailed {
575        tool: ProviderId,
576        label: String,
577        detail: String,
578    },
579
580    #[error("{}", account_on_hold(*tool, login, link.as_deref()))]
581    AccountOnHold {
582        tool: ProviderId,
583        login: Unidentified,
584        link: Option<String>,
585    },
586
587    #[error("{}", recovery_undetermined(*tool, spelling.of(*tool), from, to, detail))]
588    RecoveryUndetermined {
589        tool: ProviderId,
590        from: String,
591        to: String,
592        detail: String,
593        spelling: Spelling,
594    },
595
596    #[error(
597        "an earlier switch from `{from}` to `{to}` stopped partway through writing {}'s login, \
598         which nothing reads until a whole login is written over it, and Pitboard could not \
599         write `{to}`'s ({detail}). Nothing was deleted. Fix that, then try again: Pitboard \
600         finishes the switch first.",
601        tool.name()
602    )]
603    RecoveryUnfinished {
604        tool: ProviderId,
605        from: String,
606        to: String,
607        detail: String,
608    },
609
610    #[error(
611        "could not sign in as `{to}` ({detail}); `{from}` is still signed in, nothing was lost."
612    )]
613    SwitchRolledBack {
614        from: String,
615        to: String,
616        detail: String,
617    },
618
619    #[error(
620        "{} no longer accepts `{label}`'s parked login, so Pitboard did not move anything. \
621         The copy has been dropped; sign in to that account again with \
622         `pitboard enroll {label} --sign-in`.",
623        tool.service()
624    )]
625    ParkedLoginRefused { tool: ProviderId, label: String },
626
627    #[error(
628        "`{label}`'s parked login belongs to {who}, not to the account Pitboard has \
629         under that label. Nothing was moved. Run `pitboard doctor`, then \
630         `pitboard enroll {label} --sign-in` to replace it."
631    )]
632    ParkedLoginBelongsElsewhere { label: String, who: String },
633
634    #[error(
635        "signed in as `{to}`, and the login was gone again before Pitboard finished. {}",
636        after_it_did_not_hold(*tool, spelling.of(*tool), from, to)
637    )]
638    SwitchDidNotHold {
639        tool: ProviderId,
640        from: String,
641        to: String,
642        spelling: Spelling,
643    },
644
645    #[error(
646        "could not sign in as `{to}` ({detail}), and could not read the credential store \
647         back to find out whether anything changed. Nothing has been deleted and both \
648         logins are still here. {} and run `pitboard use {to}` again; it finishes or \
649         undoes this before doing anything else.",
650        make_readable(crate::host::OS, *tool)
651    )]
652    SwitchUnverified {
653        tool: ProviderId,
654        from: String,
655        to: String,
656        detail: String,
657    },
658
659    #[error(
660        "could not sign in as `{to}`, and could not put `{from}` back either ({detail}). \
661         `{from}`'s login is still parked: {} and sign in to any enrolled account, then \
662         `pitboard use {from}`.",
663        crate::words::sign_in_yourself(*tool, spelling.of(*tool), false)
664    )]
665    SwitchCorrupted {
666        tool: ProviderId,
667        from: String,
668        to: String,
669        detail: String,
670        spelling: Spelling,
671    },
672
673    #[error(
674        "signed in to `{label}` again, and Pitboard could not confirm that its new login \
675         took the place of the one in use ({detail}), so {} may have no login for it now. {}",
676        tool.name(),
677        not_in_use(*tool, spelling.of(*tool), label, *parked)
678    )]
679    SignInNotInstalled {
680        tool: ProviderId,
681        label: String,
682        detail: String,
683        /// Whether the new login was parked instead, which keeps the one copy of it.
684        parked: bool,
685        spelling: Spelling,
686        /// What writing it and parking it warned about, which is still true of a change
687        /// that failed afterwards. Taken out by the service and reported beside the error.
688        warnings: Vec<crate::warning::Warning>,
689    },
690
691    #[error(
692        "the new login for `{label}` could not be put in use ({detail}), so it was not \
693         kept, and {} keeps the login it has. Run `pitboard enroll {label} --sign-in` to \
694         sign in again.",
695        tool.name()
696    )]
697    SignInNotKept {
698        tool: ProviderId,
699        label: String,
700        detail: String,
701    },
702
703    #[error(
704        "the record of an interrupted switch at {path} is damaged ({source}), so Pitboard \
705         cannot tell what that switch did. Nothing was changed. Check that `pitboard status` \
706         shows the account you expect, then delete the file to continue."
707    )]
708    RecoveryRecordCorrupt {
709        path: PathBuf,
710        #[source]
711        source: serde_json::Error,
712    },
713
714    #[error("{}", recovery_elsewhere(*tool, from, to, slot))]
715    RecoveryElsewhere {
716        tool: ProviderId,
717        from: String,
718        to: String,
719        slot: String,
720    },
721
722    #[error("could not read or write Pitboard's recovery record at {path}: {source}")]
723    RecoveryFailed {
724        path: PathBuf,
725        #[source]
726        source: std::io::Error,
727    },
728
729    #[error(
730        "`{}` was not found on PATH. Install {}, run it once, then try again.",
731        tool.program(),
732        tool.name()
733    )]
734    ProgramNotFound { tool: ProviderId },
735
736    #[error(
737        "could not renew the parked login for `{label}` ({detail}); its last reading is shown \
738         instead. Run `pitboard doctor` if this keeps happening."
739    )]
740    RenewalFailed {
741        label: String,
742        cause: Option<Cause>,
743        detail: String,
744    },
745
746    #[error("the sign-in did not finish, so nothing was enrolled.")]
747    SignInIncomplete,
748
749    /// The file behind the store in use holds something else than what putting it away was
750    /// confirmed for, or is gone.
751    #[error(
752        "{} has changed since putting it away was confirmed. Putting it away again says first \
753         what it holds now.",
754        path.display()
755    )]
756    LeftLoginChanged { path: PathBuf },
757
758    /// The login stored changed before the file behind it could go, where it was going
759    /// because of that login: the file held that very login, or another of the same account.
760    #[error(
761        "the login {} has stored changed while {} was being put away, and whether the file's \
762         login is kept somewhere depended on it. Putting it away again says first what it does \
763         now.",
764        ProviderId::Claude.name(),
765        path.display()
766    )]
767    StoredLoginChanged { path: PathBuf },
768
769    /// The login left in the file is an account's nobody enrolled, so there is no account to
770    /// keep it for, and deleting the file would lose it.
771    #[error(
772        "{} holds {email}'s login{}, an account not enrolled here, so Pitboard has no account to \
773         keep it for. Enrol that account first, with `pitboard enroll <label> --sign-in`, or \
774         with `pitboard enroll <label>` while Claude Code is signed in to it, then run \
775         `pitboard stow` again.",
776        path.display(),
777        crate::words::in_organisation(organization)
778    )]
779    LeftLoginNotEnrolled {
780        path: PathBuf,
781        email: String,
782        organization: String,
783    },
784
785    #[error(
786        "Pitboard could not ask {} whose the login left in {} is ({detail}). {}",
787        ProviderId::Claude.service(),
788        path.display(),
789        try_again(*cause).unwrap_or("Run `pitboard doctor`.")
790    )]
791    LeftLoginUnidentified {
792        path: PathBuf,
793        cause: Cause,
794        detail: String,
795    },
796
797    /// What stopped putting away the file behind a tool's store, said with how far that had
798    /// gone, which is never as far as deleting the file. Its code, cause and exit status are
799    /// `error`'s, so a program branches on what stopped it.
800    #[error("{} Pitboard {partway}.", sentence(error))]
801    StowStopped {
802        partway: Partway,
803        /// What parking the login warned about, where it was parked first. Taken out by the
804        /// service and reported beside the error.
805        warnings: Vec<crate::warning::Warning>,
806        error: Box<Error>,
807    },
808
809    /// What stopped Pitboard saving a login of a tool's own it had just renewed, where no copy
810    /// of the renewed login could be kept either, so the refresh token the tool's store holds
811    /// is spent. Its code, cause and exit status are `error`'s.
812    #[error(
813        "{} Pitboard renewed {}'s login and could not save the renewed login, so the refresh \
814         token stored is spent. {}, sign in, then try again.",
815        sentence(error),
816        tool.name(),
817        crate::words::sign_in_yourself(*tool, spelling.of(*tool), true)
818    )]
819    RenewalLost {
820        tool: ProviderId,
821        error: Box<Error>,
822        spelling: Spelling,
823    },
824
825    // A refusal after the change had done what `said` says. The service takes it apart.
826    #[error("{error}")]
827    SaidFirst {
828        said: Vec<crate::warning::Warning>,
829        error: Box<Error>,
830    },
831
832    /// Signing in to a second account works by pointing the tool's own login at a scratch
833    /// directory. Where that does not isolate it from the live login, running one would
834    /// write over the account somebody is using, so Pitboard will not.
835    #[error(
836        "Pitboard will not sign in to a second account on this machine: {reason} Signing \
837         in would write over the login you are using."
838    )]
839    SignInNotIsolated { reason: String },
840
841    #[error(
842        "another `pitboard enroll --sign-in` is already waiting for its sign-in. Finish or \
843         cancel that one first."
844    )]
845    SignInInProgress,
846
847    #[error(
848        "{layer} sets `forceLoginMethod` to `console`, so Claude Code's sign-in makes an \
849         Anthropic Console login, which Pitboard cannot enrol. No sign-in was started. Only \
850         whoever manages this computer can change the setting."
851    )]
852    SignInPinnedToConsole { layer: String },
853
854    #[error("{}", pitboard_open(crate::host::OS, home))]
855    PitboardOpen { home: PathBuf },
856
857    #[error("{}", app_open(app, still))]
858    AppOpen {
859        app: &'static str,
860        // what of the app still runs once its own program has quit, as `ShipIt (pid 812)`
861        still: Vec<String>,
862    },
863
864    #[error(
865        "Pitboard could not tell whether {app} is open ({why}), so nothing has changed. Run \
866         this again."
867    )]
868    AppStateUnknown { app: &'static str, why: String },
869
870    #[error(
871        "{}'s data folder {what}, so Pitboard moves no {} login. {}Nothing has changed.",
872        tool.program(),
873        tool.name(),
874        then.said()
875    )]
876    LoginFolderUnknown {
877        tool: ProviderId,
878        what: String,
879        then: Then,
880    },
881
882    #[error(
883        "Pitboard could not read {program}'s cookie store ({detail}). Open {program}, quit it \
884         with Command-Q, then run this again. Nothing has changed.",
885        program = tool.program()
886    )]
887    LoginFolderUnreadable { tool: ProviderId, detail: String },
888
889    #[error(
890        "{program} has not finished signing in. Open {program}, wait until it shows your \
891         chats, quit it with Command-Q, then run this again. Nothing has changed.",
892        program = tool.program()
893    )]
894    SignInUnfinished { tool: ProviderId },
895
896    #[error("{}", in_doubt(*tool, why))]
897    LoginInDoubt { tool: ProviderId, why: LoginDoubt },
898
899    #[error(
900        "Another Pitboard is changing {app}'s login now, so nothing has changed. Run this \
901         again once it has finished."
902    )]
903    LoginFolderBusy { app: &'static str },
904
905    #[error(
906        "Pitboard parks a Claude Desktop login by renaming it into {}, which is on another \
907         volume than {}, and it never copies one. Keep Pitboard's folder on the volume your \
908         home is on. Nothing has changed.",
909        parks.display(),
910        root.display()
911    )]
912    DifferentVolume { parks: PathBuf, root: PathBuf },
913
914    #[error("{}", parks_not_private(path, *why))]
915    ParksNotPrivate {
916        path: PathBuf,
917        why: crate::host::Private,
918    },
919
920    #[error(
921        "Pitboard could not read this Mac's identity, which it writes beside every parked \
922         Claude Desktop login so it never puts back one parked on another Mac. Nothing has \
923         changed."
924    )]
925    MachineUnknown,
926
927    #[error("{}", opened_midway(app, label.as_deref()))]
928    AppOpenedMidway {
929        app: &'static str,
930        // the account whose login was moving; None from the start of a sign-in
931        label: Option<String>,
932    },
933
934    #[error(
935        "Pitboard could not park `{label}`'s login ({detail}) and undid what it had done. \
936         `{label}` is in use, and nothing was lost. Run this again."
937    )]
938    MoveUndone { label: String, detail: String },
939
940    #[error(
941        "Pitboard stopped while moving `{label}`'s login ({detail}). Keep Claude closed and \
942         run this again: Pitboard settles the move first."
943    )]
944    MoveStopped { label: String, detail: String },
945
946    // A settle or a give-up that failed partway: coded `recovery_undetermined`, given up alike.
947    #[error(
948        "Pitboard stopped while settling an interrupted move of `{label}`'s login ({detail}). \
949         Nothing is lost. Keep Claude closed and run this again: Pitboard settles the move \
950         first. If it stops again, `pitboard abandon` keeps every folder and moves on."
951    )]
952    RecoveryStopped { label: String, detail: String },
953
954    #[error("{}", left_signed_out(from.as_deref(), to, detail))]
955    SwitchLeftSignedOut {
956        from: Option<String>,
957        to: String,
958        detail: String,
959    },
960
961    #[error("{}", move_mixed(label, places))]
962    MoveMixed { label: String, places: Vec<String> },
963
964    // the account parked last, if any, and each folder set aside that holds a login
965    #[error("{}", would_strand(label.as_deref(), set_aside))]
966    UninstallWouldStrand {
967        label: Option<String>,
968        set_aside: Vec<PathBuf>,
969    },
970
971    #[error(
972        "Another Pitboard command finished, put back or removed the sign-in this one waited \
973         for, so it enrolled nothing. Run `pitboard` to see who is signed in."
974    )]
975    SignInSettledElsewhere { label: String },
976
977    /// The host says this process is not the person themselves (`Host::elevation`), or could
978    /// not say whether it is, so Pitboard changes nothing: the one gate every change passes
979    /// refused it. `why` is how it runs, as the host said it, and `None` where the host could
980    /// not say.
981    #[error("{}", crate::words::elevated(crate::host::OS, *why).refusal)]
982    Elevated { why: Option<&'static str> },
983
984    #[error("{}", crate::words::too_old(*build).refusal)]
985    SystemTooOld { build: Option<u32> },
986
987    /// This is a Windows build of a release made before Pitboard for Windows is released, so
988    /// it does nothing ([`crate::release`]). Kept once Windows is released, where it never
989    /// occurs.
990    #[error("Pitboard for Windows is not released yet. This build changes nothing.")]
991    WindowsNotReleased,
992
993    /// The command line itself was wrong; the message is clap's.
994    #[error("{0}")]
995    Usage(String),
996
997    /// A command that deletes something was run with nobody to ask, without `--yes`.
998    #[error(
999        "`pitboard {command}` asks before it deletes anything, and can ask only in a terminal \
1000         without `--json`. Nothing was changed. Run it in a terminal, or add `--yes`."
1001    )]
1002    ConfirmationNeeded { command: &'static str },
1003
1004    #[error(transparent)]
1005    Store(#[from] crate::store::Error),
1006
1007    #[error(transparent)]
1008    Lock(#[from] crate::lock::LockError),
1009}
1010
1011impl Error {
1012    // A saved login no store could look at, and why: the app says it in words of its own.
1013    pub fn unread_park(&self) -> Option<(&std::path::Path, &str)> {
1014        match self {
1015            Error::Store(crate::store::Error::ParkUnread { path, why, .. }) => Some((path, why)),
1016            _ => None,
1017        }
1018    }
1019
1020    /// A stable identifier a program can branch on. Adding one is safe; renaming one is not.
1021    pub fn code(&self) -> &'static str {
1022        use Error::*;
1023        match self {
1024            StateOnSyncedDrive { .. } => "state_on_synced_drive",
1025            HomeNotAbsolute { .. } => "home_not_absolute",
1026            CodexHomeMissing { .. } => "codex_home_missing",
1027            ProgramMissing { tool, .. } => match tool {
1028                ProviderId::Claude => "claude_program_missing",
1029                ProviderId::Codex => "codex_program_missing",
1030                ProviderId::Desktop => "desktop_program_missing",
1031            },
1032            CredentialTooLarge { .. } => "credential_too_large",
1033            CustomOauthEndpoint => "custom_oauth_endpoint",
1034            StateUnreadable { .. } => "state_unreadable",
1035            StateCorrupt { .. } => "state_corrupt",
1036            StateFromNewerVersion { .. } => "state_from_newer_version",
1037            StateVersionUnknown { .. } => "state_version_unknown",
1038            WarmSettingUnreadable { .. } => "warm_setting_unreadable",
1039            WarmSettingCorrupt { .. } => "warm_setting_corrupt",
1040            WarmUpUnsupported { .. } => "warm_up_unsupported",
1041            WarmUpFailed { why, .. } => why.code(),
1042            WarmUpNotDue { code, .. } => code,
1043            WarmUpHalted { halt } => halt.code(),
1044            WarmUpInProgress => "warm_up_in_progress",
1045            StateNamesUnknownTool { .. } => "state_names_unknown_tool",
1046            StateWrongMachine { .. } => "state_wrong_machine",
1047            StateWriteFailed { .. } => "state_write_failed",
1048            ScheduleUnsupported { .. } => "schedule_unsupported",
1049            ScheduleRefused { .. } => "schedule_refused",
1050            VaultFormUnsupported { .. } => "vault_form_unsupported",
1051            ScheduleNotDefaultHome { .. } => "schedule_not_default_home",
1052            ScheduleProgramMissing { .. } => "schedule_program_missing",
1053            ScheduleProgramTemporary { .. } => "schedule_program_temporary",
1054            ScheduleLauncherMissing { .. } => "schedule_launcher_missing",
1055            ScheduleProgramUnnamed => "schedule_program_unnamed",
1056            ScheduleManagerElsewhere { .. } => "schedule_manager_elsewhere",
1057            HomeUnwritable { .. } => "home_unwritable",
1058            ClaudeConfigMissing { .. } => "claude_config_missing",
1059            ClaudeConfigUnreadable { .. } => "claude_config_unreadable",
1060            ClaudeConfigNotJson { .. } => "claude_config_not_json",
1061            LiveCredentialAbsent { .. } => "live_credential_absent",
1062            LiveStoreUnsupported { .. } => "live_store_unsupported",
1063            LoginRestricted { .. } => "login_restricted",
1064            LiveCredentialElsewhere { .. } => "live_credential_elsewhere",
1065            LiveCredentialShapeUnexpected { .. } => "live_credential_shape_unexpected",
1066            AccountUnknown { .. } => "account_unknown",
1067            NothingParked { .. } => "nothing_parked",
1068            ParkedLoginExpired { .. } => "parked_login_expired",
1069            ParkedLoginRefused { .. } => "parked_login_refused",
1070            ParkedLoginBelongsElsewhere { .. } => "parked_login_belongs_elsewhere",
1071            LiveAccountNotEnrolled { .. } => "live_account_not_enrolled",
1072            AlreadyEnrolled { .. } => "already_enrolled",
1073            LabelTaken { .. } => "label_taken",
1074            ProviderUnknown { .. } => "provider_unknown",
1075            LabelAmbiguous { .. } => "label_ambiguous",
1076            CannotForgetActiveAccount { .. } => "cannot_forget_active_account",
1077            AccountNotInUse { .. } => "account_not_in_use",
1078            ParkSlotExhausted => "park_slot_exhausted",
1079            ParkedCredentialMissing { .. } => "parked_credential_missing",
1080            ParkedCredentialCorrupt { .. } => "parked_credential_corrupt",
1081            ConfigBackupFailed { .. } => "config_backup_failed",
1082            ConfigWriteFailed { .. } => "config_write_failed",
1083            SwitchRolledBack { .. } => "switch_rolled_back",
1084            SwitchDidNotHold { .. } => "switch_did_not_hold",
1085            SwitchUnverified { .. } => "switch_unverified",
1086            SwitchCorrupted { .. } => "switch_corrupted",
1087            SignInNotInstalled { .. } => "sign_in_not_installed",
1088            SignInNotKept { .. } => "sign_in_not_kept",
1089            RecoveryFailed { .. } => "recovery_failed",
1090            RecoveryRecordCorrupt { .. } => "recovery_record_corrupt",
1091            SessionExpired { .. } => "session_expired",
1092            IdentityUnverifiable { .. } => "identity_unverifiable",
1093            SignedInAccountChanged => "signed_in_account_changed",
1094            LiveLoginRefused { .. } => "live_login_refused",
1095            ReplaceFailed { .. } => "replace_failed",
1096            InstallFailed { .. } => "install_failed",
1097            AccountOnHold { .. } => "account_on_hold",
1098            RecoveryUndetermined { .. } | RecoveryUnfinished { .. } | RecoveryStopped { .. } => {
1099                "recovery_undetermined"
1100            }
1101            RecoveryElsewhere { .. } => "recovery_elsewhere",
1102            ProgramNotFound { tool } => match tool {
1103                ProviderId::Claude => "claude_not_found",
1104                ProviderId::Codex => "codex_not_found",
1105                ProviderId::Desktop => "desktop_not_found",
1106            },
1107            SignInIncomplete => "sign_in_incomplete",
1108            LeftLoginChanged { .. } => "left_login_changed",
1109            StoredLoginChanged { .. } => "stored_login_changed",
1110            LeftLoginNotEnrolled { .. } => "left_login_not_enrolled",
1111            LeftLoginUnidentified { .. } => "left_login_unidentified",
1112            StowStopped { error, .. } | RenewalLost { error, .. } | SaidFirst { error, .. } => {
1113                error.code()
1114            }
1115            SignInNotIsolated { .. } => "sign_in_not_isolated",
1116            RenewalFailed { .. } => "renewal_failed",
1117            SignInInProgress => "sign_in_in_progress",
1118            SignInPinnedToConsole { .. } => "sign_in_pinned_to_console",
1119            AppOpen { .. } => "app_open",
1120            PitboardOpen { .. } => "pitboard_open",
1121            AppStateUnknown { .. } => "app_state_unknown",
1122            LoginFolderUnknown { .. } => "login_folder_unknown",
1123            LoginFolderUnreadable { .. } => "login_folder_unreadable",
1124            SignInUnfinished { .. } => "sign_in_unfinished",
1125            LoginInDoubt { .. } => "login_in_doubt",
1126            LoginFolderBusy { .. } => "login_folder_busy",
1127            DifferentVolume { .. } => "different_volume",
1128            ParksNotPrivate { .. } => "parks_not_private",
1129            MachineUnknown => "machine_unknown",
1130            AppOpenedMidway { .. } => "app_opened_midway",
1131            MoveUndone { .. } => "move_undone",
1132            MoveStopped { .. } => "move_stopped",
1133            SwitchLeftSignedOut { .. } => "switch_left_signed_out",
1134            MoveMixed { .. } => "move_mixed",
1135            UninstallWouldStrand { .. } => "uninstall_would_strand",
1136            SignInSettledElsewhere { .. } => "sign_in_settled_elsewhere",
1137            Elevated { .. } => "elevated",
1138            SystemTooOld { .. } => "system_too_old",
1139            WindowsNotReleased => "windows_not_released",
1140            Usage(_) => "usage",
1141            ConfirmationNeeded { .. } => "confirmation_needed",
1142            Store(e) => e.code(),
1143            Lock(e) => e.code(),
1144        }
1145    }
1146
1147    /// What went wrong underneath, where the failure came from a request to Anthropic.
1148    /// `None` where nothing was asked.
1149    pub fn cause(&self) -> Option<Cause> {
1150        use Error::*;
1151        match self {
1152            IdentityUnverifiable { cause, .. } | LeftLoginUnidentified { cause, .. } => {
1153                Some(*cause)
1154            }
1155            RenewalFailed { cause, .. } => *cause,
1156            SessionExpired { refused: true, .. } | LiveLoginRefused { .. } => {
1157                Some(Cause::LoginRefused)
1158            }
1159            AccountOnHold { .. } => Some(Cause::Refused),
1160            SessionExpired { .. } => Some(Cause::TokenExpired),
1161            StowStopped { error, .. } | RenewalLost { error, .. } | SaidFirst { error, .. } => {
1162                error.cause()
1163            }
1164            _ => None,
1165        }
1166    }
1167
1168    /// Warnings a failed change carries in itself, for the caller to report beside it. Only
1169    /// a failure that happened after something worth warning about was done carries any.
1170    pub(crate) fn take_warnings(&mut self) -> Vec<crate::warning::Warning> {
1171        let mut said = self.take_said_first();
1172        if let Error::SignInNotInstalled { warnings, .. } | Error::StowStopped { warnings, .. } =
1173            self
1174        {
1175            said.append(warnings);
1176        }
1177        said
1178    }
1179
1180    // What the change had done before it refused, outermost first. What is left is the refusal
1181    // itself.
1182    pub(crate) fn take_said_first(&mut self) -> Vec<crate::warning::Warning> {
1183        let mut said = Vec::new();
1184        while let Error::SaidFirst { said: first, error } = self {
1185            said.append(first);
1186            *self = std::mem::replace(error.as_mut(), Error::SignInIncomplete);
1187        }
1188        said
1189    }
1190
1191    // This refusal, after a change that had done what `said` says.
1192    pub(crate) fn after(self, said: Vec<crate::warning::Warning>) -> Error {
1193        if said.is_empty() {
1194            return self;
1195        }
1196        Error::SaidFirst {
1197            said,
1198            error: Box::new(self),
1199        }
1200    }
1201
1202    /// 1 when a request could not be met; 2 when the command line was wrong, or lacks the
1203    /// `--yes` a command that deletes needs with nobody to ask; 3 when a login or Claude
1204    /// Code's files are in a state Pitboard cannot safely act on: an unexpected format, or a
1205    /// login that could not be put back.
1206    pub fn exit_code(&self) -> u8 {
1207        use Error::*;
1208        match self {
1209            // A login or Claude Code's files in a state Pitboard will not act on, which is
1210            // what exit 3 means: not a failure of the attempt, a refusal to attempt.
1211            LiveCredentialShapeUnexpected { .. }
1212            | LiveStoreUnsupported { .. }
1213            | LoginRestricted { .. }
1214            | ClaudeConfigNotJson { .. }
1215            | SwitchCorrupted { .. }
1216            | SwitchUnverified { .. }
1217            | SwitchDidNotHold { .. }
1218            | SignInNotInstalled { .. }
1219            | LiveCredentialElsewhere { .. }
1220            | CredentialTooLarge { .. }
1221            | CustomOauthEndpoint
1222            | SignInPinnedToConsole { .. }
1223            | RecoveryRecordCorrupt { .. }
1224            | LoginFolderUnknown { .. }
1225            | LoginInDoubt { .. }
1226            | DifferentVolume { .. }
1227            | ParksNotPrivate { .. }
1228            | MachineUnknown
1229            | MoveMixed { .. } => 3,
1230            Usage(_) | ConfirmationNeeded { .. } => 2,
1231            Store(e) => e.exit_code(),
1232            StowStopped { error, .. } | RenewalLost { error, .. } | SaidFirst { error, .. } => {
1233                error.exit_code()
1234            }
1235            _ => 1,
1236        }
1237    }
1238}
1239
1240/// `error`'s message as a sentence, ending with a full stop as some do not, for more to be
1241/// said after it.
1242fn sentence(error: &Error) -> String {
1243    let said = error.to_string();
1244    if said.ends_with('.') {
1245        said
1246    } else {
1247        format!("{said}.")
1248    }
1249}
1250
1251pub type Result<T> = std::result::Result<T, Error>;
1252
1253pub(crate) fn codex_home_missing(path: &std::path::Path) -> String {
1254    format!("{}. {CODEX_HOME_REMEDY}", codex_home_no_folder(path))
1255}
1256
1257pub(crate) fn codex_home_no_folder(path: &std::path::Path) -> String {
1258    format!(
1259        "CODEX_HOME is {}, which is no folder, so Codex does not start",
1260        path.display()
1261    )
1262}
1263
1264pub(crate) const CODEX_HOME_REMEDY: &str = "Make that folder, or unset CODEX_HOME";
1265
1266fn job_named(job: crate::schedule::Job) -> &'static str {
1267    match job {
1268        crate::schedule::Job::Renew => "the renewal schedule",
1269        crate::schedule::Job::Watch => "the watch service",
1270    }
1271}
1272
1273fn job_done(job: crate::schedule::Job) -> &'static str {
1274    match job {
1275        crate::schedule::Job::Renew => "scheduled",
1276        crate::schedule::Job::Watch => "installed",
1277    }
1278}
1279
1280fn not_default_home(
1281    home: &std::path::Path,
1282    default: &std::path::Path,
1283    job: crate::schedule::Job,
1284) -> String {
1285    let (serves, which) = match job {
1286        crate::schedule::Job::Renew => ("renews only the parked logins", "To schedule it"),
1287        crate::schedule::Job::Watch => ("watches only the accounts", "To install it"),
1288    };
1289    format!(
1290        "{} {serves} in {}, not those in {}, which PITBOARD_HOME names. Nothing was {}. \
1291         {which} for {}, unset PITBOARD_HOME and install it again.",
1292        job_named(job),
1293        default.display(),
1294        home.display(),
1295        job_done(job),
1296        default.display()
1297    )
1298}
1299
1300fn turn_on(job: crate::schedule::Job) -> &'static str {
1301    match job {
1302        crate::schedule::Job::Renew => "turn on daily renewal",
1303        crate::schedule::Job::Watch => "install the watch service",
1304    }
1305}
1306
1307fn temporary_copy(path: &std::path::Path, job: crate::schedule::Job) -> String {
1308    let turn_on = turn_on(job);
1309    use crate::schedule::TemporaryCopy;
1310    match crate::schedule::temporary_copy(path) {
1311        Some(TemporaryCopy::Zip) => format!(
1312            "{} would run {}, which is in a temporary copy Windows made of a zip it opened. \
1313             Install Pitboard, or extract the zip, and {turn_on} from there.",
1314            job_named(job),
1315            path.display()
1316        ),
1317        Some(TemporaryCopy::AppImage) => format!(
1318            "{} would run {}, which is in the folder an AppImage runs from and is gone once it \
1319             quits. Install Pitboard rather than run it from an AppImage, and {turn_on} from \
1320             there.",
1321            job_named(job),
1322            path.display()
1323        ),
1324        Some(TemporaryCopy::Translocated) | None => format!(
1325            "{} would run {}, which is in a temporary copy macOS made of the app and is gone \
1326             once the app quits. Move Pitboard to your Applications folder, open it from there, \
1327             and {turn_on} again.",
1328            job_named(job),
1329            path.display()
1330        ),
1331    }
1332}
1333
1334fn vault_form_unsupported(form: crate::state::VaultForm) -> String {
1335    let into = match form {
1336        crate::state::VaultForm::SecretService => "the login keyring",
1337        crate::state::VaultForm::Files => "files",
1338    };
1339    let kept = match crate::host::OS {
1340        Os::MacOs => "On macOS, Pitboard keeps parked logins only in the login keychain",
1341        Os::Windows => {
1342            "On Windows, Pitboard keeps parked logins only in files sealed to your Windows account"
1343        }
1344        Os::Linux => "Pitboard keeps parked logins one way on this computer",
1345    };
1346    format!("{kept}, so they cannot be moved into {into}. Nothing has changed.")
1347}
1348
1349fn manager_elsewhere(elsewhere: &crate::schedule::Elsewhere, job: crate::schedule::Job) -> String {
1350    use crate::schedule::Elsewhere;
1351    match elsewhere {
1352        Elsewhere::Folder { units } => format!(
1353            "{} would be written in {}, and your user's systemd does not read units from there. \
1354             Nothing was {}. Give this shell and systemd the same XDG_CONFIG_HOME, set or unset \
1355             as `systemctl --user show-environment` shows systemd's, then install it again.",
1356            job_named(job),
1357            units.display(),
1358            job_done(job)
1359        ),
1360        Elsewhere::Home {
1361            home,
1362            theirs: Some(theirs),
1363        } => format!(
1364            "your user's systemd runs {} with HOME set to {}, not to {}, so it would not serve \
1365             this home. Nothing was changed. Run this from a shell whose HOME is {}.",
1366            job_named(job),
1367            theirs.display(),
1368            home.display(),
1369            theirs.display()
1370        ),
1371        Elsewhere::Home { home, theirs: None } => format!(
1372            "your user's systemd runs {} with no HOME, so it would not serve {}. Nothing was \
1373             changed. Give systemd yours with `systemctl --user set-environment HOME={}`, then \
1374             try again.",
1375            job_named(job),
1376            home.display(),
1377            home.display()
1378        ),
1379    }
1380}
1381
1382fn not_absolute(variable: &str, path: &std::path::Path) -> String {
1383    let holds = if path.as_os_str().is_empty() {
1384        "empty".to_string()
1385    } else {
1386        format!("`{}`, which is not a full path", path.display())
1387    };
1388    format!(
1389        "{variable} is {holds}, so the folder it names would depend on where each program \
1390         runs. Set it to a full path, or unset it; Pitboard reads and changes nothing until \
1391         then."
1392    )
1393}
1394
1395/// [`Error::IdentityUnverifiable`]'s words: what to do follows from why.
1396fn identity_unverifiable(
1397    tool: ProviderId,
1398    program: &str,
1399    login: &Unidentified,
1400    cause: Cause,
1401    detail: &str,
1402) -> String {
1403    let service = tool.service();
1404    let next = match (try_again(cause), cause, login) {
1405        (Some(later), ..) => later.to_owned(),
1406        (None, Cause::AnswerNotUnderstood, _) => "Check for a Pitboard update.".to_owned(),
1407        (None, _, Unidentified::SignedIn | Unidentified::Unnamed) => format!(
1408            "{}, sign in, then try again.",
1409            crate::words::sign_in_yourself(tool, program, true)
1410        ),
1411        (None, _, Unidentified::Parked { label } | Unidentified::SignIn { label }) => {
1412            format!("Sign in to it again with `pitboard enroll {label} --sign-in`.")
1413        }
1414        (None, _, Unidentified::NewSignIn) => "Sign in again.".to_owned(),
1415    };
1416    match login {
1417        Unidentified::SignedIn => format!(
1418            "Pitboard could not confirm with {service} which account is signed in ({detail}), \
1419             and will not move a login it cannot identify. {next}"
1420        ),
1421        Unidentified::Parked { label } => format!(
1422            "Pitboard could not confirm with {service} whose login is parked for `{label}` \
1423             ({detail}), and will not put in use a login it cannot identify. {next}"
1424        ),
1425        Unidentified::SignIn { label } => format!(
1426            "Pitboard could not confirm with {service} whose login the sign-in for `{label}` \
1427             made ({detail}), and keeps no login it cannot identify. {next}"
1428        ),
1429        Unidentified::NewSignIn => format!(
1430            "Pitboard could not confirm with {service} whose login the sign-in made ({detail}), \
1431             and keeps no login it cannot identify. {next}"
1432        ),
1433        Unidentified::Unnamed => format!(
1434            "{service} named the account of {}'s login and would not give its email \
1435             ({detail}), and Pitboard keeps every account under its email. {next}",
1436            tool.name()
1437        ),
1438    }
1439}
1440
1441fn live_login_refused(tool: ProviderId, label: &str, detail: &str) -> String {
1442    format!(
1443        "{} Run `pitboard use {label} --yes` to replace it.",
1444        crate::words::replacing(tool, &format!("`{label}`"), detail)
1445    )
1446}
1447
1448/// [`Error::AccountOnHold`]'s words.
1449fn account_on_hold(tool: ProviderId, login: &Unidentified, link: Option<&str>) -> String {
1450    let service = tool.service();
1451    let see = link.map(|link| format!(" ({link})")).unwrap_or_default();
1452    let whose = match login {
1453        Unidentified::SignedIn | Unidentified::Unnamed => {
1454            format!("the account of {}'s login in use", tool.name())
1455        }
1456        Unidentified::Parked { label } | Unidentified::SignIn { label } => {
1457            format!("`{label}`'s account")
1458        }
1459        Unidentified::NewSignIn => "the account signed in to".to_owned(),
1460    };
1461    format!(
1462        "{service} has put {whose} on hold{see}. Pitboard keeps its login. Follow {service}'s \
1463         instructions for the account, then try again."
1464    )
1465}
1466
1467/// When asking again is the way on, what to say about it.
1468fn try_again(cause: Cause) -> Option<&'static str> {
1469    match cause {
1470        Cause::Unreachable => Some("Check the connection and try again."),
1471        Cause::RateLimited => Some("Try again in a few minutes."),
1472        Cause::ServerError => Some("Try again later."),
1473        Cause::Refused | Cause::AnswerNotUnderstood | Cause::LoginRefused | Cause::TokenExpired => {
1474            None
1475        }
1476    }
1477}
1478
1479/// [`Error::SessionExpired`]'s words.
1480fn session_expired(tool: ProviderId, program: &str, refused: bool) -> String {
1481    if refused {
1482        return format!(
1483            "{}'s login in use has expired and cannot be renewed, so Pitboard cannot confirm \
1484             which account is signed in. {}, sign in, then try again.",
1485            tool.name(),
1486            crate::words::sign_in_yourself(tool, program, true)
1487        );
1488    }
1489    format!(
1490        "{}'s session has expired, so Pitboard cannot confirm which account is signed in. \
1491         {} once so it refreshes, then try again.",
1492        tool.name(),
1493        crate::words::run_it(tool, program, true)
1494    )
1495}
1496
1497// What makes a tool's live login readable again, where it could not be read.
1498fn make_readable(os: Os, tool: ProviderId) -> &'static str {
1499    match tool {
1500        ProviderId::Claude => match os {
1501            Os::MacOs => "Unlock the keychain",
1502            // The file is Claude Code's only store there (`live_chain_order`).
1503            Os::Linux => "Make Claude Code's .credentials.json readable to you again",
1504            Os::Windows => {
1505                "Check that you can read and change Claude Code's folder and its .credentials.json"
1506            }
1507        },
1508        ProviderId::Codex => "Make Codex's auth.json readable to you again",
1509        ProviderId::Desktop => "Quit Claude",
1510    }
1511}
1512
1513fn login_elsewhere(os: Os, email: &str) -> String {
1514    format!(
1515        "{}. It will not write a login where nobody reads it. This usually means Claude Code has \
1516         started keeping logins somewhere Pitboard does not know about yet: check for a Pitboard \
1517         update, and report it with `pitboard doctor --json` if there is none.",
1518        crate::words::named_but_not_found(os, email)
1519    )
1520}
1521
1522// A keychain's ceiling is what `security` reads from stdin; Credential Manager's, 256 pieces.
1523fn too_large(
1524    store: SecretStore,
1525    tool: ProviderId,
1526    label: &str,
1527    bytes: usize,
1528    limit: usize,
1529) -> String {
1530    match store {
1531        SecretStore::Keychain => format!(
1532            "the login for `{label}` needs {bytes} bytes and `security` reads {limit} from \
1533             stdin, so it can only be written on the argument line, which PITBOARD_NO_ARGV \
1534             forbids. {}",
1535            smaller(tool)
1536        ),
1537        SecretStore::CredentialManager => format!(
1538            "the login for `{label}` needs {}. Sign out of MCP servers you no longer use to make \
1539             the login smaller.",
1540            crate::words::past_credential_manager(bytes, limit)
1541        ),
1542    }
1543}
1544
1545// What makes a login smaller, where anything does.
1546fn smaller(tool: ProviderId) -> &'static str {
1547    match tool {
1548        ProviderId::Claude => {
1549            "Unset it, or sign out of MCP servers you no longer use to make the login smaller."
1550        }
1551        ProviderId::Codex | ProviderId::Desktop => "Unset it to let Pitboard write it.",
1552    }
1553}
1554
1555/// Which write took a switched-in login away again, as far as each tool is known to make
1556/// one, and what that leaves.
1557fn after_it_did_not_hold(tool: ProviderId, program: &str, from: &str, to: &str) -> String {
1558    match tool {
1559        ProviderId::Claude => format!(
1560            "Claude Code removes a login without taking the write lock when `/logout` has \
1561             given up waiting, which is the one write Pitboard cannot exclude. Nothing was \
1562             lost: both `{from}` and `{to}` are parked. Run `{program}` and sign in to any \
1563             enrolled account, then `pitboard use {to}`."
1564        ),
1565        // Not "nothing was lost": the likeliest writer is a codex session refreshing the
1566        // outgoing account, which spends the token in that account's park, and `codex
1567        // login` would revoke whatever login is left in auth.json.
1568        ProviderId::Codex => format!(
1569            "Codex takes no lock, so a codex session still running from before the switch, \
1570             refreshing or signing out, rewrote auth.json underneath it. `{to}` is still \
1571             parked. `{from}`'s park may hold a token that refresh spent. Quit every running \
1572             codex, then run `pitboard` to see what is signed in; do not run `{program} login` \
1573             or `{program} logout` until you have, because either revokes the login they find."
1574        ),
1575        ProviderId::Desktop => "Claude was opened before Pitboard finished and wrote its own \
1576                                login back. Quit Claude, then run `pitboard` to see which \
1577                                account it holds."
1578            .into(),
1579    }
1580}
1581
1582/// Where a new login that could not be put in use went, and the way back from there.
1583fn not_in_use(tool: ProviderId, program: &str, label: &str, parked: bool) -> String {
1584    if parked {
1585        format!(
1586            "The new login is parked, so it is not lost. Run `pitboard` to see what is \
1587             signed in; if nothing is, {} and sign in to any enrolled account, then \
1588             `pitboard use {label}`.",
1589            crate::words::sign_in_yourself(tool, program, false)
1590        )
1591    } else {
1592        format!(
1593            "It could not be parked either: {} and sign in to `{label}` again.",
1594            crate::words::sign_in_yourself(tool, program, false)
1595        )
1596    }
1597}
1598
1599// What a step of a Claude Desktop change says to do once it has refused.
1600#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1601pub enum Then {
1602    Nothing,
1603    OpenAndQuit,
1604    UpdatePitboard,
1605    CopyAside,
1606    SignInAndEnrol,
1607}
1608
1609impl Then {
1610    // With a space after it, where it says anything.
1611    pub(crate) fn said(self) -> &'static str {
1612        match self {
1613            Then::Nothing => "",
1614            Then::OpenAndQuit => "Open Claude, quit it with Command-Q, then run this again. ",
1615            Then::UpdatePitboard => {
1616                "Update Pitboard, or report it at https://github.com/datlechin/pitboard/issues if \
1617                 no release reads it yet. "
1618            }
1619            Then::CopyAside => {
1620                "Claude resets a settings file it cannot read when it opens, so copy it aside, \
1621                 open Claude, quit it with Command-Q, then run this again. "
1622            }
1623            Then::SignInAndEnrol => {
1624                "Open Claude. If it asks you to sign in, sign in. Quit it with Command-Q, then \
1625                 run `pitboard enroll desktop/<label>` for the account it shows. "
1626            }
1627        }
1628    }
1629}
1630
1631// Why the login Claude holds cannot be taken as any account's without the person's word.
1632#[derive(Debug, Clone, PartialEq, Eq)]
1633pub enum LoginDoubt {
1634    // `named`: the account Claude names, as typed; None for one Pitboard has not enrolled
1635    NamedAnother {
1636        recorded: String,
1637        named: Option<String>,
1638    },
1639    // `label` was signed in to outside Pitboard, beside the login it parked
1640    SignedInOutside {
1641        label: String,
1642    },
1643}
1644
1645fn pitboard_open(os: Os, home: &std::path::Path) -> String {
1646    let quit = match os {
1647        Os::MacOs => "Quit it from its item in the menu bar",
1648        // Every desktop shows its window; only some show a tray.
1649        Os::Linux => "Quit it with Ctrl+Q in its window or from its tray menu",
1650        Os::Windows => "Exit it from its icon's menu in the notification area",
1651    };
1652    format!(
1653        "the Pitboard app is open, and it would make {} again once it was gone. {quit}, then \
1654         run this again. Nothing has changed.",
1655        home.display()
1656    )
1657}
1658
1659fn app_open(app: &str, still: &[String]) -> String {
1660    if still.is_empty() {
1661        return format!(
1662            "{app} is open, and Pitboard changes its login only while it is closed. Quit {app} \
1663             with Command-Q, then run this again. Nothing has changed."
1664        );
1665    }
1666    format!(
1667        "{app} has quit, and {} from it is still running, and Pitboard changes {app}'s login \
1668         only while all of it is closed. {} Nothing has changed.",
1669        crate::words::listed(still.to_vec()),
1670        crate::words::wait_for_still(crate::host::OS, "run this again")
1671    )
1672}
1673
1674fn in_doubt(tool: ProviderId, why: &LoginDoubt) -> String {
1675    let enroll = Key::new(tool, "<label>").typed();
1676    match why {
1677        LoginDoubt::NamedAnother { recorded, named } => {
1678            let named = named.as_ref().map_or_else(
1679                || "an account Pitboard has not enrolled".to_string(),
1680                |label| format!("`{label}`"),
1681            );
1682            format!(
1683                "Pitboard recorded this {program} login as `{recorded}`'s, and {program} names \
1684                 {named} for it. Open {program}, check which account it shows, quit it with \
1685                 Command-Q, then run `pitboard enroll {enroll}` under that account's name. \
1686                 Nothing has changed.",
1687                program = tool.program()
1688            )
1689        }
1690        LoginDoubt::SignedInOutside { label } => format!(
1691            "{program} was signed in to `{label}` outside Pitboard, so Pitboard cannot tell this \
1692             login from the one it parked. Open {program}, check which account it shows, and \
1693             quit it with Command-Q. If it shows `{label}`, run `pitboard enroll {label}`, then \
1694             this again. If it shows another account, run `pitboard enroll {enroll}` under that \
1695             account's name. Nothing has changed.",
1696            program = tool.program()
1697        ),
1698    }
1699}
1700
1701fn not_enrolled(tool: ProviderId, who: &str) -> String {
1702    let enroll = Key::new(tool, "<label>").typed();
1703    match tool {
1704        ProviderId::Claude | ProviderId::Codex => format!(
1705            "{who} is signed in but not enrolled, so it cannot be parked. Run `pitboard enroll \
1706             {enroll}` for it first."
1707        ),
1708        ProviderId::Desktop => format!(
1709            "Claude is signed in to an account Pitboard has not enrolled, so it cannot be \
1710             parked. Run `pitboard enroll {enroll}` for it first."
1711        ),
1712    }
1713}
1714
1715fn already_enrolled(
1716    tool: ProviderId,
1717    email: &str,
1718    label: &str,
1719    asked: &str,
1720    waited: bool,
1721) -> String {
1722    match tool {
1723        ProviderId::Claude | ProviderId::Codex => format!(
1724            "{email} is already enrolled as `{label}`. To add a different account, run \
1725             `pitboard enroll {} --sign-in`.",
1726            Key::new(tool, "<label>").typed()
1727        ),
1728        ProviderId::Desktop if waited => format!(
1729            "Claude is signed in to `{label}`. Run `pitboard enroll {label}` to record that \
1730             login, then add another with `pitboard enroll {asked} --sign-in`."
1731        ),
1732        ProviderId::Desktop => format!(
1733            "Claude is signed in to `{label}`, which is enrolled already. To add `{asked}`, run \
1734             `pitboard enroll {asked} --sign-in`."
1735        ),
1736    }
1737}
1738
1739fn parks_not_private(path: &std::path::Path, why: crate::host::Private) -> String {
1740    use crate::host::Private;
1741    let path = path.display();
1742    let own = "Point `PITBOARD_HOME` at a folder of your own on this volume, then run this again.";
1743    let said = match why {
1744        Private::Shared => {
1745            format!("{path} can be reached by others. Run `chmod 700 {path}`, then run this again.")
1746        }
1747        Private::Link => {
1748            format!("{path} is a link, so Pitboard parks no Claude Desktop login there. {own}")
1749        }
1750        Private::NotOwn => {
1751            format!("{path} is not yours, so Pitboard parks no Claude Desktop login there. {own}")
1752        }
1753        Private::NotADirectory | Private::Missing | Private::Yes => format!(
1754            "{path} is not a folder, so Pitboard parks no Claude Desktop login there. {own}"
1755        ),
1756    };
1757    format!("{said} Nothing has changed.")
1758}
1759
1760fn opened_midway(app: &str, label: Option<&str>) -> String {
1761    match label {
1762        Some(label) => format!(
1763            "{app} was opened while Pitboard moved `{label}`'s login, so Pitboard stopped. \
1764             Nothing is lost. Quit {app} with Command-Q, then run this again: Pitboard settles \
1765             the move first."
1766        ),
1767        None => format!(
1768            "{app} was opened while Pitboard set aside the account name {app} kept, so \
1769             Pitboard stopped. Nothing is lost. Quit {app} with Command-Q, then run this again."
1770        ),
1771    }
1772}
1773
1774fn would_strand(label: Option<&str>, set_aside: &[PathBuf]) -> String {
1775    let every = "so uninstalling would delete every Claude Desktop login Pitboard holds.";
1776    match label {
1777        Some(label) => format!(
1778            "No Claude Desktop account is in use, and `{label}` is parked, {every} Run `pitboard \
1779             use {label}`, then uninstall, or `pitboard forget` each Claude Desktop account first."
1780        ),
1781        None => {
1782            let held = match set_aside {
1783                [_] => "holds a Claude Desktop login",
1784                _ => "hold Claude Desktop logins",
1785            };
1786            let folders = set_aside.iter().map(|path| path.display().to_string());
1787            format!(
1788                "No Claude Desktop account is in use, and {} {held} Pitboard set aside, {every} \
1789                 Run `pitboard enroll desktop/<label> --sign-in` to sign in to an account you \
1790                 keep, then uninstall.",
1791                crate::words::listed(folders)
1792            )
1793        }
1794    }
1795}
1796
1797fn move_mixed(label: &str, places: &[String]) -> String {
1798    format!(
1799        "Giving up would leave parts of `{label}` beside another login in Claude's folder: {}. \
1800         Nothing has changed. {}",
1801        places.join(", "),
1802        crate::words::mixed_way_out(label)
1803    )
1804}
1805
1806fn left_signed_out(from: Option<&str>, to: &str, detail: &str) -> String {
1807    match from {
1808        Some(from) => format!(
1809            "`{from}` is parked, and `{to}` could not be put in use ({detail}). Claude is \
1810             signed out and both logins are parked. Run `pitboard use {to}` again, or `pitboard \
1811             use {from}` to go back."
1812        ),
1813        None => format!(
1814            "`{to}` could not be put in use ({detail}). Claude is signed out and `{to}` is \
1815             still parked. Run `pitboard use {to}` again."
1816        ),
1817    }
1818}
1819
1820fn warm_up_unsupported(tool: ProviderId, label: &str) -> String {
1821    match tool {
1822        ProviderId::Claude | ProviderId::Codex => format!(
1823            "`{label}` is a {name} account, and Pitboard warms up Claude Code accounts only: when \
1824             a {name} period starts has not been measured.",
1825            name = tool.name()
1826        ),
1827        ProviderId::Desktop => format!(
1828            "`{label}` is a Claude Desktop account, and Pitboard sends no request for one, so it \
1829             warms up none."
1830        ),
1831    }
1832}
1833
1834/// "from `work` to `home`", or "to `home`" for a replacement, which has no account going out.
1835fn between(from: &str, to: &str) -> String {
1836    if from.is_empty() {
1837        format!("to `{to}`")
1838    } else {
1839        format!("from `{from}` to `{to}`")
1840    }
1841}
1842
1843fn recovery_undetermined(
1844    tool: ProviderId,
1845    program: &str,
1846    from: &str,
1847    to: &str,
1848    detail: &str,
1849) -> String {
1850    match tool {
1851        ProviderId::Claude | ProviderId::Codex => format!(
1852            "an earlier switch {} was interrupted, and Pitboard cannot yet \
1853             tell whether it finished ({detail}). Nothing was changed. {} once so its session \
1854             is current, then try again.",
1855            between(from, to),
1856            crate::words::run_it(tool, program, true)
1857        ),
1858        ProviderId::Desktop => format!(
1859            "An earlier move of `{to}`'s login was interrupted, and Pitboard cannot tell where it \
1860             stopped ({detail}). Nothing has changed. {}",
1861            crate::words::undetermined_way_out()
1862        ),
1863    }
1864}
1865
1866fn recovery_elsewhere(tool: ProviderId, from: &str, to: &str, slot: &str) -> String {
1867    match tool {
1868        ProviderId::Claude | ProviderId::Codex => format!(
1869            "an earlier switch of {} {} was interrupted while its login was at {slot}, and \
1870             this run reads it from somewhere else, so it cannot tell what that switch did. \
1871             Nothing was changed. {} to finish it, or `pitboard abandon` to keep every login \
1872             it names and move on.",
1873            tool.name(),
1874            between(from, to),
1875            crate::words::pointing_where_it_did(tool)
1876        ),
1877        ProviderId::Desktop => format!(
1878            "An earlier move of `{to}`'s login was interrupted while Claude kept its data in \
1879             {slot}, and this run finds it somewhere else. Nothing has changed. {}",
1880            crate::words::elsewhere_way_out(tool)
1881        ),
1882    }
1883}
1884
1885#[cfg(test)]
1886mod tests {
1887    use super::*;
1888
1889    // Claude Code keeps no keychain on Windows: its file, or Credential Manager. On Linux the
1890    // file alone.
1891    #[test]
1892    fn claude_codes_lost_and_unreadable_logins_are_worded_for_each_system() {
1893        for (store, too_large_said) in [
1894            (
1895                SecretStore::Keychain,
1896                "the login for `l` needs 9 bytes and `security` reads 4 from stdin, so it can only \
1897                 be written on the argument line, which PITBOARD_NO_ARGV forbids. Unset it, or \
1898                 sign out of MCP servers you no longer use to make the login smaller.",
1899            ),
1900            (
1901                SecretStore::CredentialManager,
1902                "the login for `l` needs 9 bytes, past the 4 Claude Code keeps in Credential \
1903                 Manager. Sign out of MCP servers you no longer use to make the login smaller.",
1904            ),
1905        ] {
1906            assert_eq!(
1907                too_large(store, ProviderId::Claude, "l", 9, 4),
1908                too_large_said
1909            );
1910        }
1911        for (os, places, readable) in [
1912            (
1913                Os::MacOs,
1914                "in the keychain or in the file it also reads",
1915                "Unlock the keychain",
1916            ),
1917            (
1918                Os::Linux,
1919                "in .credentials.json",
1920                "Make Claude Code's .credentials.json readable to you again",
1921            ),
1922            (
1923                Os::Windows,
1924                "in .credentials.json or in Credential Manager",
1925                "Check that you can read and change Claude Code's folder and its .credentials.json",
1926            ),
1927        ] {
1928            assert!(
1929                login_elsewhere(os, "a@example.com").starts_with(&format!(
1930                    "Claude Code's config says a@example.com is signed in, but Pitboard cannot \
1931                     find that login {places}. It will not write a login where nobody reads it."
1932                )),
1933                "{os:?}"
1934            );
1935            assert_eq!(make_readable(os, ProviderId::Claude), readable);
1936        }
1937    }
1938
1939    // The Linux app's main menu has no Quit, as GNOME's apps have none.
1940    #[test]
1941    fn a_refusal_while_the_app_runs_says_how_each_system_quits_it() {
1942        let home = std::path::Path::new("/home/x/.pitboard");
1943        let quit = |os| {
1944            let said = pitboard_open(os, home);
1945            let (_, rest) = said.split_once("again once it was gone. ").expect("a quit");
1946            rest.to_owned()
1947        };
1948        assert_eq!(
1949            quit(Os::MacOs),
1950            "Quit it from its item in the menu bar, then run this again. Nothing has changed."
1951        );
1952        assert_eq!(
1953            quit(Os::Linux),
1954            "Quit it with Ctrl+Q in its window or from its tray menu, then run this again. \
1955             Nothing has changed."
1956        );
1957        assert_eq!(
1958            quit(Os::Windows),
1959            "Exit it from its icon's menu in the notification area, then run this again. \
1960             Nothing has changed."
1961        );
1962    }
1963
1964    #[test]
1965    fn no_sentence_said_on_linux_names_a_keychain_a_menu_bar_or_activity_monitor() {
1966        let linux = Os::Linux;
1967        let named: Vec<String> = ProviderId::ALL
1968            .iter()
1969            .map(|tool| make_readable(linux, *tool).to_owned())
1970            .chain([
1971                login_elsewhere(linux, "a@example.com"),
1972                pitboard_open(linux, std::path::Path::new("/home/x/.pitboard")),
1973            ])
1974            .filter(|said| crate::words::names_what_linux_has_not(said))
1975            .collect();
1976        assert!(named.is_empty(), "{named:#?}");
1977    }
1978
1979    // Word for word what each said before a tool could be an app, with npm's `.cmd` where found.
1980    #[test]
1981    fn every_claude_code_and_codex_sentence_reads_as_it_did() {
1982        let said = |tool: ProviderId, spelling: Spelling| {
1983            let moved = |make: fn(ProviderId, Spelling, String, String, String) -> Error| {
1984                make(tool, spelling, "a".into(), "b".into(), "d".into()).to_string()
1985            };
1986            let not_installed = |parked| Error::SignInNotInstalled {
1987                tool,
1988                label: "l".into(),
1989                detail: "d".into(),
1990                parked,
1991                spelling,
1992                warnings: Vec::new(),
1993            };
1994            vec![
1995                Error::LiveCredentialAbsent {
1996                    tool,
1997                    label: None,
1998                    spelling,
1999                }
2000                .to_string(),
2001                moved(
2002                    |tool, spelling, from, to, detail| Error::RecoveryUndetermined {
2003                        tool,
2004                        from,
2005                        to,
2006                        detail,
2007                        spelling,
2008                    },
2009                ),
2010                moved(|tool, spelling, from, to, detail| Error::SwitchCorrupted {
2011                    tool,
2012                    from,
2013                    to,
2014                    detail,
2015                    spelling,
2016                }),
2017                moved(|tool, _, from, to, slot| Error::RecoveryElsewhere {
2018                    tool,
2019                    from,
2020                    to,
2021                    slot,
2022                }),
2023                Error::RenewalLost {
2024                    tool,
2025                    error: Box::new(Error::SignedInAccountChanged),
2026                    spelling,
2027                }
2028                .to_string(),
2029                Error::SessionExpired {
2030                    tool,
2031                    refused: true,
2032                    spelling,
2033                }
2034                .to_string(),
2035                Error::SessionExpired {
2036                    tool,
2037                    refused: false,
2038                    spelling,
2039                }
2040                .to_string(),
2041                not_installed(true).to_string(),
2042                not_installed(false).to_string(),
2043                crate::warning::Warning::SignInParkedNotInUse {
2044                    tool,
2045                    label: "l".into(),
2046                    why: "w".into(),
2047                    spelling,
2048                }
2049                .to_string(),
2050                Error::LiveAccountNotEnrolled {
2051                    tool,
2052                    who: "a@b.c".into(),
2053                }
2054                .to_string(),
2055                Error::AlreadyEnrolled {
2056                    tool,
2057                    email: "a@b.c".into(),
2058                    label: "l".into(),
2059                    asked: "other".into(),
2060                    waited: false,
2061                }
2062                .to_string(),
2063            ]
2064        };
2065        let before = |name: &str, sign_in: &str, run: &str, home: &str, enroll: &str| {
2066            vec![
2067                format!(
2068                    "nothing is signed in to {name} right now. Run `{sign_in}`, sign in, then try again."
2069                ),
2070                format!(
2071                    "an earlier switch from `a` to `b` was interrupted, and Pitboard cannot yet \
2072                     tell whether it finished (d). Nothing was changed. Run `{run}` once so its \
2073                     session is current, then try again."
2074                ),
2075                format!(
2076                    "could not sign in as `b`, and could not put `a` back either (d). `a`'s login \
2077                     is still parked: run `{sign_in}` and sign in to any enrolled account, then \
2078                     `pitboard use a`."
2079                ),
2080                format!(
2081                    "an earlier switch of {name} from `a` to `b` was interrupted while its login \
2082                     was at d, and this run reads it from somewhere else, so it cannot tell what \
2083                     that switch did. Nothing was changed. Run Pitboard with {home} pointing \
2084                     where it did to finish it, or `pitboard abandon` to keep every login it \
2085                     names and move on."
2086                ),
2087                format!(
2088                    "the signed-in account changed while switching. Nothing was moved; try again. \
2089                     Pitboard renewed {name}'s login and could not save the renewed login, so \
2090                     the refresh token stored is spent. Run `{sign_in}`, sign in, then try again."
2091                ),
2092                format!(
2093                    "{name}'s login in use has expired and cannot be renewed, so Pitboard cannot \
2094                     confirm which account is signed in. Run `{sign_in}`, sign in, then try again."
2095                ),
2096                format!(
2097                    "{name}'s session has expired, so Pitboard cannot confirm which account is \
2098                     signed in. Run `{run}` once so it refreshes, then try again."
2099                ),
2100                format!(
2101                    "signed in to `l` again, and Pitboard could not confirm that its new login \
2102                     took the place of the one in use (d), so {name} may have no login for it \
2103                     now. The new login is parked, so it is not lost. Run `pitboard` to see what \
2104                     is signed in; if nothing is, run `{sign_in}` and sign in to any enrolled \
2105                     account, then `pitboard use l`."
2106                ),
2107                format!(
2108                    "signed in to `l` again, and Pitboard could not confirm that its new login \
2109                     took the place of the one in use (d), so {name} may have no login for it \
2110                     now. It could not be parked either: run `{sign_in}` and sign in to `l` again."
2111                ),
2112                format!(
2113                    "{name} goes on with the login it has: Pitboard could not tell whose it is \
2114                     (w), so it parked the new login for `l` rather than write over that one. If \
2115                     that login no longer works, run `{sign_in}` and sign in to `l` there."
2116                ),
2117                format!(
2118                    "a@b.c is signed in but not enrolled, so it cannot be parked. Run `pitboard \
2119                     enroll {enroll}` for it first."
2120                ),
2121                format!(
2122                    "a@b.c is already enrolled as `l`. To add a different account, run `pitboard \
2123                     enroll {enroll} --sign-in`."
2124                ),
2125            ]
2126        };
2127        let pairs = |tool, spelling, expected: Vec<String>| {
2128            for (now, then) in said(tool, spelling).into_iter().zip(expected) {
2129                assert_eq!(now, then, "{tool}");
2130            }
2131        };
2132        for spelling in [Spelling::Bare, Spelling::Cmd] {
2133            let (claude, codex) = (
2134                spelling.of(ProviderId::Claude),
2135                spelling.of(ProviderId::Codex),
2136            );
2137            pairs(
2138                ProviderId::Claude,
2139                spelling,
2140                before(
2141                    "Claude Code",
2142                    claude,
2143                    claude,
2144                    "CLAUDE_CONFIG_DIR",
2145                    "<label>",
2146                ),
2147            );
2148            pairs(
2149                ProviderId::Codex,
2150                spelling,
2151                before(
2152                    "Codex",
2153                    &format!("{codex} login"),
2154                    codex,
2155                    "CODEX_HOME",
2156                    "codex/<label>",
2157                ),
2158            );
2159        }
2160        // Claude Desktop has words of its own for each, and none names a program to run.
2161        for sentence in said(ProviderId::Desktop, Spelling::Bare) {
2162            assert!(!sentence.contains("Run `Claude`"), "{sentence}");
2163            assert!(!sentence.contains("run `Claude`"), "{sentence}");
2164        }
2165        let absent = |label: Option<&str>| {
2166            Error::LiveCredentialAbsent {
2167                tool: ProviderId::Desktop,
2168                label: label.map(str::to_string),
2169                spelling: Spelling::Bare,
2170            }
2171            .to_string()
2172        };
2173        assert_eq!(
2174            absent(Some("desktop/travel")),
2175            "Claude is not signed in. Run `pitboard enroll desktop/travel --sign-in`, then sign \
2176             in inside Claude and quit it: Pitboard waits for that, and sets aside any account \
2177             name Claude kept first."
2178        );
2179        assert!(absent(None).contains("`pitboard enroll desktop/<label> --sign-in`"));
2180    }
2181
2182    // Windows PowerShell 5.1 refuses the `claude.ps1` beside npm's `claude.cmd`.
2183    #[test]
2184    fn every_command_to_run_names_the_cmd_pitboard_found() {
2185        let missing = Error::ClaudeConfigMissing {
2186            path: PathBuf::from("C:/Users/x/.claude.json"),
2187            spelling: Spelling::Cmd,
2188        };
2189        assert!(
2190            missing
2191                .to_string()
2192                .ends_with("Run `claude.cmd` once, sign in, then try again."),
2193            "{missing}"
2194        );
2195        let gone = |tool, spelling| {
2196            Error::SwitchDidNotHold {
2197                tool,
2198                from: "a".into(),
2199                to: "b".into(),
2200                spelling,
2201            }
2202            .to_string()
2203        };
2204        let claude = gone(ProviderId::Claude, Spelling::Cmd);
2205        assert!(
2206            claude.contains("Run `claude.cmd` and sign in to any enrolled account"),
2207            "{claude}"
2208        );
2209        let codex = gone(ProviderId::Codex, Spelling::Cmd);
2210        assert!(
2211            codex.contains("do not run `codex.cmd login` or `codex.cmd logout`"),
2212            "{codex}"
2213        );
2214        let broken = crate::store::Error::Broken {
2215            why: "`t` lacks piece #2 of the 3 its manifest names".into(),
2216            spelling: Spelling::Cmd,
2217        };
2218        assert!(
2219            broken
2220                .to_string()
2221                .contains("`claude.cmd auth logout` deletes it"),
2222            "{broken}"
2223        );
2224    }
2225
2226    #[test]
2227    fn a_refusal_names_the_account_or_what_still_runs() {
2228        assert_eq!(
2229            Error::CannotForgetActiveAccount {
2230                label: "alpha".into()
2231            }
2232            .to_string(),
2233            "`alpha` is signed in; switch to another account before forgetting it."
2234        );
2235        assert_eq!(
2236            Error::AccountUnknown {
2237                label: "nobody".into(),
2238                enrolled: Enrolled(vec!["alpha".into(), "beta".into()]),
2239            }
2240            .to_string(),
2241            "no account is enrolled as `nobody`. Enrolled: `alpha`, `beta`. Run `pitboard \
2242             enroll nobody --sign-in` to add it."
2243        );
2244        assert_eq!(
2245            Error::AppOpen {
2246                app: "Claude",
2247                still: Vec::new()
2248            }
2249            .to_string(),
2250            "Claude is open, and Pitboard changes its login only while it is closed. Quit \
2251             Claude with Command-Q, then run this again. Nothing has changed."
2252        );
2253        assert_eq!(
2254            Error::AppOpen {
2255                app: "Claude",
2256                still: vec!["ShipIt (pid 812)".into()]
2257            }
2258            .to_string(),
2259            format!(
2260                "Claude has quit, and ShipIt (pid 812) from it is still running, and Pitboard \
2261                 changes Claude's login only while all of it is closed. {} Nothing has changed.",
2262                crate::words::wait_for_still(crate::host::OS, "run this again")
2263            )
2264        );
2265    }
2266
2267    #[test]
2268    fn a_moves_refusals_say_their_code_their_exit_and_what_to_do() {
2269        let said = |error: Error| (error.code(), error.exit_code(), error.to_string());
2270        let label = || "desktop/work".to_string();
2271        assert_eq!(
2272            said(Error::MachineUnknown),
2273            (
2274                "machine_unknown",
2275                3,
2276                "Pitboard could not read this Mac's identity, which it writes beside every \
2277                 parked Claude Desktop login so it never puts back one parked on another Mac. \
2278                 Nothing has changed."
2279                    .into()
2280            )
2281        );
2282        assert_eq!(
2283            said(Error::AppOpenedMidway {
2284                app: "Claude",
2285                label: Some(label())
2286            }),
2287            (
2288                "app_opened_midway",
2289                1,
2290                "Claude was opened while Pitboard moved `desktop/work`'s login, so Pitboard \
2291                 stopped. Nothing is lost. Quit Claude with Command-Q, then run this again: \
2292                 Pitboard settles the move first."
2293                    .into()
2294            )
2295        );
2296        assert!(
2297            said(Error::AppOpenedMidway {
2298                app: "Claude",
2299                label: None
2300            })
2301            .2
2302            .contains("set aside the account name Claude kept")
2303        );
2304        assert_eq!(
2305            said(Error::SwitchLeftSignedOut {
2306                from: Some(label()),
2307                to: "desktop/home".into(),
2308                detail: "d".into()
2309            }),
2310            (
2311                "switch_left_signed_out",
2312                1,
2313                "`desktop/work` is parked, and `desktop/home` could not be put in use (d). \
2314                 Claude is signed out and both logins are parked. Run `pitboard use \
2315                 desktop/home` again, or `pitboard use desktop/work` to go back."
2316                    .into()
2317            )
2318        );
2319        assert!(
2320            said(Error::SwitchLeftSignedOut {
2321                from: None,
2322                to: "desktop/home".into(),
2323                detail: "d".into()
2324            })
2325            .2
2326            .ends_with("`desktop/home` is still parked. Run `pitboard use desktop/home` again.")
2327        );
2328        assert_eq!(
2329            said(Error::RecoveryStopped {
2330                label: label(),
2331                detail: "d".into()
2332            }),
2333            (
2334                "recovery_undetermined",
2335                1,
2336                "Pitboard stopped while settling an interrupted move of `desktop/work`'s login \
2337                 (d). Nothing is lost. Keep Claude closed and run this again: Pitboard settles \
2338                 the move first. If it stops again, `pitboard abandon` keeps every folder and \
2339                 moves on."
2340                    .into()
2341            )
2342        );
2343        let parks = PathBuf::from("/p/parks");
2344        for (why, words) in [
2345            (crate::host::Private::Shared, "Run `chmod 700 /p/parks`"),
2346            (crate::host::Private::Link, "/p/parks is a link"),
2347            (crate::host::Private::NotOwn, "/p/parks is not yours"),
2348        ] {
2349            let (code, exit, sentence) = said(Error::ParksNotPrivate {
2350                path: parks.clone(),
2351                why,
2352            });
2353            assert_eq!((code, exit), ("parks_not_private", 3));
2354            assert!(sentence.contains(words), "{sentence}");
2355            assert!(sentence.ends_with("Nothing has changed."), "{sentence}");
2356        }
2357        for (error, code, exit) in [
2358            (
2359                Error::DifferentVolume {
2360                    parks: parks.clone(),
2361                    root: PathBuf::from("/data"),
2362                },
2363                "different_volume",
2364                3,
2365            ),
2366            (
2367                Error::MoveUndone {
2368                    label: label(),
2369                    detail: "d".into(),
2370                },
2371                "move_undone",
2372                1,
2373            ),
2374            (
2375                Error::MoveStopped {
2376                    label: label(),
2377                    detail: "d".into(),
2378                },
2379                "move_stopped",
2380                1,
2381            ),
2382            (
2383                Error::MoveMixed {
2384                    label: label(),
2385                    places: vec!["`a` in Claude's folder".into()],
2386                },
2387                "move_mixed",
2388                3,
2389            ),
2390            (
2391                Error::UninstallWouldStrand {
2392                    label: Some(label()),
2393                    set_aside: Vec::new(),
2394                },
2395                "uninstall_would_strand",
2396                1,
2397            ),
2398            (
2399                Error::UninstallWouldStrand {
2400                    label: None,
2401                    set_aside: vec![PathBuf::from("/p/parks/pitboard-aside-1")],
2402                },
2403                "uninstall_would_strand",
2404                1,
2405            ),
2406            (
2407                Error::SignInSettledElsewhere { label: label() },
2408                "sign_in_settled_elsewhere",
2409                1,
2410            ),
2411        ] {
2412            assert_eq!((error.code(), error.exit_code()), (code, exit), "{error}");
2413            assert!(!error.to_string().contains('\u{2014}'), "{error}");
2414        }
2415        let waited = Error::AlreadyEnrolled {
2416            tool: ProviderId::Desktop,
2417            email: String::new(),
2418            label: "desktop/home".into(),
2419            asked: "desktop/travel".into(),
2420            waited: true,
2421        };
2422        assert_eq!(
2423            waited.to_string(),
2424            "Claude is signed in to `desktop/home`. Run `pitboard enroll desktop/home` to \
2425             record that login, then add another with `pitboard enroll desktop/travel \
2426             --sign-in`."
2427        );
2428    }
2429
2430    #[test]
2431    fn codes_are_unique_so_a_caller_can_branch_on_them() {
2432        let samples = [
2433            Error::LiveCredentialAbsent {
2434                tool: ProviderId::Claude,
2435                label: None,
2436                spelling: Spelling::Bare,
2437            },
2438            Error::ParkSlotExhausted,
2439            Error::SignedInAccountChanged,
2440            Error::AccountUnknown {
2441                label: "x".into(),
2442                enrolled: Enrolled::default(),
2443            },
2444            Error::NothingParked {
2445                tool: ProviderId::Claude,
2446                label: "x".into(),
2447            },
2448            Error::ParkedLoginExpired { label: "x".into() },
2449            Error::AccountNotInUse {
2450                tool: ProviderId::Claude,
2451                label: "x".into(),
2452            },
2453            Error::LabelTaken {
2454                label: "x".into(),
2455                who: "e".into(),
2456            },
2457            Error::SwitchRolledBack {
2458                from: "x".into(),
2459                to: "y".into(),
2460                detail: "d".into(),
2461            },
2462            Error::SignInNotKept {
2463                tool: ProviderId::Codex,
2464                label: "x".into(),
2465                detail: "d".into(),
2466            },
2467            Error::Elevated { why: None },
2468            Error::SystemTooOld { build: Some(17763) },
2469            Error::WindowsNotReleased,
2470            Error::LeftLoginChanged { path: "f".into() },
2471            Error::StoredLoginChanged { path: "f".into() },
2472            Error::Usage("u".into()),
2473            Error::ConfirmationNeeded { command: "stow" },
2474            Error::VaultFormUnsupported {
2475                form: crate::state::VaultForm::Files,
2476            },
2477        ];
2478        let mut codes: Vec<&str> = samples.iter().map(Error::code).collect();
2479        codes.sort_unstable();
2480        let before = codes.len();
2481        codes.dedup();
2482        assert_eq!(codes.len(), before);
2483    }
2484
2485    /// Whatever stops putting the file away is branched on by its own code, cause and exit
2486    /// status, and says after its own words how far putting it away had gone.
2487    #[test]
2488    fn what_stopped_putting_a_file_away_keeps_its_code_and_says_how_far_it_went() {
2489        let stopped = Error::StowStopped {
2490            partway: Partway::Parked {
2491                label: "work".into(),
2492            },
2493            warnings: Vec::new(),
2494            error: Box::new(Error::Store(crate::store::Error::Locked)),
2495        };
2496
2497        assert_eq!(stopped.code(), "credential_store_locked");
2498        assert_eq!(
2499            stopped.exit_code(),
2500            Error::Store(crate::store::Error::Locked).exit_code()
2501        );
2502        assert!(
2503            stopped.to_string().ends_with(&format!(
2504                "{}. Pitboard deleted nothing, having parked the login in the file for `work`.",
2505                crate::store::locked(crate::host::OS)
2506            )),
2507            "{stopped}"
2508        );
2509
2510        let unidentified = Error::StowStopped {
2511            partway: Partway::Nothing,
2512            warnings: Vec::new(),
2513            error: Box::new(Error::LeftLoginUnidentified {
2514                path: "f".into(),
2515                cause: Cause::Unreachable,
2516                detail: "offline".into(),
2517            }),
2518        };
2519        assert_eq!(unidentified.code(), "left_login_unidentified");
2520        assert_eq!(unidentified.cause(), Some(Cause::Unreachable));
2521        assert!(
2522            unidentified
2523                .to_string()
2524                .ends_with("try again. Pitboard changed nothing."),
2525            "{unidentified}"
2526        );
2527    }
2528
2529    #[test]
2530    fn a_refusal_after_what_was_said_is_given_back_as_itself() {
2531        let refusal = || Error::AccountNotInUse {
2532            tool: ProviderId::Desktop,
2533            label: "desktop/work".into(),
2534        };
2535        let waiting = crate::warning::Warning::MoveWaiting {
2536            tool: ProviderId::Desktop,
2537            label: "desktop/work".into(),
2538        };
2539        let mut carried = refusal().after(vec![waiting]);
2540        assert_eq!(carried.code(), "account_not_in_use");
2541        assert_eq!(carried.exit_code(), refusal().exit_code());
2542        assert_eq!(carried.to_string(), refusal().to_string());
2543        let said = carried.take_warnings();
2544        assert_eq!(
2545            said.iter()
2546                .map(crate::warning::Warning::code)
2547                .collect::<Vec<_>>(),
2548            ["move_waiting"]
2549        );
2550        assert!(
2551            matches!(carried, Error::AccountNotInUse { .. }),
2552            "{carried:?}"
2553        );
2554        assert!(carried.take_warnings().is_empty());
2555        let alone = refusal().after(Vec::new());
2556        assert!(matches!(alone, Error::AccountNotInUse { .. }), "{alone:?}");
2557    }
2558
2559    #[test]
2560    fn a_broken_assumption_exits_differently_from_a_bad_request() {
2561        assert_eq!(
2562            Error::LiveCredentialShapeUnexpected {
2563                tool: ProviderId::Claude,
2564                detail: "x".into()
2565            }
2566            .exit_code(),
2567            3
2568        );
2569        assert_eq!(
2570            Error::AccountUnknown {
2571                label: "x".into(),
2572                enrolled: Enrolled::default()
2573            }
2574            .exit_code(),
2575            1
2576        );
2577    }
2578
2579    #[test]
2580    fn every_message_tells_the_user_something_to_do() {
2581        // A message that only states a fact leaves the user stuck.
2582        let actionable = [
2583            Error::LiveCredentialAbsent {
2584                tool: ProviderId::Claude,
2585                label: None,
2586                spelling: Spelling::Bare,
2587            }
2588            .to_string(),
2589            Error::LiveCredentialAbsent {
2590                tool: ProviderId::Codex,
2591                label: None,
2592                spelling: Spelling::Bare,
2593            }
2594            .to_string(),
2595            Error::AccountUnknown {
2596                label: "work".into(),
2597                enrolled: Enrolled(vec!["personal".into()]),
2598            }
2599            .to_string(),
2600            Error::NothingParked {
2601                tool: ProviderId::Claude,
2602                label: "work".into(),
2603            }
2604            .to_string(),
2605            Error::ParkedLoginExpired {
2606                label: "work".into(),
2607            }
2608            .to_string(),
2609            Error::ParkedCredentialMissing {
2610                label: "work".into(),
2611            }
2612            .to_string(),
2613            Error::LiveAccountNotEnrolled {
2614                tool: ProviderId::Claude,
2615                who: "a@b.c".into(),
2616            }
2617            .to_string(),
2618            Error::SignInNotKept {
2619                tool: ProviderId::Codex,
2620                label: "codex/work".into(),
2621                detail: "the keychain is locked".into(),
2622            }
2623            .to_string(),
2624            Error::ConfirmationNeeded { command: "forget" }.to_string(),
2625            Error::LoginRestricted {
2626                tool: ProviderId::Claude,
2627                label: "work".into(),
2628                reason: "a pin leaves it out".into(),
2629            }
2630            .to_string(),
2631            Error::LoginRestricted {
2632                tool: ProviderId::Codex,
2633                label: "codex/work".into(),
2634                reason: "a setting rules it out".into(),
2635            }
2636            .to_string(),
2637        ];
2638        for message in actionable {
2639            assert!(
2640                ["Run ", "Sign in", "Switch to"]
2641                    .iter()
2642                    .any(|way| message.contains(way)),
2643                "no action offered: {message}"
2644            );
2645        }
2646    }
2647
2648    /// Codex's messages name Codex and the command that signs in to it; Claude Code's name
2649    /// Claude Code. A message about the wrong tool sends somebody to run the wrong program.
2650    #[test]
2651    fn a_message_names_the_tool_it_is_about() {
2652        let codex = Error::LiveCredentialAbsent {
2653            tool: ProviderId::Codex,
2654            label: None,
2655            spelling: Spelling::Bare,
2656        }
2657        .to_string();
2658        assert!(
2659            codex.contains("Codex") && codex.contains("`codex login`"),
2660            "{codex}"
2661        );
2662        assert!(!codex.contains("Claude"), "{codex}");
2663
2664        let unverifiable = Error::IdentityUnverifiable {
2665            tool: ProviderId::Codex,
2666            login: Unidentified::SignedIn,
2667            cause: Cause::Unreachable,
2668            detail: "offline".into(),
2669            spelling: Spelling::Bare,
2670        }
2671        .to_string();
2672        assert!(unverifiable.contains("OpenAI"), "{unverifiable}");
2673
2674        let claude = Error::IdentityUnverifiable {
2675            tool: ProviderId::Claude,
2676            login: Unidentified::SignedIn,
2677            cause: Cause::Unreachable,
2678            detail: "offline".into(),
2679            spelling: Spelling::Bare,
2680        }
2681        .to_string();
2682        assert!(claude.contains("confirm with Anthropic"), "{claude}");
2683    }
2684
2685    // A 400 used to say "check the connection", which no connection mends.
2686    #[test]
2687    fn a_refusal_says_to_sign_in_again_and_an_outage_to_try_again() {
2688        let said = |cause| {
2689            Error::IdentityUnverifiable {
2690                tool: ProviderId::Claude,
2691                login: Unidentified::SignedIn,
2692                cause,
2693                detail: "Anthropic answered 400: No organization associated with this token".into(),
2694                spelling: Spelling::Bare,
2695            }
2696            .to_string()
2697        };
2698        assert_eq!(
2699            said(Cause::Refused),
2700            "Pitboard could not confirm with Anthropic which account is signed in (Anthropic \
2701             answered 400: No organization associated with this token), and will not move a \
2702             login it cannot identify. Run `claude`, sign in, then try again."
2703        );
2704        assert!(said(Cause::Unreachable).ends_with("Check the connection and try again."));
2705        assert!(said(Cause::ServerError).ends_with("Try again later."));
2706        assert!(Cause::ServerError.worth_retrying());
2707        assert!(!Cause::Refused.worth_retrying());
2708    }
2709
2710    // The reporter's dialog said "which account is signed in" when it may have been the
2711    // parked login of the account being switched to that failed.
2712    #[test]
2713    fn the_parked_login_that_failed_is_named() {
2714        let said = |cause| {
2715            Error::IdentityUnverifiable {
2716                tool: ProviderId::Claude,
2717                login: Unidentified::Parked {
2718                    label: "dtg".into(),
2719                },
2720                cause,
2721                detail: "Anthropic answered 400".into(),
2722                spelling: Spelling::Bare,
2723            }
2724            .to_string()
2725        };
2726        assert_eq!(
2727            said(Cause::Refused),
2728            "Pitboard could not confirm with Anthropic whose login is parked for `dtg` \
2729             (Anthropic answered 400), and will not put in use a login it cannot identify. Sign \
2730             in to it again with `pitboard enroll dtg --sign-in`."
2731        );
2732        assert!(said(Cause::Unreachable).ends_with("Check the connection and try again."));
2733        assert!(!said(Cause::Refused).contains("signed in ("));
2734    }
2735
2736    // A refused sign-in used to be told to run `claude` and sign in to the tool itself.
2737    #[test]
2738    fn a_sign_in_that_cannot_be_identified_is_signed_in_again_through_pitboard() {
2739        let said = Error::IdentityUnverifiable {
2740            tool: ProviderId::Claude,
2741            login: Unidentified::SignIn {
2742                label: "dtg".into(),
2743            },
2744            cause: Cause::Refused,
2745            detail: "Anthropic answered 400".into(),
2746            spelling: Spelling::Bare,
2747        }
2748        .to_string();
2749        assert_eq!(
2750            said,
2751            "Pitboard could not confirm with Anthropic whose login the sign-in for `dtg` made \
2752             (Anthropic answered 400), and keeps no login it cannot identify. Sign in to it \
2753             again with `pitboard enroll dtg --sign-in`."
2754        );
2755    }
2756
2757    #[test]
2758    fn a_sign_in_for_an_account_not_named_yet_is_said_without_a_name() {
2759        let error = |cause| Error::IdentityUnverifiable {
2760            tool: ProviderId::Codex,
2761            login: Unidentified::NewSignIn,
2762            cause,
2763            detail: "OpenAI answered 400".into(),
2764            spelling: Spelling::Bare,
2765        };
2766        assert_eq!(
2767            error(Cause::Refused).to_string(),
2768            "Pitboard could not confirm with OpenAI whose login the sign-in made (OpenAI \
2769             answered 400), and keeps no login it cannot identify. Sign in again."
2770        );
2771        assert_eq!(
2772            account_on_hold(ProviderId::Codex, &Unidentified::NewSignIn, None),
2773            "OpenAI has put the account signed in to on hold. Pitboard keeps its login. Follow \
2774             OpenAI's instructions for the account, then try again."
2775        );
2776    }
2777
2778    /// The codes of the two tools' missing programs stay distinct, and Claude Code's keep
2779    /// the names they were released under.
2780    #[test]
2781    fn a_missing_program_keeps_its_released_code() {
2782        let missing = |tool| Error::ProgramNotFound { tool }.code();
2783        assert_eq!(missing(ProviderId::Claude), "claude_not_found");
2784        assert_eq!(missing(ProviderId::Codex), "codex_not_found");
2785        let absent = |tool| {
2786            Error::ProgramMissing {
2787                tool,
2788                program: "x".into(),
2789            }
2790            .code()
2791        };
2792        assert_eq!(absent(ProviderId::Claude), "claude_program_missing");
2793        assert_eq!(absent(ProviderId::Codex), "codex_program_missing");
2794    }
2795
2796    /// A Pitboard that finds its files written by a newer one is updated by the route it
2797    /// came by. The app's Check for Updates moves only the app and the command line inside
2798    /// it, so it is not offered as another way to update this one.
2799    #[test]
2800    fn a_newer_pitboards_files_say_which_update_moves_which_pitboard() {
2801        let path = PathBuf::from("/home/x/.pitboard/state.json");
2802        for message in [
2803            Error::StateFromNewerVersion {
2804                path: path.clone(),
2805                found: 9,
2806                expected: 5,
2807            }
2808            .to_string(),
2809            Error::StateNamesUnknownTool {
2810                path,
2811                tool: "gemini".into(),
2812            }
2813            .to_string(),
2814        ] {
2815            assert!(
2816                message.contains("Update this Pitboard the way you installed it."),
2817                "{message}"
2818            );
2819            assert!(
2820                message.contains("The app, and the command line inside it, update with"),
2821                "{message}"
2822            );
2823            assert!(!message.contains("or with the app"), "{message}");
2824        }
2825    }
2826
2827    /// Advice to enrol names the tool the account is for: a bare name would enrol a Claude
2828    /// Code account for a Codex login.
2829    #[test]
2830    fn enrolment_advice_keeps_the_tool() {
2831        let codex = Error::LiveAccountNotEnrolled {
2832            tool: ProviderId::Codex,
2833            who: "a@b.c".into(),
2834        }
2835        .to_string();
2836        assert!(codex.contains("pitboard enroll codex/<label>"), "{codex}");
2837        let claude = Error::LiveAccountNotEnrolled {
2838            tool: ProviderId::Claude,
2839            who: "a@b.c".into(),
2840        }
2841        .to_string();
2842        assert!(claude.contains("pitboard enroll <label>"), "{claude}");
2843        let already = Error::AlreadyEnrolled {
2844            tool: ProviderId::Codex,
2845            email: "a@b.c".into(),
2846            label: "codex/work".into(),
2847            asked: "codex/other".into(),
2848            waited: false,
2849        }
2850        .to_string();
2851        assert!(
2852            already.contains("pitboard enroll codex/<label> --sign-in"),
2853            "{already}"
2854        );
2855    }
2856
2857    /// Only a command that changes something finishes an interrupted switch; a plain
2858    /// `pitboard` reads and leaves it. So the message names the switch to run again, as it
2859    /// would be typed here.
2860    #[test]
2861    fn an_unverified_switch_names_a_command_that_finishes_it() {
2862        let message = Error::SwitchUnverified {
2863            tool: ProviderId::Codex,
2864            from: "codex/personal".into(),
2865            to: "codex/work".into(),
2866            detail: "auth.json is not readable".into(),
2867        }
2868        .to_string();
2869        assert!(
2870            message.contains("run `pitboard use codex/work` again"),
2871            "{message}"
2872        );
2873        assert!(!message.contains("run `pitboard` again"), "{message}");
2874    }
2875}