Skip to main content

pitboard_core/
state.rs

1//! Which accounts Pitboard knows and where each one is parked. No secrets: the logins stay
2//! in the keychain or vault.
3//!
4//! Stamped with the machine that wrote it, because a parked login belongs to exactly one
5//! machine: presenting a refresh token another machine has since rotated ends the login on
6//! both.
7
8use crate::context::Context;
9use crate::error::{Error, Result};
10use crate::host::Os;
11use crate::in_use::{Identified, InUse, Replaced};
12use crate::permit::Permit;
13use crate::provider::ProviderId;
14use crate::provider::{Identity, Owner};
15use crate::{atomic, home};
16use serde::{Deserialize, Serialize};
17use serde_json::Value;
18use std::collections::BTreeMap;
19use std::path::PathBuf;
20
21const SCHEMA: u32 = 9;
22
23#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Default)]
24#[serde(rename_all = "snake_case")]
25pub enum ParkKind {
26    #[default]
27    Vault,
28    // a folder under `<pitboard home>/parks`, holding an app's own files
29    Folder,
30}
31
32impl ParkKind {
33    // By reference, as `skip_serializing_if` calls it.
34    pub fn is_vault(&self) -> bool {
35        matches!(self, ParkKind::Vault)
36    }
37}
38
39/// How a home keeps its parked logins, where its system offers more than one way
40/// ([`crate::host::Host::vault_forms`]): on Linux, as items of the Secret Service or as files
41/// in the home.
42#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
43#[serde(rename_all = "snake_case")]
44pub enum VaultForm {
45    SecretService,
46    Files,
47}
48
49impl VaultForm {
50    /// What a program branches on, as `state.json` writes it: `secret_service` or `files`.
51    pub fn code(self) -> &'static str {
52        match self {
53            VaultForm::SecretService => "secret_service",
54            VaultForm::Files => "files",
55        }
56    }
57}
58
59// Where a home's parks are, recorded by its first save on a system that offers a choice, and a
60// move of them to another form (`switch/vault.rs`).
61#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
62pub(crate) struct Vault {
63    pub(crate) form: VaultForm,
64    // A move under way, written before anything is copied into this form.
65    #[serde(default, skip_serializing_if = "Option::is_none")]
66    pub(crate) moving_to: Option<VaultForm>,
67    // What a move took out of the form it left, listed by the save that names the new form.
68    #[serde(default, skip_serializing_if = "Option::is_none")]
69    pub(crate) leaving: Option<Leaving>,
70}
71
72impl Vault {
73    pub(crate) fn kept_as(form: VaultForm) -> Vault {
74        Vault {
75            form,
76            moving_to: None,
77            leaving: None,
78        }
79    }
80}
81
82// Parks still in the form a move left, each deleted from there and taken off this list.
83#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
84pub(crate) struct Leaving {
85    pub(crate) from: VaultForm,
86    pub(crate) parks: Vec<String>,
87}
88
89#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
90pub struct Dropped {
91    pub service: String,
92    #[serde(default, skip_serializing_if = "ParkKind::is_vault")]
93    pub kind: ParkKind,
94    // Set by `forget_folder` alone, for `State::remove` and `uninstall`: a held login goes then.
95    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
96    pub forgotten: bool,
97}
98
99#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
100#[serde(rename_all = "snake_case")]
101pub enum SetAside {
102    InTheWay,
103    Superseded,
104    AnotherMachine,
105    GivenUp,
106    Orphan,
107}
108
109// A folder under `parks` no account holds as its park: only `forget` and `uninstall` delete it.
110#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
111pub struct Aside {
112    pub name: String,
113    pub tool: ProviderId,
114    pub at: i64,
115    pub why: SetAside,
116    // the id it was parked for
117    #[serde(default, skip_serializing_if = "Option::is_none")]
118    pub account: Option<String>,
119    // the fingerprint of the session its jar holds
120    #[serde(default, skip_serializing_if = "Option::is_none")]
121    pub login: Option<String>,
122}
123
124#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
125#[serde(rename_all = "snake_case")]
126pub enum Half {
127    Leave,
128    Arrive,
129}
130
131// One half of a folder login's move, written before its first rename and removed by the save
132// that records what the half came to.
133#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
134pub struct Moving {
135    pub half: Half,
136    pub started_at: i64,
137    // the account whose login moves
138    pub id: String,
139    pub label: String,
140    // the folder under `parks` it moves to (leave) or from (arrive)
141    pub park: String,
142    pub login: String,
143    // the items the source held when the record was written
144    pub items: Vec<String>,
145    // SHA-256, hex, of each account key's value as the source held it
146    pub keys: BTreeMap<String, String>,
147    // each folder this move reserved for what it set aside, and why, saved before it is made
148    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
149    pub asides: BTreeMap<String, SetAside>,
150    pub slot: String,
151    // the sign-in this leave is for, copied into `awaiting` by its commit
152    #[serde(default, skip_serializing_if = "Option::is_none")]
153    pub awaited: Option<Awaited>,
154}
155
156// A sign-in inside the app is waited for, with an account parked for it.
157#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
158pub struct Awaited {
159    pub since: i64,
160    // the name asked
161    pub label: String,
162    // the id that label has already: a Sign In Again
163    #[serde(default, skip_serializing_if = "Option::is_none")]
164    pub account: Option<String>,
165    // the id of the account parked for it
166    pub put_back: String,
167}
168
169/// A login held for an account while another is signed in. There is at most one per
170/// account: once installed it is Claude Code's again, and Claude Code rotates it from then
171/// on, so a copy kept back would only ever present a token it has moved past.
172#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
173pub struct Park {
174    pub service: String,
175    #[serde(default, skip_serializing_if = "ParkKind::is_vault")]
176    pub kind: ParkKind,
177    pub parked_at: i64,
178    // a document's refresh token's, a folder login's session cookie's as stored
179    #[serde(rename = "refresh_fingerprint")]
180    pub login: String,
181    /// Until then its usage can be asked without renewing it first.
182    pub access_expires_at: Option<i64>,
183    /// Until then it can be restored.
184    pub refresh_expires_at: Option<i64>,
185    // the jar's own date for the session cookie: said, never a refusal
186    #[serde(default, skip_serializing_if = "Option::is_none")]
187    pub session_expires_at: Option<i64>,
188}
189
190/// A login of a tool's own that Pitboard renewed and has not saved where the tool keeps it
191/// yet, with the vault item holding a copy of the renewed login meanwhile.
192#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
193pub(crate) struct Renewing {
194    pub(crate) tool: ProviderId,
195    /// The tool's credential slot it is kept in.
196    pub(crate) slot: String,
197    /// Which of the tool's stores keeps it, as [`crate::store::Backend::name`] names it.
198    pub(crate) store: String,
199    /// The fingerprint of the refresh token the renewal sent.
200    pub(crate) sent: String,
201    /// The vault item holding the renewed login.
202    pub(crate) service: String,
203}
204
205impl Park {
206    pub fn restorable_at(&self, now: i64) -> bool {
207        self.refresh_expires_at.is_none_or(|at| at > now)
208    }
209
210    pub(crate) fn askable_at(&self, now: i64) -> bool {
211        self.access_expires_at.is_none_or(|at| at > now)
212    }
213}
214
215pub(crate) const RENEW_WITHIN: i64 = 3 * 86_400;
216
217/// Whether a login whose refresh token expires at `refresh_expires_at` is due to be renewed:
218/// within three days, and not yet expired.
219pub fn renewal_due(refresh_expires_at: i64, now: i64) -> bool {
220    (1..RENEW_WITHIN).contains(&(refresh_expires_at - now))
221}
222
223/// What one provider keeps about an account that the others have no equivalent of.
224///
225/// A tagged enum rather than a pile of optional fields, so no code reading a Codex account
226/// ever has to decide what an absent Claude organisation means for it. `provider` is the
227/// tag, and the variant's own fields sit beside `label` and `email` in the file, which is
228/// why a schema 3 account needs nothing moved to become a schema 4 one.
229#[derive(Serialize, Deserialize, Debug, Clone)]
230#[serde(tag = "provider", rename_all = "snake_case")]
231pub(crate) enum Detail {
232    Claude {
233        organization_uuid: String,
234        /// Written into Claude Code's config on switching here. Only what Anthropic
235        /// confirmed, so Claude Code fetches the rest of its profile itself.
236        oauth_account: Value,
237    },
238    Codex {
239        /// The ChatGPT workspace this account belongs to, where it belongs to one.
240        #[serde(default)]
241        workspace_id: Option<String>,
242    },
243    Desktop {},
244}
245
246/// Claude Code's own extras, for a caller that has already established it is holding a
247/// Claude account.
248#[derive(Debug)]
249pub(crate) struct ClaudeDetail<'a> {
250    pub(crate) organization_uuid: &'a str,
251    pub(crate) oauth_account: &'a Value,
252}
253
254#[derive(Serialize, Deserialize, Debug, Clone)]
255pub struct Account {
256    pub label: String,
257    /// What Pitboard files the account's parked logins, readings, budget and windows under.
258    /// Set at enrolment and never changed, so none of them has to move.
259    pub id: String,
260    /// The account as its tool names it: Anthropic's account uuid, which is the person and
261    /// not the login, or Codex's ChatGPT account joined with the person in it.
262    pub account_uuid: String,
263    pub email: String,
264    pub parked: Option<Park>,
265    /// When this account last came to be in use, in epoch seconds: switched to, enrolled
266    /// while signed in, or named by its service for the login its tool has stored.
267    ///
268    /// Pitboard renews a parked login for as long as the account is enrolled, so an account
269    /// somebody enrolled once and never came back to keeps a live, continuously rotated
270    /// refresh token on the machine indefinitely. Nothing said so, and nothing asked.
271    /// Recording this is what lets `doctor` say it.
272    ///
273    /// `None` on an account enrolled before this was recorded, and on one that has never
274    /// been in use.
275    #[serde(default)]
276    pub last_used_at: Option<i64>,
277    /// When the account's only login was replaced by a sign-in outside Pitboard, in epoch
278    /// seconds: its tool's store held that login with nothing parked for it and no other
279    /// slot's record naming it, and its service then named another account's login there, or
280    /// none. Pitboard keeps no copy of a login in use, so nothing brings it back. Cleared once
281    /// the account holds a parked login or is in use again.
282    #[serde(default, skip_serializing_if = "Option::is_none")]
283    pub replaced_at: Option<i64>,
284    /// The plan its login last said, as a label: "Ultra", "Pro".
285    #[serde(default, skip_serializing_if = "Option::is_none")]
286    pub plan: Option<String>,
287    /// Which tool's login this is, and whatever only that tool keeps.
288    #[serde(flatten)]
289    pub(crate) detail: Detail,
290}
291
292/// One account, the way Pitboard tells accounts apart: which tool, and what it is called
293/// there.
294///
295/// A label alone stopped being enough the day a second tool could have a `work` of its own.
296/// Everything that finds, changes or drops an account takes one of these, so no lookup can
297/// quietly land on the other tool's account of the same name.
298#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
299pub struct Key {
300    pub provider: ProviderId,
301    pub label: String,
302}
303
304impl Key {
305    pub fn new(provider: ProviderId, label: impl Into<String>) -> Key {
306        Key {
307            provider,
308            label: label.into(),
309        }
310    }
311
312    /// The name as somebody would type it back: bare for the tool a bare name means,
313    /// qualified for any other. Every message and the audit log use this, so a Claude Code
314    /// account reads exactly as it did before there was a second tool.
315    pub fn typed(&self) -> String {
316        if self.provider == crate::label::DEFAULT {
317            self.label.clone()
318        } else {
319            self.qualified()
320        }
321    }
322
323    /// `codex/work`, whichever tool it is.
324    pub fn qualified(&self) -> String {
325        format!(
326            "{}{}{}",
327            self.provider.code(),
328            crate::label::SEPARATOR,
329            self.label
330        )
331    }
332
333    // A label 0.1.x wrote with a slash, such as `team/a`, where `team` names no tool, is whole.
334    pub fn parse(typed: &str) -> Key {
335        match crate::label::parse(typed) {
336            Ok(crate::label::Spec::Qualified(provider, label)) => Key::new(provider, label),
337            _ => Key::new(crate::label::DEFAULT, typed),
338        }
339    }
340}
341
342impl std::fmt::Display for Key {
343    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
344        f.write_str(&self.typed())
345    }
346}
347
348impl Account {
349    pub(crate) fn key(&self) -> Key {
350        Key::new(self.provider(), self.label.clone())
351    }
352
353    pub(crate) fn is(&self, key: &Key) -> bool {
354        self.label == key.label && self.provider() == key.provider
355    }
356
357    pub fn provider(&self) -> ProviderId {
358        match self.detail {
359            Detail::Claude { .. } => ProviderId::Claude,
360            Detail::Codex { .. } => ProviderId::Codex,
361            Detail::Desktop {} => ProviderId::Desktop,
362        }
363    }
364
365    /// Whose login this account's is, as its tool's service names one.
366    pub(crate) fn owner(&self) -> Owner {
367        Owner {
368            account_uuid: self.account_uuid.clone(),
369            email: self.email.clone(),
370            organization_uuid: match &self.detail {
371                Detail::Claude {
372                    organization_uuid, ..
373                } => organization_uuid.clone(),
374                Detail::Codex { workspace_id, .. } => workspace_id.clone().unwrap_or_default(),
375                Detail::Desktop {} => String::new(),
376            },
377        }
378    }
379
380    /// Whether `owner`'s login is this account's.
381    pub(crate) fn owned_by(&self, owner: &Owner) -> bool {
382        self.holds(&owner.identity())
383    }
384
385    /// Whether `identity` is this account's login.
386    pub(crate) fn holds(&self, identity: &Identity) -> bool {
387        self.account_uuid == identity.account_uuid
388            && match &self.detail {
389                // One person in two organisations holds two logins, each on its own plan.
390                Detail::Claude {
391                    organization_uuid, ..
392                } => *organization_uuid == identity.organization_uuid,
393                // Codex's account id already joins the workspace with the person in it.
394                Detail::Codex { .. } => true,
395                // One claude.ai session covers the person's organisations.
396                Detail::Desktop {} => true,
397            }
398    }
399
400    /// Claude Code's extras, or `None` when this account belongs to another tool.
401    pub(crate) fn claude(&self) -> Option<ClaudeDetail<'_>> {
402        match &self.detail {
403            Detail::Claude {
404                organization_uuid,
405                oauth_account,
406            } => Some(ClaudeDetail {
407                organization_uuid,
408                oauth_account,
409            }),
410            Detail::Codex { .. } | Detail::Desktop {} => None,
411        }
412    }
413}
414
415#[derive(Serialize, Deserialize, Debug, Clone)]
416pub struct State {
417    pub(crate) schema: u32,
418    pub(crate) machine: String,
419    pub(crate) accounts: Vec<Account>,
420    /// Whose login each tool has stored, as its service last said, by the tool's code: the
421    /// record of the credential slot `slot` names for that tool.
422    #[serde(default)]
423    pub(crate) in_use: BTreeMap<String, InUse>,
424    /// The credential slot each tool's `in_use` was recorded for. One state file serves
425    /// every slot a machine uses, and a tool's own home variable changes which store is the
426    /// live one, so a record made in one slot says nothing about another.
427    #[serde(default)]
428    pub(crate) slot: BTreeMap<String, String>,
429    /// The record of each other slot a tool was read in, by the tool's code and then the
430    /// slot. [`load`] puts the slot it reads in place of the one `slot` names, so a read or a
431    /// change in one slot keeps every other slot's record for when that slot is read again.
432    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
433    pub(crate) other_slots: BTreeMap<String, BTreeMap<String, InUse>>,
434    /// Parked items no account refers to any more. Listed in the same save that drops them
435    /// and removed once deleted, so a delete that fails or is interrupted is retried.
436    #[serde(default)]
437    pub discarded: Vec<Dropped>,
438    /// Parked items an account here holds that this home never wrote down: logins
439    /// `pitboard repair` found in the store and gave back. On macOS every `PITBOARD_HOME`
440    /// shares the login keychain, so each may be another Pitboard's parked login, and
441    /// letting one go unused must leave it where it is. Removed once nothing here holds it.
442    /// Always empty where the vault is a directory inside this home, which nobody else
443    /// parks in.
444    #[serde(default)]
445    pub(crate) foreign: Vec<String>,
446    /// Parked items that copy the login in a file behind a tool's store which is still
447    /// there, each written down before the copy is. A put-away that stopped leaves the login
448    /// in both, and a session that signs in with the file can renew it there, which spends
449    /// the copy. So the next put-away never keeps one of these in place of what the file
450    /// holds by then. Emptied once the file has gone.
451    #[serde(default, skip_serializing_if = "Vec::is_empty")]
452    pub(crate) from_file: Vec<String>,
453    /// Renewals of a tool's own login whose answer is not saved where the tool keeps it yet,
454    /// each written down before the refresh token is sent. At most one per slot.
455    #[serde(default, skip_serializing_if = "Vec::is_empty")]
456    pub(crate) renewing: Vec<Renewing>,
457    // by tool code
458    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
459    pub moving: BTreeMap<String, Moving>,
460    #[serde(default, skip_serializing_if = "Vec::is_empty")]
461    pub aside: Vec<Aside>,
462    // by tool code
463    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
464    pub awaiting: BTreeMap<String, Awaited>,
465    /// How this home keeps its parked logins, where the system offers a choice. Recorded by
466    /// the home's first save, and changed only by a move between forms (`pitboard vault
467    /// move`): the parks are where it says, and a home that took another form would no longer
468    /// find them.
469    #[serde(default, skip_serializing_if = "Option::is_none")]
470    pub(crate) vault: Option<Vault>,
471}
472
473impl Default for State {
474    fn default() -> Self {
475        State {
476            schema: SCHEMA,
477            machine: machine_id(),
478            accounts: Vec::new(),
479            in_use: BTreeMap::new(),
480            slot: BTreeMap::new(),
481            other_slots: BTreeMap::new(),
482            discarded: Vec::new(),
483            foreign: Vec::new(),
484            from_file: Vec::new(),
485            renewing: Vec::new(),
486            moving: BTreeMap::new(),
487            aside: Vec::new(),
488            awaiting: BTreeMap::new(),
489            vault: None,
490        }
491    }
492}
493
494impl State {
495    /// Whose login `which` has stored, as its service last said.
496    pub(crate) fn in_use(&self, which: ProviderId) -> Option<&InUse> {
497        self.in_use.get(which.code())
498    }
499
500    /// The account whose login `which` has stored, as its service last said. `None` where
501    /// it stored none, where nothing is recorded, and where that login's account is not
502    /// enrolled.
503    pub fn account_in_use(&self, which: ProviderId) -> Option<&Account> {
504        let owner = self.in_use(which)?.owner.as_ref()?;
505        self.account_of(which, owner)
506    }
507
508    /// Record whose login `which` has stored, as its service said it at `at`.
509    ///
510    /// A record that agrees with `found` is kept as it is, with when it was first said.
511    /// Where the login is another account's than before, that account came to be in use at
512    /// `at`, and the one before lost the login it had in use. With nothing parked for it and
513    /// no other slot's record naming it, that was its only login, gone to a sign-in outside
514    /// Pitboard: a switch parks the login it moves out first.
515    pub(crate) fn identified(&mut self, which: ProviderId, found: InUse, at: i64) -> Identified {
516        let before = self.in_use.get(which.code());
517        if before.is_some_and(|known| known.agrees(which, &found)) {
518            return Identified {
519                changed: false,
520                replaced: None,
521            };
522        }
523        let was = before.and_then(|known| known.owner.clone());
524        let mut replaced = None;
525        if before.and_then(|known| known.account(which)) != found.account(which) {
526            if let Some(previous) = was
527                .as_ref()
528                .filter(|owner| !self.stored_in_another_slot(which, owner))
529                .and_then(|owner| self.account_of_mut(which, owner))
530                && previous.parked.is_none()
531            {
532                previous.replaced_at = Some(at);
533                replaced = Some(Replaced {
534                    key: previous.key(),
535                });
536            }
537            if let Some(now) = found
538                .owner
539                .as_ref()
540                .and_then(|owner| self.account_of_mut(which, owner))
541            {
542                now.replaced_at = None;
543                now.last_used_at = Some(at);
544            }
545        }
546        self.in_use.insert(which.code().to_string(), found);
547        Identified {
548            changed: true,
549            replaced,
550        }
551    }
552
553    /// Whether another slot's record says `which` has `owner`'s login stored there, which a
554    /// change in this slot leaves where it is.
555    fn stored_in_another_slot(&self, which: ProviderId, owner: &Owner) -> bool {
556        let account = Some(new_id(which, owner));
557        self.other_slots.get(which.code()).is_some_and(|records| {
558            records
559                .values()
560                .any(|record| record.account(which) == account)
561        })
562    }
563
564    /// Make `which`'s record the one of `slot`. Where it is of another slot, that one waits
565    /// with the other slots' records, and the record `slot` was last given, where there is
566    /// one, comes back. A record with no slot named is taken as `slot`'s.
567    fn in_slot(&mut self, which: ProviderId, slot: String) {
568        let code = which.code();
569        if let Some(recorded) = self.slot.get(code).filter(|recorded| **recorded != slot) {
570            let others = self.other_slots.entry(code.to_string()).or_default();
571            if let Some(record) = self.in_use.remove(code) {
572                others.insert(recorded.clone(), record);
573            }
574            if let Some(record) = others.remove(&slot) {
575                self.in_use.insert(code.to_string(), record);
576            }
577            if others.is_empty() {
578                self.other_slots.remove(code);
579            }
580        }
581        self.slot.insert(code.to_string(), slot);
582    }
583
584    /// Forget whose login every tool has stored, in every slot.
585    pub(crate) fn forget_in_use(&mut self) {
586        self.in_use.clear();
587        self.slot.clear();
588        self.other_slots.clear();
589    }
590
591    /// The account's name as a command would take it here: bare for the tool a bare name
592    /// means, unless another tool has an account of the same name, in which case a bare
593    /// name would be refused as ambiguous and the tool is said.
594    ///
595    /// What every message that tells somebody what to type uses, so the command it names
596    /// is one that works on this machine.
597    pub(crate) fn typed(&self, key: &Key) -> String {
598        let shared = self
599            .accounts
600            .iter()
601            .any(|a| a.label == key.label && a.provider() != key.provider);
602        if shared { key.qualified() } else { key.typed() }
603    }
604
605    /// Every label this tool has enrolled, for a message that would otherwise send someone
606    /// to another command to find out.
607    pub(crate) fn labels(&self, provider: ProviderId) -> crate::error::Enrolled {
608        crate::error::Enrolled(
609            self.accounts
610                .iter()
611                .filter(|a| a.provider() == provider)
612                .map(|a| a.label.clone())
613                .collect(),
614        )
615    }
616
617    // A vault item's name or a folder's: held, waiting to be deleted, renewing, moving or set
618    // aside.
619    pub fn names(&self, service: &str) -> bool {
620        self.accounts
621            .iter()
622            .filter_map(|a| a.parked.as_ref())
623            .any(|p| p.service == service)
624            || self.discarded.iter().any(|d| d.service == service)
625            || self
626                .renewing
627                .iter()
628                .any(|renewing| renewing.service == service)
629            || self.aside.iter().any(|aside| aside.name == service)
630            || self.moves(service)
631    }
632
633    // Whether a move under way holds the folder `name`, as its park or as one it set aside.
634    pub fn moves(&self, name: &str) -> bool {
635        self.moving
636            .values()
637            .any(|moving| moving.park == name || moving.asides.contains_key(name))
638    }
639
640    pub fn moving(&self, which: ProviderId) -> Option<&Moving> {
641        self.moving.get(which.code())
642    }
643
644    pub fn awaiting(&self, which: ProviderId) -> Option<&Awaited> {
645        self.awaiting.get(which.code())
646    }
647
648    /// The account under this key.
649    ///
650    /// Callers that took a name from a person should go through [`crate::label::resolve`]
651    /// first, which knows what to do when two tools share a label.
652    pub(crate) fn get(&self, key: &Key) -> Option<&Account> {
653        self.accounts.iter().find(|a| a.is(key))
654    }
655
656    /// This tool's account holding `owner`'s login.
657    pub(crate) fn account_of(&self, provider: ProviderId, owner: &Owner) -> Option<&Account> {
658        self.accounts
659            .iter()
660            .find(|a| a.provider() == provider && a.owned_by(owner))
661    }
662
663    /// Whose `identity` is, where Pitboard knows the account: enrolled, or the one its record
664    /// last named in use.
665    pub(crate) fn named(&self, provider: ProviderId, identity: &Identity) -> Option<Owner> {
666        let enrolled = self
667            .accounts
668            .iter()
669            .find(|a| a.provider() == provider && a.holds(identity))
670            .map(|a| Owner::named(identity.clone(), a.email.clone()));
671        enrolled.or_else(|| {
672            self.in_use(provider)?
673                .owner
674                .clone()
675                .filter(|owner| owner.identity() == *identity)
676        })
677    }
678
679    /// What `owner`'s login is filed under: its account's id, or the one it would be
680    /// enrolled with.
681    pub(crate) fn id_of(&self, provider: ProviderId, owner: &Owner) -> String {
682        self.id_for(provider, &owner.identity())
683    }
684
685    /// [`State::id_of`], for a login known by its identity alone.
686    pub(crate) fn id_for(&self, provider: ProviderId, identity: &Identity) -> String {
687        self.accounts
688            .iter()
689            .find(|a| a.provider() == provider && a.holds(identity))
690            .map_or_else(|| identity_id(provider, identity), |a| a.id.clone())
691    }
692
693    /// This tool's account filed under `id`.
694    pub(crate) fn by_id(&self, provider: ProviderId, id: &str) -> Option<&Account> {
695        self.accounts
696            .iter()
697            .find(|a| a.provider() == provider && a.id == id)
698    }
699
700    /// The account a parked item was written for.
701    ///
702    /// A park's name carries the account's id and not its tool, because names were fixed
703    /// before there was a second tool and every item already on a machine is filed under
704    /// one. The ids cannot collide in practice: each is built from its tool's UUIDs.
705    pub(crate) fn owner_of_park(&self, id: &str) -> Option<&Account> {
706        self.accounts.iter().find(|a| a.id == id)
707    }
708
709    fn get_mut(&mut self, key: &Key) -> Option<&mut Account> {
710        self.accounts.iter_mut().find(|a| a.is(key))
711    }
712
713    fn account_of_mut(&mut self, provider: ProviderId, owner: &Owner) -> Option<&mut Account> {
714        self.accounts
715            .iter_mut()
716            .find(|a| a.provider() == provider && a.owned_by(owner))
717    }
718
719    // The park it replaces: a vault item is released, a folder is set aside.
720    pub fn park(&mut self, key: &Key, park: Park) {
721        let (service, at) = (park.service.clone(), park.parked_at);
722        let Some(account) = self.get_mut(key) else {
723            return;
724        };
725        account.replaced_at = None;
726        if let Some(previous) = account.parked.replace(park)
727            && previous.service != service
728        {
729            match previous.kind {
730                ParkKind::Vault => self.release(&previous.service),
731                ParkKind::Folder => self.set_aside(key, previous, SetAside::Superseded, at),
732            }
733        }
734    }
735
736    // Keep `park` of `key`'s account as a folder no account holds, and stop holding it.
737    pub fn set_aside(&mut self, key: &Key, park: Park, why: SetAside, at: i64) {
738        let account = self.get_mut(key).map(|account| {
739            account.parked.take_if(|held| held.service == park.service);
740            account.id.clone()
741        });
742        if self.aside.iter().any(|aside| aside.name == park.service) {
743            return;
744        }
745        self.aside.push(Aside {
746            name: park.service,
747            tool: key.provider,
748            at,
749            why,
750            account,
751            login: Some(park.login),
752        });
753    }
754
755    // A folder a move leaves that no account holds as its park any more. `aside.login` is
756    // the session its jar holds, so none where the jar went back into the app's folder.
757    pub(crate) fn keep_aside(&mut self, aside: Aside) {
758        self.let_go(&aside.name);
759        if !self.aside.iter().any(|kept| kept.name == aside.name) {
760            self.aside.push(aside);
761        }
762    }
763
764    // An aside given back as a park, or deleted.
765    pub(crate) fn drop_aside(&mut self, name: &str) -> Option<Aside> {
766        let at = self.aside.iter().position(|aside| aside.name == name)?;
767        Some(self.aside.remove(at))
768    }
769
770    pub(crate) fn aside_of(&self, id: &str) -> impl Iterator<Item = &Aside> {
771        self.aside
772            .iter()
773            .filter(move |aside| aside.account.as_deref() == Some(id))
774    }
775
776    /// Hold a park this home did not write, found in the store and given back. It is used
777    /// like any other, and deleted only once it has been.
778    pub(crate) fn park_foreign(&mut self, key: &Key, park: Park) {
779        let service = park.service.clone();
780        self.park(key, park);
781        if self.references(&service) && !self.is_foreign(&service) {
782            self.foreign.push(service);
783        }
784    }
785
786    /// Whether an account here holds `service` without this home having written it.
787    pub(crate) fn is_foreign(&self, service: &str) -> bool {
788        self.foreign.iter().any(|listed| listed == service)
789    }
790
791    /// Take `service` as this home's own from now on, because this home has used it: a
792    /// renewal presented its refresh token, or a move wrote it into a vault of this home alone.
793    /// Letting it go afterwards deletes it.
794    pub(crate) fn used_here(&mut self, service: &str) {
795        self.foreign.retain(|listed| listed != service);
796    }
797
798    /// Take `service`, which an account here holds, as one this home did not write: a move found
799    /// it in the vault it moves to, which every home shares. Letting it go leaves it there.
800    pub(crate) fn written_elsewhere(&mut self, service: &str) {
801        if self.references(service) && !self.is_foreign(service) {
802            self.foreign.push(service.to_string());
803        }
804    }
805
806    // Installed, spent by a renewal, or a copy of a login still signed in: nothing can use
807    // it again, and a copy must not stay beside its login, so it goes whoever wrote it.
808    pub(crate) fn discard(&mut self, service: &str, kind: ParkKind) {
809        self.let_go(service);
810        if !self
811            .discarded
812            .iter()
813            .any(|listed| listed.service == service)
814        {
815            self.discarded.push(Dropped {
816                service: service.to_string(),
817                kind,
818                forgotten: false,
819            });
820        }
821    }
822
823    /// Stop holding `service` because nothing here wants it any more: a newer park replaced
824    /// it, or its account was dropped. Listed for deletion only when this home wrote it. One
825    /// `repair` gave back may be another Pitboard's parked login, which this one never
826    /// used, and deleting it would end that account's session for somebody who never ran
827    /// the command that did it.
828    pub(crate) fn release(&mut self, service: &str) {
829        if self.is_foreign(service) {
830            self.let_go(service);
831        } else {
832            self.discard(service, ParkKind::Vault);
833        }
834    }
835
836    /// No account holds `service` afterwards, and nothing records who wrote it or what it
837    /// copied.
838    fn let_go(&mut self, service: &str) {
839        for account in &mut self.accounts {
840            account.parked.take_if(|p| p.service == service);
841        }
842        self.foreign.retain(|listed| listed != service);
843        self.from_file.retain(|listed| listed != service);
844    }
845
846    /// `service` is about to hold a copy of the login in a file behind a tool's store.
847    pub(crate) fn copying_from_file(&mut self, service: &str) {
848        if !self.is_from_file(service) {
849            self.from_file.push(service.to_string());
850        }
851    }
852
853    /// Whether `service` copies the login a file behind a tool's store held, with that file
854    /// still there as far as anything recorded.
855    pub(crate) fn is_from_file(&self, service: &str) -> bool {
856        self.from_file.iter().any(|listed| listed == service)
857    }
858
859    /// The file behind a tool's store has gone, so no park copies it any more. Whether any
860    /// was written down as one.
861    pub(crate) fn file_gone(&mut self) -> bool {
862        !std::mem::take(&mut self.from_file).is_empty()
863    }
864
865    pub(crate) fn references(&self, service: &str) -> bool {
866        self.accounts
867            .iter()
868            .any(|a| a.parked.as_ref().is_some_and(|p| p.service == service))
869    }
870
871    /// Add the account, or replace the one this tool already has under its label.
872    pub(crate) fn upsert(&mut self, account: Account) {
873        match self.get_mut(&account.key()) {
874            Some(existing) => *existing = account,
875            None => self.accounts.push(account),
876        }
877    }
878
879    /// Enroll the account under `from` as `to` instead, inside the same tool. Only the
880    /// label changes: parked logins are named by account, not by label.
881    pub(crate) fn relabel(&mut self, from: &Key, to: &str) -> Result<&Account> {
882        let target = Key::new(from.provider, to);
883        if from.label != to
884            && let Some(taken) = self.get(&target)
885        {
886            let renamed = self.get(from).map(|a| a.email.as_str());
887            return Err(Error::LabelTaken {
888                label: target.typed(),
889                who: crate::words::login(
890                    from.provider,
891                    &taken.email,
892                    renamed == Some(taken.email.as_str()),
893                ),
894            });
895        }
896        let enrolled = self.labels(from.provider);
897        let account = self.get_mut(from).ok_or_else(|| Error::AccountUnknown {
898            label: from.typed(),
899            enrolled,
900        })?;
901        account.label = to.to_string();
902        Ok(account)
903    }
904
905    // Whose login its tool has stored stays recorded: the record names its owner, not a label.
906    pub fn remove(&mut self, key: &Key) -> Option<Account> {
907        let index = self.accounts.iter().position(|a| a.is(key))?;
908        let account = self.accounts.remove(index);
909        if let Some(park) = &account.parked {
910            match park.kind {
911                ParkKind::Vault => self.release(&park.service),
912                ParkKind::Folder => self.forget_folder(&park.service),
913            }
914        }
915        let filed: Vec<String> = self
916            .aside_of(&account.id)
917            .map(|aside| aside.name.clone())
918            .collect();
919        for name in filed {
920            self.drop_aside(&name);
921            self.forget_folder(&name);
922        }
923        self.awaiting
924            .retain(|_, awaited| awaited.put_back != account.id);
925        for awaited in self.awaiting.values_mut() {
926            awaited.account.take_if(|id| *id == account.id);
927        }
928        Some(account)
929    }
930
931    // Every folder set aside listed for deletion, as `uninstall` asks.
932    pub(crate) fn forget_asides(&mut self) {
933        for aside in std::mem::take(&mut self.aside) {
934            self.forget_folder(&aside.name);
935        }
936    }
937
938    // Every folder listed for deletion deleted whatever it still holds, as `uninstall` asks.
939    pub(crate) fn forget_discarded(&mut self) {
940        let folders: Vec<String> = self
941            .discarded
942            .iter()
943            .filter(|dropped| dropped.kind == ParkKind::Folder && !dropped.forgotten)
944            .map(|dropped| dropped.service.clone())
945            .collect();
946        for name in folders {
947            self.forget_folder(&name);
948        }
949    }
950
951    // The one way a folder that holds a login is listed to be deleted. Never one a move holds.
952    fn forget_folder(&mut self, name: &str) {
953        self.let_go(name);
954        if self.moves(name) {
955            return;
956        }
957        self.discarded.retain(|listed| listed.service != name);
958        self.discarded.push(Dropped {
959            service: name.to_string(),
960            kind: ParkKind::Folder,
961            forgotten: true,
962        });
963    }
964}
965
966/// The id a login is enrolled with. Claude's joins the organisation, since Anthropic's
967/// account uuid is the person and each of their organisations is a login of its own. `_`
968/// is in neither uuid, and is safe in a park's name and a readings file.
969pub(crate) fn new_id(provider: ProviderId, owner: &Owner) -> String {
970    identity_id(provider, &owner.identity())
971}
972
973pub(crate) fn identity_id(provider: ProviderId, identity: &Identity) -> String {
974    match provider {
975        ProviderId::Claude => format!("{}_{}", identity.account_uuid, identity.organization_uuid),
976        ProviderId::Codex => identity.account_uuid.clone(),
977        ProviderId::Desktop => format!("desktop_{}", identity.account_uuid),
978    }
979}
980
981// What `machine_id` answers where the platform's id could not be read.
982pub(crate) const UNKNOWN_MACHINE: &str = "unknown";
983
984/// Hashed, so the raw platform identifier never lands in a file Pitboard writes.
985pub(crate) fn machine_id() -> String {
986    use sha2::{Digest, Sha256};
987    match machine_uid::get() {
988        Ok(raw) => hex::encode(Sha256::digest(raw.as_bytes())),
989        Err(_) => String::from(UNKNOWN_MACHINE),
990    }
991}
992
993// The account index's name in Pitboard's directory.
994pub(crate) const FILE: &str = "state.json";
995
996fn file(ctx: &Context) -> PathBuf {
997    home::dir(ctx).join(FILE)
998}
999
1000// One stat of the account index alone: the readings the status line writes after every
1001// message say nothing of who is signed in, and a front end follows them apart.
1002pub(crate) fn changed_at(ctx: &Context) -> i64 {
1003    crate::time::changed_at(&file(ctx))
1004}
1005
1006pub(crate) fn load(ctx: &Context) -> Result<State> {
1007    let (state, here) = load_any_machine(ctx)?;
1008    if !here {
1009        return Err(Error::StateWrongMachine { path: file(ctx) });
1010    }
1011    Ok(state)
1012}
1013
1014/// The state whatever machine wrote it, and whether that machine is this one.
1015///
1016/// Only `adopt` reads it this way. Everything else goes through [`load`], which refuses a
1017/// file from elsewhere: a parked login is a refresh token, and two machines taking turns
1018/// presenting one ends the login for both.
1019///
1020/// A build that may do nothing here reads nothing either ([`crate::release`]), so an app on
1021/// a Windows build of a release before Windows is released is refused at its first read.
1022pub(crate) fn load_any_machine(ctx: &Context) -> Result<(State, bool)> {
1023    let path = file(ctx);
1024    let Some(document) = current_document(ctx)? else {
1025        return Ok((State::default(), true));
1026    };
1027    // An account of a tool this build does not know was written by a newer Pitboard, not
1028    // damaged. Said as such, because the advice for a corrupt file is to delete it, and
1029    // following that here would orphan every parked login in the vault.
1030    if let Some(unknown) = unknown_tool(&document) {
1031        return Err(Error::StateNamesUnknownTool {
1032            path: path.clone(),
1033            tool: unknown,
1034        });
1035    }
1036    let state: State = serde_json::from_value(document).map_err(|source| Error::StateCorrupt {
1037        path: path.clone(),
1038        source,
1039    })?;
1040    let here = state.machine == machine_id();
1041    let mut state = state;
1042    // Whose login a tool has stored is a fact about one slot. Per tool, so a changed
1043    // `CLAUDE_CONFIG_DIR` says nothing about Codex's record, nor `CODEX_HOME` about Claude
1044    // Code's.
1045    for &tool in ProviderId::ALL {
1046        if let Some(slot) = crate::provider::slot(ctx, tool) {
1047            state.in_slot(tool, slot);
1048        }
1049    }
1050    Ok((state, here))
1051}
1052
1053// The state file brought up to this schema, or `None` where there is no file yet.
1054fn current_document(ctx: &Context) -> Result<Option<Value>> {
1055    crate::release::check()?;
1056    let path = file(ctx);
1057    home::check_absolute(ctx)?;
1058    home::check_location(ctx, &home::dir(ctx))?;
1059    let lock = home::dir(ctx).join("state.lock");
1060    let raw = match atomic::read(&path, &lock, |path| std::fs::read_to_string(path)) {
1061        Ok(s) => s,
1062        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
1063        Err(source) => return Err(Error::StateUnreadable { path, source }),
1064    };
1065    let mut document: Value = serde_json::from_str(&raw).map_err(|source| Error::StateCorrupt {
1066        path: path.clone(),
1067        source,
1068    })?;
1069    migrate(&mut document, &path, ctx.os)?;
1070    Ok(Some(document))
1071}
1072
1073/// How this home keeps its parked logins, as its state file records it: `None` where it
1074/// records none, as a home with no state file yet does, and every home on a system that
1075/// keeps its parks one way.
1076///
1077/// Read from the file at each look rather than from a state in memory, so the vault every
1078/// caller opens is the one the home's last save named.
1079pub(crate) fn vault_form(ctx: &Context) -> Result<Option<VaultForm>> {
1080    Ok(vault(ctx)?.map(|vault| vault.form))
1081}
1082
1083// The whole record, a move of the parks included.
1084fn vault(ctx: &Context) -> Result<Option<Vault>> {
1085    let Some(mut document) = current_document(ctx)? else {
1086        return Ok(None);
1087    };
1088    let Some(vault) = document.get_mut("vault").map(Value::take) else {
1089        return Ok(None);
1090    };
1091    serde_json::from_value(vault)
1092        .map(Some)
1093        .map_err(|source| Error::StateCorrupt {
1094            path: file(ctx),
1095            source,
1096        })
1097}
1098
1099/// Where a home that records no form yet writes down the one its parks go in, before the
1100/// first is written: a save of the state as it stands, which records it. The park, its name
1101/// and the save that names it then agree, even where the Secret Service stops answering
1102/// between them. Nothing is written where the system offers no choice, or the home recorded one.
1103pub(crate) fn record_vault(ctx: &Context, permit: Permit) -> Result<()> {
1104    if ctx.host().vault_forms().is_empty() || vault_form(ctx)?.is_some() {
1105        return Ok(());
1106    }
1107    let (state, _) = load_any_machine(ctx)?;
1108    save(ctx, permit, &state)
1109}
1110
1111/// The first tool an account names that this build does not know, if any.
1112fn unknown_tool(document: &Value) -> Option<String> {
1113    document
1114        .get("accounts")?
1115        .as_array()?
1116        .iter()
1117        .filter_map(|account| account.get("provider")?.as_str())
1118        .find(|code| ProviderId::parse(code).is_none())
1119        .map(str::to_owned)
1120}
1121
1122/// Brings an older file up to the current format in place.
1123///
1124/// The command line and the app carry their own copy of this crate and update by different
1125/// routes, so on one machine an older Pitboard will meet a file a newer one wrote. Reading
1126/// forwards is what this is for; reading backwards is not possible, and says so.
1127///
1128/// `os` is the system reading it, which wrote it: a step may bring a file forward as that
1129/// system's Pitboard kept it.
1130fn migrate(document: &mut Value, path: &std::path::Path, os: Os) -> Result<()> {
1131    // Each bump adds a step after the ones before it, so a file two versions behind is
1132    // brought all the way forward in one read.
1133    let found = document
1134        .get("schema")
1135        .and_then(Value::as_u64)
1136        .unwrap_or_default();
1137    let found = u32::try_from(found).unwrap_or(u32::MAX);
1138    match found {
1139        SCHEMA => Ok(()),
1140        3..SCHEMA => {
1141            if found == 3 {
1142                three_to_four(document);
1143            }
1144            if found <= 4 {
1145                four_to_five(document);
1146            }
1147            if found <= 5 {
1148                five_to_six(document);
1149            }
1150            if found <= 6 {
1151                six_to_seven(document);
1152            }
1153            if found <= 7 {
1154                seven_to_eight(document);
1155            }
1156            eight_to_nine(document, os);
1157            Ok(())
1158        }
1159        // Nothing released wrote 1 or 2: the schema reached 3 before the first release.
1160        0..3 => Err(Error::StateVersionUnknown {
1161            path: path.to_path_buf(),
1162            found,
1163        }),
1164        _ => Err(Error::StateFromNewerVersion {
1165            path: path.to_path_buf(),
1166            found,
1167            expected: SCHEMA,
1168        }),
1169    }
1170}
1171
1172/// Schema 3 was Claude Code and nothing else, so every account in one is a Claude account
1173/// and the two singular records are Claude's.
1174///
1175/// Deliberately the smallest transform there could be. Nothing is nested and nothing is
1176/// renamed, because `Detail` is flattened and tagged: a schema 3 account already has
1177/// `organization_uuid` and `oauth_account` as siblings of `label`, which is exactly where
1178/// schema 4 reads them. All that is missing is the tag. No keychain item and no vault file
1179/// is touched, so a bug here is recoverable by fixing the code and reading again, never by
1180/// somebody signing in from scratch.
1181fn three_to_four(document: &mut Value) {
1182    let claude = Value::from(ProviderId::Claude.code());
1183    if let Some(accounts) = document.get_mut("accounts").and_then(Value::as_array_mut) {
1184        for account in accounts {
1185            if let Some(fields) = account.as_object_mut() {
1186                fields.insert("provider".into(), claude.clone());
1187            }
1188        }
1189    }
1190    for singular in ["active", "slot"] {
1191        let was = document.get(singular).cloned().unwrap_or(Value::Null);
1192        document[singular] = match was {
1193            Value::String(label) => serde_json::json!({ ProviderId::Claude.code(): label }),
1194            _ => serde_json::json!({}),
1195        };
1196    }
1197    document["schema"] = serde_json::json!(4);
1198}
1199
1200/// Schema 4 filed every account under its tool's account id, and Anthropic's is the person:
1201/// one person in two organisations was one account. Schema 5 gives each account an id of
1202/// its own, and an account already enrolled keeps the one everything is filed under, so
1203/// no park, reading or window has to move.
1204fn four_to_five(document: &mut Value) {
1205    if let Some(accounts) = document.get_mut("accounts").and_then(Value::as_array_mut) {
1206        for account in accounts {
1207            if let Some(fields) = account.as_object_mut()
1208                && let Some(id) = fields.get("account_uuid").cloned()
1209            {
1210                fields.insert("id".into(), id);
1211            }
1212        }
1213    }
1214    document["schema"] = serde_json::json!(5);
1215}
1216
1217/// Schema 5 recorded the account Pitboard last switched to, by label, which a sign-in
1218/// outside Pitboard left naming an account whose login was gone. Schema 6 records whose login
1219/// each tool has stored, as its service said. A record brought forward is that account's,
1220/// with no login and `known_at` 0: nothing established which login the store held. A label
1221/// naming no account names nobody.
1222fn five_to_six(document: &mut Value) {
1223    let accounts: Vec<Account> = document
1224        .get("accounts")
1225        .and_then(Value::as_array)
1226        .into_iter()
1227        .flatten()
1228        .filter_map(|account| serde_json::from_value(account.clone()).ok())
1229        .collect();
1230    let in_use: serde_json::Map<String, Value> = document
1231        .get("active")
1232        .and_then(Value::as_object)
1233        .into_iter()
1234        .flatten()
1235        .filter_map(|(code, label)| {
1236            let key = Key::new(ProviderId::parse(code)?, label.as_str()?);
1237            let account = accounts.iter().find(|a| a.is(&key))?;
1238            let unconfirmed = InUse {
1239                owner: Some(account.owner()),
1240                login: String::new(),
1241                known_at: 0,
1242                named: None,
1243            };
1244            let record = serde_json::to_value(unconfirmed).expect("a record is serialisable");
1245            Some((code.clone(), record))
1246        })
1247        .collect();
1248    if let Some(fields) = document.as_object_mut() {
1249        fields.remove("active");
1250        fields.insert("in_use".into(), Value::Object(in_use));
1251    }
1252    document["schema"] = serde_json::json!(6);
1253}
1254
1255/// Schema 7 adds `renewing`, which a schema 6 file reads as empty. It is a bump so that an
1256/// earlier Pitboard refuses the file: one would drop `renewing` at its next save, leaving the
1257/// copy of the renewed login named by nothing, so the next renewal of that login, by this
1258/// version or by 0.10.0's `stow`, would send the spent refresh token again.
1259fn six_to_seven(document: &mut Value) {
1260    document["schema"] = serde_json::json!(7);
1261}
1262
1263// Schema 8 holds Claude Desktop's login, kept as files, beside one kept as a document: a park's
1264// `kind`, `discarded` as typed entries that say `forgotten`, `moving`, `aside`, `awaiting`, and
1265// Claude Desktop's `in_use` slot, the data folder's path. A bump: every earlier release reads
1266// `discarded` as names, and would call a file of typed entries corrupt.
1267fn seven_to_eight(document: &mut Value) {
1268    if let Some(discarded) = document.get_mut("discarded").and_then(Value::as_array_mut) {
1269        for entry in discarded {
1270            if let Value::String(service) = entry {
1271                *entry = serde_json::json!({ "service": service });
1272            }
1273        }
1274    }
1275    document["schema"] = serde_json::json!(8);
1276}
1277
1278/// Schema 9 records how a home keeps its parks (`vault`), where the system offers a choice. On
1279/// Linux every earlier Pitboard parked in files, so a schema 8 file there comes forward with
1280/// its parks in files; macOS and Windows keep theirs one way and record none. A bump: an
1281/// earlier Pitboard would drop `vault` at its next save and look for this home's parks in
1282/// files, where a home on the Secret Service has none.
1283fn eight_to_nine(document: &mut Value, os: Os) {
1284    match os {
1285        Os::Linux => document["vault"] = serde_json::json!({ "form": "files" }),
1286        Os::MacOs | Os::Windows => {}
1287    }
1288    document["schema"] = serde_json::json!(9);
1289}
1290
1291pub(crate) fn save(ctx: &Context, permit: Permit, state: &State) -> Result<()> {
1292    home::check_absolute(ctx)?;
1293    home::check_location(ctx, &home::dir(ctx))?;
1294    let mut state = state.clone();
1295    for &tool in ProviderId::ALL {
1296        if let Some(slot) = crate::provider::slot(ctx, tool) {
1297            state.in_slot(tool, slot);
1298        }
1299    }
1300    state.vault = recorded_vault(ctx, &state)?;
1301    let state = &state;
1302    let path = file(ctx);
1303    let write = |source| Error::StateWriteFailed {
1304        path: path.clone(),
1305        source,
1306    };
1307    home::ensure(ctx, permit).map_err(write)?;
1308    let body = serde_json::to_string_pretty(state).expect("State is always serialisable");
1309    atomic::write(permit, &path, body.as_bytes(), atomic::Perms::Secret).map_err(write)
1310}
1311
1312// The record a save writes: none where the system keeps parks one way; otherwise the one this
1313// state holds, else the one the file holds, else the form a new home takes.
1314fn recorded_vault(ctx: &Context, state: &State) -> Result<Option<Vault>> {
1315    let host = ctx.host();
1316    if host.vault_forms().is_empty() {
1317        return Ok(None);
1318    }
1319    match &state.vault {
1320        Some(vault) => Ok(Some(vault.clone())),
1321        None => Ok(vault(ctx)?.or_else(|| crate::store::new_home_form(ctx).map(Vault::kept_as))),
1322    }
1323}
1324
1325#[cfg(test)]
1326#[allow(
1327    clippy::disallowed_methods,
1328    reason = "a test sets up its scratch files as a person or a tool would"
1329)]
1330mod tests {
1331    #[test]
1332    fn a_key_reads_back_as_it_was_written() {
1333        for key in [
1334            Key::new(ProviderId::Claude, "work"),
1335            Key::new(ProviderId::Codex, "work"),
1336            Key::new(ProviderId::Desktop, "work"),
1337            Key::new(ProviderId::Claude, "team/a"),
1338        ] {
1339            assert_eq!(Key::parse(&key.typed()), key);
1340            assert_eq!(Key::parse(&key.qualified()), key);
1341        }
1342    }
1343
1344    /// CLAUDE_CONFIG_DIR picks which keychain item is the live one, and one state file
1345    /// serves every slot on a machine. A record of whose login one slot holds says nothing
1346    /// about another, so it is not carried over, and says nothing about Codex's at all. It is
1347    /// kept for when its slot is read again, whatever another slot records meanwhile.
1348    #[test]
1349    fn whose_login_another_slot_holds_is_not_claimed_here() {
1350        let scratch = tempfile::tempdir().expect("a scratch folder");
1351        let home = scratch.path().join("home");
1352        let here = Context::new(home.clone()).with_pitboard_home(home.clone());
1353        let elsewhere = here
1354            .clone()
1355            .with_claude_config_dir(home.join("somewhere-else").to_string_lossy().into());
1356
1357        let mut state = State::default();
1358        state.accounts.push(account("work", None));
1359        state.accounts.push(codex_account("personal"));
1360        let found = InUse::of(&state.accounts[0], "f", 100);
1361        state.identified(ProviderId::Claude, found.clone(), 100);
1362        let codex = InUse::of(&state.accounts[1], "f", 100);
1363        state.identified(ProviderId::Codex, codex.clone(), 100);
1364        save(&here, Permit::for_a_test(), &state).expect("saved");
1365
1366        assert_eq!(
1367            load(&here).unwrap().in_use(ProviderId::Claude),
1368            Some(&found)
1369        );
1370        let moved = load(&elsewhere).unwrap();
1371        assert_eq!(
1372            moved.in_use(ProviderId::Claude),
1373            None,
1374            "another slot's record of whose login is stored is not this slot's"
1375        );
1376        assert_eq!(
1377            moved.in_use(ProviderId::Codex),
1378            Some(&codex),
1379            "Codex's slot did not move"
1380        );
1381
1382        let mut moved = moved;
1383        let there = InUse::of(&moved.accounts[0], "g", 200);
1384        moved.identified(ProviderId::Claude, there.clone(), 200);
1385        save(&elsewhere, Permit::for_a_test(), &moved).expect("saved");
1386        assert_eq!(
1387            load(&here).unwrap().in_use(ProviderId::Claude),
1388            Some(&found),
1389            "this slot's record is kept while another slot records its own"
1390        );
1391        save(&here, Permit::for_a_test(), &load(&here).unwrap()).expect("saved");
1392        assert_eq!(
1393            load(&elsewhere).unwrap().in_use(ProviderId::Claude),
1394            Some(&there),
1395            "and so is the other's"
1396        );
1397    }
1398
1399    /// `CODEX_HOME` picks which `auth.json` is Codex's live login, the way
1400    /// `CLAUDE_CONFIG_DIR` picks Claude Code's keychain item. A record made under one home
1401    /// says nothing about another, and says nothing about Claude Code's at all.
1402    #[test]
1403    fn another_codex_home_is_another_codex_slot() {
1404        let scratch = tempfile::tempdir().expect("a scratch folder");
1405        let home = scratch.path().join("home");
1406        let here = Context::new(home.clone()).with_pitboard_home(home.clone());
1407        let mut state = State::default();
1408        state.accounts.push(account("work", None));
1409        state.accounts.push(codex_account("work"));
1410        for (which, at) in [(ProviderId::Claude, 0), (ProviderId::Codex, 1)] {
1411            let found = InUse::of(&state.accounts[at], "f", 100);
1412            state.identified(which, found, 100);
1413        }
1414        save(&here, Permit::for_a_test(), &state).expect("saved");
1415
1416        let label_in_use = |state: &State, which| {
1417            state
1418                .account_in_use(which)
1419                .map(|account| account.label.clone())
1420        };
1421        let moved = here
1422            .clone()
1423            .with_codex_home(home.join("somewhere-else").to_string_lossy().into());
1424        let loaded = load(&moved).unwrap();
1425        assert_eq!(loaded.in_use(ProviderId::Codex), None);
1426        assert_eq!(
1427            label_in_use(&loaded, ProviderId::Claude).as_deref(),
1428            Some("work"),
1429            "Claude Code's slot did not move"
1430        );
1431        assert_eq!(
1432            label_in_use(&load(&here).unwrap(), ProviderId::Codex).as_deref(),
1433            Some("work")
1434        );
1435    }
1436
1437    /// A file written by the version in people's hands today. The command line and the app
1438    /// update separately, so a file one of them wrote has to keep loading in the other.
1439    #[test]
1440    fn the_format_shipped_in_0_1_x_still_loads() {
1441        let written = serde_json::json!({
1442            "schema": 3,
1443            "machine": machine_id(),
1444            "accounts": [{
1445                "label": "work",
1446                "account_uuid": "acc-1",
1447                "email": "a@b.c",
1448                "organization_uuid": "org-1",
1449                "oauth_account": {"emailAddress": "a@b.c"},
1450                "parked": {
1451                    "service": "pitboard-park-acc-1-1789935600123",
1452                    "parked_at": 1_789_935_600,
1453                    "refresh_fingerprint": "abcd",
1454                    "access_expires_at": 1_789_999_999,
1455                    "refresh_expires_at": 1_792_000_000
1456                }
1457            }],
1458            "active": "work",
1459            "discarded": []
1460        });
1461        let mut document = written;
1462        migrate(
1463            &mut document,
1464            std::path::Path::new("/tmp/state.json"),
1465            crate::host::OS,
1466        )
1467        .expect("still current");
1468        let state: State = serde_json::from_value(document).expect("still parses");
1469        assert_eq!(state.get(&claude("work")).unwrap().email, "a@b.c");
1470        assert_eq!(state.get(&claude("work")).unwrap().id, "acc-1");
1471        assert_eq!(
1472            state.account_in_use(ProviderId::Claude).map(Account::key),
1473            Some(claude("work"))
1474        );
1475    }
1476
1477    /// Migrating a file that is already current must change nothing.
1478    ///
1479    /// `three_to_four` rewrites `active` and `slot` in place and `five_to_six` drops
1480    /// `active`, and a version check that slipped would wrap an already-wrapped map into
1481    /// `{"claude": {"claude": "work"}}`, or find no `active` to bring forward, and lose whose
1482    /// login is stored, silently, on every load after that.
1483    #[test]
1484    fn migrating_a_current_file_is_a_no_op() {
1485        let mut once = serde_json::json!({
1486            "schema": 3,
1487            "machine": machine_id(),
1488            "accounts": [{
1489                "label": "work", "account_uuid": "acc-1", "email": "a@b.c",
1490                "organization_uuid": "org-1", "oauth_account": {}, "parked": null
1491            }],
1492            "active": "work",
1493            "slot": "Claude Code-credentials",
1494            "discarded": ["gone"]
1495        });
1496        migrate(
1497            &mut once,
1498            std::path::Path::new("/tmp/state.json"),
1499            crate::host::OS,
1500        )
1501        .expect("3 to 9");
1502        assert_eq!(once["discarded"], serde_json::json!([{"service": "gone"}]));
1503        let mut twice = once.clone();
1504        migrate(
1505            &mut twice,
1506            std::path::Path::new("/tmp/state.json"),
1507            crate::host::OS,
1508        )
1509        .expect("9 is current");
1510        assert_eq!(once, twice, "a second migration must change nothing");
1511        assert!(once.get("active").is_none());
1512        assert_eq!(
1513            once["in_use"]["claude"]["owner"]["account_uuid"],
1514            serde_json::json!("acc-1")
1515        );
1516        assert_eq!(
1517            once["slot"],
1518            serde_json::json!({"claude": "Claude Code-credentials"})
1519        );
1520        assert_eq!(once["accounts"][0]["provider"], "claude");
1521        assert_eq!(once["accounts"][0]["id"], "acc-1");
1522        assert_eq!(once["schema"], SCHEMA);
1523    }
1524
1525    /// Schema 3 had no `active` at all when nothing had been switched to, and a migration
1526    /// that turned that into a one-entry map naming nothing would claim a switch happened.
1527    #[test]
1528    fn a_file_that_never_switched_migrates_to_no_account_in_use() {
1529        let mut document = serde_json::json!({
1530            "schema": 3, "machine": machine_id(), "accounts": [], "discarded": []
1531        });
1532        migrate(
1533            &mut document,
1534            std::path::Path::new("/tmp/state.json"),
1535            crate::host::OS,
1536        )
1537        .expect("3 to 9");
1538        let state: State = serde_json::from_value(document).expect("parses");
1539        assert!(state.in_use.is_empty() && state.slot.is_empty());
1540    }
1541
1542    /// A file as 0.9.0 writes it names the account last switched to. It comes forward as
1543    /// that account's record with nothing established about the login, so nothing reads it
1544    /// as what the service said until the service is asked.
1545    #[test]
1546    fn a_schema_5_file_comes_forward_with_the_account_in_use_unconfirmed() {
1547        let scratch = tempfile::tempdir().expect("a scratch folder");
1548        let home = scratch.path().to_path_buf();
1549        let ctx = Context::new(home.clone()).with_pitboard_home(home.clone());
1550        std::fs::write(
1551            home.join("state.json"),
1552            serde_json::json!({
1553                "schema": 5,
1554                "machine": machine_id(),
1555                "accounts": [{
1556                    "label": "work",
1557                    "id": "acc-1_org-1",
1558                    "account_uuid": "acc-1",
1559                    "email": "a@b.c",
1560                    "parked": null,
1561                    "last_used_at": 1_789_935_000,
1562                    "provider": "claude",
1563                    "organization_uuid": "org-1",
1564                    "oauth_account": {"accountUuid": "acc-1", "organizationUuid": "org-1"}
1565                }],
1566                "active": {"claude": "work", "codex": "gone"},
1567                "slot": {},
1568                "discarded": [],
1569                "foreign": []
1570            })
1571            .to_string(),
1572        )
1573        .unwrap();
1574
1575        let state = load(&ctx).expect("brought forward");
1576        assert_eq!(
1577            state.in_use(ProviderId::Claude),
1578            Some(&InUse {
1579                owner: Some(Owner {
1580                    account_uuid: "acc-1".into(),
1581                    email: "a@b.c".into(),
1582                    organization_uuid: "org-1".into(),
1583                }),
1584                login: String::new(),
1585                known_at: 0,
1586                named: None,
1587            })
1588        );
1589        assert_eq!(
1590            state.in_use(ProviderId::Codex),
1591            None,
1592            "a label naming no account names nobody"
1593        );
1594
1595        save(&ctx, Permit::for_a_test(), &state).expect("saved");
1596        let written: Value =
1597            serde_json::from_str(&std::fs::read_to_string(home.join("state.json")).unwrap())
1598                .unwrap();
1599        assert_eq!(written["schema"], SCHEMA);
1600        assert!(written.get("active").is_none(), "{written}");
1601        assert_eq!(written["in_use"]["claude"]["known_at"], 0);
1602    }
1603
1604    #[test]
1605    fn a_schema_6_file_is_written_back_at_this_schema_and_otherwise_as_it_was() {
1606        let scratch = tempfile::tempdir().expect("a scratch folder");
1607        let home = scratch.path().to_path_buf();
1608        let ctx = Context::new(home.clone()).with_pitboard_home(home.clone());
1609        let mut state = State::default();
1610        state.accounts.push(account("work", Some(park("parked"))));
1611        let found = InUse::of(&state.accounts[0], "f", 100);
1612        state.identified(ProviderId::Claude, found, 100);
1613        state.discarded.push(Dropped {
1614            service: "gone".into(),
1615            kind: ParkKind::Vault,
1616            forgotten: false,
1617        });
1618        save(&ctx, Permit::for_a_test(), &state).expect("saved");
1619        let path = home.join("state.json");
1620        let read = |path: &PathBuf| -> Value {
1621            serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap()
1622        };
1623        let mut written = read(&path);
1624        written["schema"] = 6.into();
1625        std::fs::write(&path, written.to_string()).unwrap();
1626
1627        let state = load(&ctx).expect("a schema 6 file is read");
1628        save(&ctx, Permit::for_a_test(), &state).expect("saved");
1629
1630        brought_forward(&mut written);
1631        assert_eq!(read(&path), written);
1632    }
1633
1634    #[test]
1635    fn a_schema_7_file_0_11_0_wrote_is_written_back_at_this_schema_with_its_discarded_parks_typed()
1636    {
1637        let scratch = tempfile::tempdir().expect("a scratch folder");
1638        let home = scratch.path().to_path_buf();
1639        let ctx = Context::new(home.clone()).with_pitboard_home(home.clone());
1640        let mut state = State::default();
1641        state.accounts.push(account("work", Some(park("parked"))));
1642        let found = InUse::of(&state.accounts[0], "f", 100);
1643        state.identified(ProviderId::Claude, found, 100);
1644        save(&ctx, Permit::for_a_test(), &state).expect("saved");
1645        let path = home.join("state.json");
1646        let read = |path: &PathBuf| -> Value {
1647            serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap()
1648        };
1649        let mut written = read(&path);
1650        written["schema"] = 7.into();
1651        written["discarded"] = serde_json::json!(["pitboard-park-a-1", "pitboard-park-b-2"]);
1652        std::fs::write(&path, written.to_string()).unwrap();
1653
1654        let state = load(&ctx).expect("a schema 7 file is read");
1655        save(&ctx, Permit::for_a_test(), &state).expect("saved");
1656
1657        brought_forward(&mut written);
1658        written["discarded"] = serde_json::json!([
1659            {"service": "pitboard-park-a-1"},
1660            {"service": "pitboard-park-b-2"}
1661        ]);
1662        assert_eq!(read(&path), written);
1663    }
1664
1665    #[test]
1666    fn a_schema_7_park_reads_and_writes_as_it_was() {
1667        let written = serde_json::json!({
1668            "service": "pitboard-park-a-1", "parked_at": 100, "refresh_fingerprint": "0a1b",
1669            "access_expires_at": 200, "refresh_expires_at": null
1670        });
1671        let park: Park = serde_json::from_value(written.clone()).expect("a schema 7 park");
1672        assert_eq!(park.kind, ParkKind::Vault);
1673        assert_eq!(park.login, "0a1b");
1674        assert_eq!(park.session_expires_at, None);
1675        assert_eq!(serde_json::to_value(&park).unwrap(), written);
1676
1677        let folder = Park {
1678            kind: ParkKind::Folder,
1679            session_expires_at: Some(900),
1680            ..park
1681        };
1682        let written = serde_json::to_value(&folder).unwrap();
1683        assert_eq!(written["kind"], "folder");
1684        assert_eq!(written["refresh_fingerprint"], "0a1b");
1685        assert_eq!(written["session_expires_at"], 900);
1686        assert_eq!(serde_json::from_value::<Park>(written).unwrap(), folder);
1687        let dropped = Dropped {
1688            service: "pitboard-park-a-1".into(),
1689            kind: ParkKind::Folder,
1690            forgotten: false,
1691        };
1692        assert_eq!(
1693            serde_json::to_value(&dropped).unwrap(),
1694            serde_json::json!({"service": "pitboard-park-a-1", "kind": "folder"})
1695        );
1696    }
1697
1698    fn folder_park(service: &str, login: &str, at: i64) -> Park {
1699        Park {
1700            service: service.into(),
1701            kind: ParkKind::Folder,
1702            parked_at: at,
1703            login: login.into(),
1704            access_expires_at: None,
1705            refresh_expires_at: None,
1706            session_expires_at: None,
1707        }
1708    }
1709
1710    #[test]
1711    fn a_move_and_a_sign_in_waited_for_name_their_folders_and_follow_a_forgotten_account() {
1712        let mut s = State::default();
1713        s.accounts.push(account("work", None));
1714        s.accounts
1715            .push(account("home", Some(folder_park("park-home", "f1", 100))));
1716        let (work, home) = (
1717            Key::new(ProviderId::Claude, "work"),
1718            Key::new(ProviderId::Claude, "home"),
1719        );
1720        let awaited = Awaited {
1721            since: 5,
1722            label: "travel".into(),
1723            account: Some("home-uuid".into()),
1724            put_back: "work-uuid".into(),
1725        };
1726        s.moving.insert(
1727            "desktop".into(),
1728            Moving {
1729                half: Half::Arrive,
1730                started_at: 5,
1731                id: "home-uuid".into(),
1732                label: "home".into(),
1733                park: "park-home".into(),
1734                login: "f1".into(),
1735                items: vec!["Cookies".into()],
1736                keys: BTreeMap::new(),
1737                asides: BTreeMap::from([("aside-1".to_string(), SetAside::InTheWay)]),
1738                slot: "/data".into(),
1739                awaited: None,
1740            },
1741        );
1742        s.awaiting.insert("desktop".into(), awaited.clone());
1743        assert!(s.names("park-home") && s.names("aside-1") && !s.names("aside-2"));
1744        assert!(s.moves("aside-1") && s.moving(ProviderId::Desktop).is_some());
1745
1746        let written = serde_json::to_value(&s).unwrap();
1747        assert_eq!(written["moving"]["desktop"]["half"], "arrive");
1748        assert_eq!(
1749            written["moving"]["desktop"]["asides"]["aside-1"],
1750            "in_the_way"
1751        );
1752        assert_eq!(written["awaiting"]["desktop"]["put_back"], "work-uuid");
1753        let read: State = serde_json::from_value(written).unwrap();
1754        assert_eq!(read.moving, s.moving);
1755        assert_eq!(read.awaiting, s.awaiting);
1756        let plain = serde_json::to_value(State::default()).unwrap();
1757        assert!(plain.get("moving").is_none() && plain.get("awaiting").is_none());
1758
1759        // A folder a move holds is never listed to be deleted, forgotten or not.
1760        s.remove(&home);
1761        assert!(discarded(&s).is_empty(), "{:?}", s.discarded);
1762        assert_eq!(
1763            s.awaiting["desktop"].account, None,
1764            "a Sign In Again of a forgotten account reads as an add"
1765        );
1766        s.remove(&work);
1767        assert!(s.awaiting.is_empty(), "nothing is left to put back");
1768    }
1769
1770    #[test]
1771    fn a_folder_park_replaced_is_set_aside_and_never_listed_for_deletion() {
1772        let mut s = State::default();
1773        s.accounts.push(account("work", None));
1774        s.accounts.push(account("home", Some(park("vault-old"))));
1775        let (work, home) = (
1776            Key::new(ProviderId::Claude, "work"),
1777            Key::new(ProviderId::Claude, "home"),
1778        );
1779        s.park(&work, folder_park("folder-old", "f1", 100));
1780        s.park(&work, folder_park("folder-new", "f2", 200));
1781        assert_eq!(
1782            s.get(&work).unwrap().parked.as_ref().unwrap().service,
1783            "folder-new"
1784        );
1785        assert_eq!(
1786            s.aside,
1787            [Aside {
1788                name: "folder-old".into(),
1789                tool: ProviderId::Claude,
1790                at: 200,
1791                why: SetAside::Superseded,
1792                account: Some("work-uuid".into()),
1793                login: Some("f1".into()),
1794            }]
1795        );
1796        assert!(discarded(&s).is_empty(), "never listed for deletion");
1797        assert!(s.names("folder-old") && s.names("folder-new"));
1798        assert_eq!(s.aside_of("work-uuid").count(), 1);
1799
1800        // A vault park replaced is let go as it always was.
1801        s.park(&home, park("vault-new"));
1802        assert_eq!(discarded(&s), ["vault-old"]);
1803        assert_eq!(s.aside.len(), 1);
1804
1805        assert_eq!(
1806            s.drop_aside("folder-old").map(|a| a.name).as_deref(),
1807            Some("folder-old")
1808        );
1809        assert!(!s.names("folder-old"));
1810    }
1811
1812    #[test]
1813    fn forgetting_an_account_is_the_only_way_its_folder_is_listed_forgotten() {
1814        let mut s = State::default();
1815        s.accounts.push(account("work", None));
1816        s.accounts.push(account("home", None));
1817        let (work, home) = (
1818            Key::new(ProviderId::Claude, "work"),
1819            Key::new(ProviderId::Claude, "home"),
1820        );
1821        s.park(&work, folder_park("work-1", "f1", 100));
1822        s.park(&work, folder_park("work-2", "f2", 200));
1823        s.park(&home, folder_park("home-1", "f3", 100));
1824        s.set_aside(
1825            &home,
1826            folder_park("home-0", "f0", 50),
1827            SetAside::GivenUp,
1828            300,
1829        );
1830        s.discard("emptied", ParkKind::Folder);
1831        assert!(
1832            s.discarded.iter().all(|d| !d.forgotten),
1833            "{:?}",
1834            s.discarded
1835        );
1836
1837        s.remove(&work);
1838        let forgotten: Vec<&str> = s
1839            .discarded
1840            .iter()
1841            .filter(|d| d.forgotten)
1842            .map(|d| d.service.as_str())
1843            .collect();
1844        assert_eq!(
1845            forgotten,
1846            ["work-2", "work-1"],
1847            "its park, and what was set aside for it"
1848        );
1849        assert!(s.discarded.iter().all(|d| d.kind == ParkKind::Folder));
1850        assert_eq!(
1851            s.aside.iter().map(|a| a.name.as_str()).collect::<Vec<_>>(),
1852            ["home-0"],
1853            "another account's stays"
1854        );
1855        assert!(s.get(&home).unwrap().parked.is_some());
1856
1857        s.forget_asides();
1858        assert!(s.aside.is_empty());
1859        assert!(
1860            s.discarded
1861                .iter()
1862                .any(|d| d.service == "home-0" && d.forgotten)
1863        );
1864        assert!(!s.discarded.iter().any(|d| d.service == "home-1"));
1865    }
1866
1867    #[test]
1868    fn a_discarded_entry_already_typed_is_left_as_it_is() {
1869        let mut document = serde_json::json!({
1870            "schema": 7, "machine": machine_id(), "accounts": [],
1871            "discarded": ["pitboard-park-a-1", {"service": "pitboard-park-b-2"}]
1872        });
1873        migrate(
1874            &mut document,
1875            std::path::Path::new("/tmp/state.json"),
1876            crate::host::OS,
1877        )
1878        .expect("7 to 9");
1879        assert_eq!(
1880            document["discarded"],
1881            serde_json::json!([{"service": "pitboard-park-a-1"}, {"service": "pitboard-park-b-2"}])
1882        );
1883    }
1884
1885    /// 0.11.0 kept a Codex plan beside the workspace, as its token says it.
1886    #[test]
1887    fn a_codex_plan_0_11_0_recorded_is_the_accounts_plan() {
1888        let scratch = tempfile::tempdir().expect("a scratch folder");
1889        let home = scratch.path().to_path_buf();
1890        let ctx = Context::new(home.clone()).with_pitboard_home(home.clone());
1891        let mut state = State::default();
1892        state.accounts.push(codex_account("work"));
1893        save(&ctx, Permit::for_a_test(), &state).expect("saved");
1894        let path = home.join("state.json");
1895        let read = |path: &PathBuf| -> Value {
1896            serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap()
1897        };
1898        let mut written = read(&path);
1899        written["schema"] = 7.into();
1900        written["accounts"][0]["plan"] = "pro".into();
1901        std::fs::write(&path, written.to_string()).unwrap();
1902
1903        let state = load(&ctx).expect("read");
1904        assert_eq!(state.accounts[0].plan.as_deref(), Some("pro"));
1905        save(&ctx, Permit::for_a_test(), &state).expect("saved");
1906
1907        brought_forward(&mut written);
1908        assert_eq!(read(&path), written);
1909        assert_eq!(read(&path)["accounts"][0]["label"], "work");
1910    }
1911
1912    /// A file as 0.8.0 writes it. Each account keeps the id its parks, readings and windows
1913    /// are already filed under.
1914    #[test]
1915    fn the_format_0_8_0_writes_keeps_every_account_where_it_is_filed() {
1916        let mut document = serde_json::json!({
1917            "schema": 4,
1918            "machine": machine_id(),
1919            "accounts": [
1920                {
1921                    "label": "work",
1922                    "account_uuid": "acc-1",
1923                    "email": "a@b.c",
1924                    "parked": {
1925                        "service": "pitboard-park-acc-1-1789935600123",
1926                        "parked_at": 1_789_935_600,
1927                        "refresh_fingerprint": "abcd",
1928                        "access_expires_at": 1_789_999_999,
1929                        "refresh_expires_at": 1_792_000_000
1930                    },
1931                    "last_used_at": 1_789_935_000,
1932                    "provider": "claude",
1933                    "organization_uuid": "org-1",
1934                    "oauth_account": {
1935                        "accountUuid": "acc-1",
1936                        "emailAddress": "a@b.c",
1937                        "organizationUuid": "org-1"
1938                    }
1939                },
1940                {
1941                    "label": "work",
1942                    "account_uuid": "team_user-1",
1943                    "email": "a@b.c",
1944                    "parked": null,
1945                    "last_used_at": null,
1946                    "provider": "codex",
1947                    "workspace_id": "team",
1948                    "plan": "team"
1949                }
1950            ],
1951            "active": {"claude": "work", "codex": "work"},
1952            "slot": {"claude": "Claude Code-credentials", "codex": "/home/a/.codex"},
1953            "discarded": [],
1954            "foreign": []
1955        });
1956        migrate(
1957            &mut document,
1958            std::path::Path::new("/tmp/state.json"),
1959            crate::host::OS,
1960        )
1961        .expect("4 to 9");
1962        let state: State = serde_json::from_value(document).expect("parses");
1963
1964        let work = state.get(&claude("work")).unwrap();
1965        assert_eq!(
1966            (work.id.as_str(), work.account_uuid.as_str()),
1967            ("acc-1", "acc-1")
1968        );
1969        let codex = state.get(&Key::new(ProviderId::Codex, "work")).unwrap();
1970        assert_eq!(codex.id, "team_user-1");
1971        assert_eq!(
1972            state.owner_of_park("acc-1").map(Account::key),
1973            Some(work.key())
1974        );
1975        let signed_in = Owner {
1976            account_uuid: "acc-1".into(),
1977            email: "a@b.c".into(),
1978            organization_uuid: "org-1".into(),
1979        };
1980        assert_eq!(
1981            state.id_of(ProviderId::Claude, &signed_in),
1982            "acc-1",
1983            "the login it was enrolled with is still found by its organisation"
1984        );
1985    }
1986
1987    /// Anthropic's account uuid is the person. Their logins to two organisations are two
1988    /// accounts, and a third organisation's is neither.
1989    #[test]
1990    fn one_person_in_two_organisations_is_two_accounts() {
1991        let in_org = |label: &str, id: &str, org: &str| Account {
1992            last_used_at: None,
1993            replaced_at: None,
1994            plan: None,
1995            label: label.into(),
1996            id: id.into(),
1997            account_uuid: "acc".into(),
1998            email: "a@b.c".into(),
1999            detail: Detail::Claude {
2000                organization_uuid: org.into(),
2001                oauth_account: serde_json::json!({}),
2002            },
2003            parked: None,
2004        };
2005        let mut state = State::default();
2006        state.upsert(in_org("work", "acc", "org-a"));
2007        state.upsert(in_org("team", "acc_org-b", "org-b"));
2008        let signed_in = |org: &str| Owner {
2009            account_uuid: "acc".into(),
2010            email: "a@b.c".into(),
2011            organization_uuid: org.into(),
2012        };
2013        let label_of = |org: &str| {
2014            state
2015                .account_of(ProviderId::Claude, &signed_in(org))
2016                .map(|a| a.label.as_str())
2017        };
2018
2019        assert_eq!(label_of("org-a"), Some("work"));
2020        assert_eq!(label_of("org-b"), Some("team"));
2021        assert_eq!(label_of("org-c"), None);
2022        assert_eq!(
2023            state.id_of(ProviderId::Claude, &signed_in("org-c")),
2024            "acc_org-c"
2025        );
2026        assert!(
2027            state
2028                .account_of(ProviderId::Codex, &signed_in("org-a"))
2029                .is_none()
2030        );
2031    }
2032
2033    /// `Detail` is flattened and tagged, which is the whole reason the migration has
2034    /// nothing to move. If it ever stopped sitting beside `label` in the file, every
2035    /// account already written would stop loading.
2036    #[test]
2037    fn a_providers_own_fields_sit_beside_the_shared_ones() {
2038        let account = Account {
2039            label: "work".into(),
2040            id: "acc".into(),
2041            account_uuid: "acc".into(),
2042            email: "a@b.c".into(),
2043            parked: None,
2044            last_used_at: None,
2045            replaced_at: None,
2046            plan: None,
2047            detail: Detail::Claude {
2048                organization_uuid: "org".into(),
2049                oauth_account: serde_json::json!({"emailAddress": "a@b.c"}),
2050            },
2051        };
2052        let written = serde_json::to_value(&account).expect("writes");
2053        assert_eq!(written["provider"], "claude");
2054        assert_eq!(written["organization_uuid"], "org");
2055        assert_eq!(written["label"], "work");
2056        assert!(
2057            written.get("detail").is_none(),
2058            "flattened, so there is no nested object: {written}"
2059        );
2060        let back: Account = serde_json::from_value(written).expect("reads back");
2061        assert_eq!(back.provider(), ProviderId::Claude);
2062        assert_eq!(back.claude().unwrap().organization_uuid, "org");
2063    }
2064
2065    /// A file naming a tool this build does not know came from a newer Pitboard. Called
2066    /// corrupt, its advice would be to delete it, which orphans every parked login.
2067    #[test]
2068    fn an_account_of_an_unknown_tool_asks_for_an_upgrade_not_a_deletion() {
2069        let scratch = tempfile::tempdir().expect("a scratch folder");
2070        let home = scratch.path().to_path_buf();
2071        let ctx = Context::new(home.clone()).with_pitboard_home(home.clone());
2072        std::fs::write(
2073            home.join("state.json"),
2074            serde_json::json!({
2075                "schema": SCHEMA,
2076                "machine": machine_id(),
2077                "accounts": [{
2078                    "label": "work", "account_uuid": "u", "email": "a@b.c",
2079                    "parked": null, "provider": "somethingnew"
2080                }],
2081                "in_use": {}, "slot": {}, "discarded": []
2082            })
2083            .to_string(),
2084        )
2085        .unwrap();
2086        let err = load(&ctx).unwrap_err();
2087        assert_eq!(err.code(), "state_names_unknown_tool");
2088        assert!(err.to_string().contains("somethingnew"), "{err}");
2089        assert!(!err.to_string().contains("Delete"), "{err}");
2090    }
2091
2092    /// Two writes of the index within one second are two changes to a front end that follows
2093    /// it: a switch typed in a terminal in the second of the last write it saw went unseen
2094    /// until it next looked for another reason.
2095    #[test]
2096    fn two_writes_within_one_second_are_two_changes() {
2097        let scratch = tempfile::tempdir().expect("a scratch folder");
2098        let home = scratch.path().to_path_buf();
2099        let ctx = Context::new(home.clone()).with_pitboard_home(home.clone());
2100        std::fs::write(home.join("state.json"), "{}").unwrap();
2101        let second = std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_760_000_000);
2102        let written_at = |millis| {
2103            std::fs::File::options()
2104                .write(true)
2105                .open(home.join("state.json"))
2106                .and_then(|index| {
2107                    index.set_modified(second + std::time::Duration::from_millis(millis))
2108                })
2109                .expect("the index's time set");
2110            changed_at(&ctx)
2111        };
2112        assert_ne!(written_at(100), written_at(600));
2113    }
2114
2115    // Every Linux Pitboard before schema 9 parked in files (`store/vault.rs`), so a home it kept
2116    // stays in files, even where a Secret Service answers by now.
2117    #[test]
2118    fn a_schema_8_file_linux_wrote_comes_forward_with_its_parks_in_files() {
2119        let written = serde_json::json!({
2120            "schema": 8, "machine": machine_id(), "accounts": [], "discarded": []
2121        });
2122        let mut document = written.clone();
2123        migrate(
2124            &mut document,
2125            std::path::Path::new("/tmp/state.json"),
2126            Os::Linux,
2127        )
2128        .expect("8 to 9");
2129        assert_eq!(document["schema"], 9);
2130        assert_eq!(document["vault"], serde_json::json!({"form": "files"}));
2131        let state: State = serde_json::from_value(document).expect("parses");
2132        assert_eq!(state.vault, Some(Vault::kept_as(VaultForm::Files)));
2133
2134        let scratch = tempfile::tempdir().expect("a scratch folder");
2135        let home = scratch.path().join("home");
2136        let env = crate::context::Environment::on(
2137            Os::Linux,
2138            [("HOME", home.to_string_lossy().into_owned())],
2139        );
2140        let mem = crate::host::memory::MemoryHost::by_form();
2141        let ctx = Context::read(&env, "cli")
2142            .with_pitboard_home(home.join(".pitboard"))
2143            .with_memory_stores(std::sync::Arc::clone(&mem));
2144        std::fs::create_dir_all(home.join(".pitboard")).expect("a Pitboard home");
2145        std::fs::write(home.join(".pitboard/state.json"), written.to_string()).expect("written");
2146        assert_eq!(vault_form(&ctx).expect("read"), Some(VaultForm::Files));
2147        save(&ctx, Permit::for_a_test(), &load(&ctx).expect("loaded")).expect("saved");
2148        let saved: Value = serde_json::from_str(
2149            &std::fs::read_to_string(home.join(".pitboard/state.json")).unwrap(),
2150        )
2151        .unwrap();
2152        assert_eq!(saved["vault"], serde_json::json!({"form": "files"}));
2153        assert_eq!(saved["schema"], SCHEMA);
2154    }
2155
2156    // macOS keeps every park in the keychain and Windows in files sealed to the account: one way
2157    // each, so neither records one.
2158    #[test]
2159    fn a_schema_8_file_from_macos_or_windows_comes_forward_with_no_vault_form() {
2160        for os in [Os::MacOs, Os::Windows] {
2161            let mut document = serde_json::json!({
2162                "schema": 8, "machine": machine_id(), "accounts": [], "discarded": []
2163            });
2164            migrate(&mut document, std::path::Path::new("/tmp/state.json"), os).expect("8 to 9");
2165            assert_eq!(document["schema"], 9, "{os:?}");
2166            assert!(document.get("vault").is_none(), "{os:?}: {document}");
2167            let state: State = serde_json::from_value(document).expect("parses");
2168            assert_eq!(state.vault, None, "{os:?}");
2169        }
2170
2171        let scratch = tempfile::tempdir().expect("a scratch folder");
2172        let ctx = Context::new(scratch.path().to_path_buf())
2173            .with_pitboard_home(scratch.path().join(".pitboard"))
2174            .with_memory_stores(crate::host::memory::MemoryHost::new());
2175        save(&ctx, Permit::for_a_test(), &State::default()).expect("saved");
2176        let saved = std::fs::read_to_string(scratch.path().join(".pitboard/state.json")).unwrap();
2177        assert!(!saved.contains("vault"), "{saved}");
2178    }
2179
2180    /// The other direction cannot work, and the message has to say which half to upgrade.
2181    #[test]
2182    fn a_file_from_a_newer_pitboard_is_refused() {
2183        let mut current =
2184            serde_json::json!({"schema": SCHEMA, "machine": machine_id(), "accounts": []});
2185        migrate(
2186            &mut current,
2187            std::path::Path::new("/tmp/state.json"),
2188            crate::host::OS,
2189        )
2190        .expect("this one's own");
2191        let mut document = serde_json::json!({"schema": SCHEMA + 1});
2192        let err = migrate(
2193            &mut document,
2194            std::path::Path::new("/tmp/state.json"),
2195            crate::host::OS,
2196        )
2197        .unwrap_err();
2198        assert_eq!(err.code(), "state_from_newer_version");
2199        let said = err.to_string();
2200        assert!(said.contains("Update this Pitboard"), "{said}");
2201        assert!(
2202            !said.contains("brew") && !said.contains("cargo"),
2203            "it names no one way of installing Pitboard: {said}"
2204        );
2205    }
2206
2207    #[test]
2208    fn a_schema_number_too_large_to_hold_is_refused() {
2209        let mut document = serde_json::json!({
2210            "schema": (1_u64 << 32) + u64::from(SCHEMA),
2211            "machine": machine_id(),
2212            "accounts": []
2213        });
2214        let err = migrate(
2215            &mut document,
2216            std::path::Path::new("/tmp/state.json"),
2217            crate::host::OS,
2218        )
2219        .unwrap_err();
2220        assert_eq!(err.code(), "state_from_newer_version");
2221    }
2222
2223    #[test]
2224    fn each_migration_step_stamps_the_schema_it_brings_a_file_to() {
2225        for (from, step) in [
2226            (3, three_to_four as fn(&mut Value)),
2227            (4, four_to_five),
2228            (5, five_to_six),
2229            (6, six_to_seven),
2230            (7, seven_to_eight),
2231            (8, |document| eight_to_nine(document, Os::Linux)),
2232            (8, |document| eight_to_nine(document, Os::MacOs)),
2233        ] {
2234            let mut document = serde_json::json!({"schema": from, "accounts": []});
2235            step(&mut document);
2236            assert_eq!(document["schema"], from + 1, "the step from {from}");
2237        }
2238    }
2239
2240    use super::*;
2241
2242    // An older file as this schema writes it back, on this system: on Linux, with its parks in
2243    // files, where every earlier Pitboard there kept them.
2244    fn brought_forward(written: &mut Value) {
2245        written["schema"] = SCHEMA.into();
2246        match crate::host::OS {
2247            Os::Linux => written["vault"] = serde_json::json!({"form": "files"}),
2248            Os::MacOs | Os::Windows => {}
2249        }
2250    }
2251
2252    fn claude(label: &str) -> Key {
2253        Key::new(ProviderId::Claude, label)
2254    }
2255
2256    #[test]
2257    fn machine_id_is_stable_and_real() {
2258        let a = machine_id();
2259        assert_eq!(a, machine_id());
2260        assert_eq!(
2261            a.len(),
2262            64,
2263            "expected a sha256 of the platform id, got {a:?}"
2264        );
2265        assert_ne!(
2266            a, "unknown",
2267            "this platform should report a stable machine id"
2268        );
2269    }
2270
2271    fn park(service: &str) -> Park {
2272        Park {
2273            service: service.into(),
2274            parked_at: 100,
2275            kind: ParkKind::Vault,
2276            login: "f".into(),
2277            access_expires_at: Some(200),
2278            refresh_expires_at: Some(300),
2279            session_expires_at: None,
2280        }
2281    }
2282
2283    fn discarded(s: &State) -> Vec<&str> {
2284        s.discarded.iter().map(|d| d.service.as_str()).collect()
2285    }
2286
2287    fn account(label: &str, parked: Option<Park>) -> Account {
2288        Account {
2289            last_used_at: None,
2290            replaced_at: None,
2291            plan: None,
2292            label: label.into(),
2293            id: format!("{label}-uuid"),
2294            account_uuid: format!("{label}-uuid"),
2295            email: format!("{label}@example.com"),
2296            detail: Detail::Claude {
2297                organization_uuid: "o".into(),
2298                oauth_account: serde_json::json!({}),
2299            },
2300            parked,
2301        }
2302    }
2303
2304    #[test]
2305    fn a_new_park_discards_the_one_it_replaces() {
2306        let mut s = State::default();
2307        s.upsert(account("work", Some(park("old"))));
2308        s.park(&claude("work"), park("new"));
2309        assert_eq!(
2310            s.get(&claude("work"))
2311                .unwrap()
2312                .parked
2313                .as_ref()
2314                .unwrap()
2315                .service,
2316            "new"
2317        );
2318        assert_eq!(discarded(&s), ["old"]);
2319        assert!(!s.references("old"));
2320    }
2321
2322    #[test]
2323    fn discarding_releases_whichever_account_held_it_and_lists_it_once() {
2324        let mut s = State::default();
2325        s.upsert(account("work", Some(park("current"))));
2326        s.discard("something-else", ParkKind::Vault);
2327        assert!(s.get(&claude("work")).unwrap().parked.is_some());
2328        s.discard("current", ParkKind::Vault);
2329        s.discard("current", ParkKind::Vault);
2330        assert!(s.get(&claude("work")).unwrap().parked.is_none());
2331        assert_eq!(discarded(&s), ["something-else", "current"]);
2332    }
2333
2334    /// A park let go of, installed or replaced, is no longer written down as a copy of a
2335    /// file's login, and the list is left out of the file while it is empty.
2336    #[test]
2337    fn a_park_let_go_of_is_no_longer_a_copy_of_a_files_login() {
2338        let mut s = State::default();
2339        s.upsert(account("work", Some(park("copy"))));
2340        assert!(!serde_json::to_string(&s).unwrap().contains("from_file"));
2341        s.copying_from_file("copy");
2342        s.copying_from_file("copy");
2343        assert_eq!(s.from_file, ["copy"]);
2344        assert!(s.is_from_file("copy"));
2345
2346        s.park(&claude("work"), park("renewed"));
2347        assert!(s.from_file.is_empty());
2348        assert!(!s.file_gone(), "nothing was written down by then");
2349    }
2350
2351    #[test]
2352    fn relabelling_keeps_the_account_and_its_park() {
2353        let mut s = State::default();
2354        s.upsert(account("wrong", Some(park("p"))));
2355        s.upsert(account("other", None));
2356
2357        assert_eq!(
2358            s.relabel(&claude("wrong"), "right").unwrap().email,
2359            "wrong@example.com"
2360        );
2361        assert!(s.get(&claude("wrong")).is_none());
2362        let renamed = s.get(&claude("right")).unwrap();
2363        assert_eq!(renamed.account_uuid, "wrong-uuid");
2364        assert_eq!(renamed.parked.as_ref().unwrap().service, "p");
2365        assert!(s.discarded.is_empty(), "nothing is deleted by a rename");
2366    }
2367
2368    /// The record names whose login is stored, not a label, so a rename has nothing in it
2369    /// to change.
2370    #[test]
2371    fn renaming_an_account_leaves_the_record_alone() {
2372        let mut s = State::default();
2373        s.upsert(account("wrong", None));
2374        let found = InUse::of(s.get(&claude("wrong")).unwrap(), "f", 100);
2375        s.identified(ProviderId::Claude, found.clone(), 100);
2376
2377        s.relabel(&claude("wrong"), "right").unwrap();
2378
2379        assert_eq!(s.in_use(ProviderId::Claude), Some(&found));
2380        assert_eq!(
2381            s.account_in_use(ProviderId::Claude)
2382                .map(|a| a.label.as_str()),
2383            Some("right")
2384        );
2385    }
2386
2387    #[test]
2388    fn relabelling_refuses_a_taken_label_and_an_unknown_one() {
2389        let mut s = State::default();
2390        s.upsert(account("a", None));
2391        s.upsert(account("b", None));
2392        assert!(matches!(
2393            s.relabel(&claude("a"), "b"),
2394            Err(Error::LabelTaken { .. })
2395        ));
2396        assert!(matches!(
2397            s.relabel(&claude("nobody"), "c"),
2398            Err(Error::AccountUnknown { .. })
2399        ));
2400        assert_eq!(
2401            s.accounts
2402                .iter()
2403                .map(|a| a.label.as_str())
2404                .collect::<Vec<_>>(),
2405            ["a", "b"],
2406            "a refused rename changes nothing"
2407        );
2408        assert!(s.relabel(&claude("a"), "a").is_ok());
2409    }
2410
2411    /// Anthropic naming another account's login, where the account in use had nothing
2412    /// parked, means a sign-in outside Pitboard wrote over that account's only login.
2413    #[test]
2414    fn an_answer_naming_another_account_marks_the_account_whose_only_login_it_replaced() {
2415        let mut s = State::default();
2416        s.upsert(account("work", None));
2417        s.upsert(account("personal", None));
2418        s.upsert(account("spare", Some(park("p"))));
2419        let said = |s: &State, label: &str, login: &str, at: i64| {
2420            InUse::of(s.get(&claude(label)).unwrap(), login, at)
2421        };
2422        let work = said(&s, "work", "work-login", 100);
2423        s.identified(ProviderId::Claude, work, 100);
2424
2425        let personal = said(&s, "personal", "personal-login", 200);
2426        let identified = s.identified(ProviderId::Claude, personal.clone(), 200);
2427        assert!(identified.changed);
2428        assert_eq!(
2429            identified.replaced,
2430            Some(Replaced {
2431                key: claude("work")
2432            })
2433        );
2434        assert_eq!(s.get(&claude("work")).unwrap().replaced_at, Some(200));
2435        let now = s.get(&claude("personal")).unwrap();
2436        assert_eq!((now.last_used_at, now.replaced_at), (Some(200), None));
2437        assert_eq!(s.in_use(ProviderId::Claude), Some(&personal));
2438
2439        // The same account on another login: a renewal, or a sign-in to it again.
2440        let renewed = InUse {
2441            login: "personal-renewed".into(),
2442            known_at: 300,
2443            ..personal
2444        };
2445        let identified = s.identified(ProviderId::Claude, renewed.clone(), 300);
2446        assert!(identified.changed);
2447        assert_eq!(identified.replaced, None);
2448        assert_eq!(
2449            s.get(&claude("personal")).unwrap().last_used_at,
2450            Some(200),
2451            "still the account it was"
2452        );
2453
2454        let again = InUse {
2455            known_at: 400,
2456            ..renewed
2457        };
2458        assert!(!s.identified(ProviderId::Claude, again, 400).changed);
2459        assert_eq!(
2460            s.in_use(ProviderId::Claude).map(|r| r.known_at),
2461            Some(300),
2462            "known since it was first said"
2463        );
2464
2465        // An account that holds a parked login lost nothing when its login in use went.
2466        let spare = said(&s, "spare", "spare-login", 500);
2467        s.identified(ProviderId::Claude, spare, 500);
2468        let back = said(&s, "work", "work-login-2", 600);
2469        let identified = s.identified(ProviderId::Claude, back, 600);
2470        assert_eq!(identified.replaced, None);
2471        assert_eq!(s.get(&claude("spare")).unwrap().replaced_at, None);
2472        assert_eq!(
2473            s.get(&claude("work")).unwrap().replaced_at,
2474            None,
2475            "in use again"
2476        );
2477    }
2478
2479    /// An account signed in under two `CLAUDE_CONFIG_DIR`s keeps its login in the other when
2480    /// a sign-in to another account replaces it in this one, so it lost nothing. Once no
2481    /// slot's record names it, the login replaced was its only one.
2482    #[test]
2483    fn a_login_another_slot_still_holds_is_not_the_only_one() {
2484        let mut s = State::default();
2485        s.upsert(account("work", None));
2486        s.upsert(account("personal", None));
2487        let said = |s: &State, label: &str, login: &str, at: i64| {
2488            InUse::of(s.get(&claude(label)).unwrap(), login, at)
2489        };
2490        let other = |s: &mut State, record: InUse| {
2491            s.other_slots
2492                .entry(ProviderId::Claude.code().into())
2493                .or_default()
2494                .insert("Claude Code-credentials-other".into(), record);
2495        };
2496        let work_there = said(&s, "work", "work-there", 50);
2497        other(&mut s, work_there);
2498        let work = said(&s, "work", "work-login", 100);
2499        s.identified(ProviderId::Claude, work, 100);
2500
2501        let personal = said(&s, "personal", "personal-login", 200);
2502        let identified = s.identified(ProviderId::Claude, personal, 200);
2503
2504        assert_eq!(identified.replaced, None);
2505        assert_eq!(s.get(&claude("work")).unwrap().replaced_at, None);
2506
2507        let work = said(&s, "work", "work-login-2", 300);
2508        s.identified(ProviderId::Claude, work, 300);
2509        let personal_there = said(&s, "personal", "personal-there", 350);
2510        other(&mut s, personal_there);
2511        let personal = said(&s, "personal", "personal-login", 400);
2512        let identified = s.identified(ProviderId::Claude, personal, 400);
2513
2514        assert_eq!(
2515            identified.replaced,
2516            Some(Replaced {
2517                key: claude("work")
2518            })
2519        );
2520        assert_eq!(s.get(&claude("work")).unwrap().replaced_at, Some(400));
2521    }
2522
2523    #[test]
2524    fn parking_a_replaced_account_clears_it() {
2525        let mut s = State::default();
2526        s.upsert(account("work", None));
2527        s.upsert(account("personal", None));
2528        for (label, at) in [("work", 100), ("personal", 200)] {
2529            let found = InUse::of(s.get(&claude(label)).unwrap(), label, at);
2530            s.identified(ProviderId::Claude, found, at);
2531        }
2532        assert_eq!(s.get(&claude("work")).unwrap().replaced_at, Some(200));
2533
2534        s.park(&claude("work"), park("p"));
2535
2536        assert_eq!(s.get(&claude("work")).unwrap().replaced_at, None);
2537    }
2538
2539    #[test]
2540    fn removing_an_account_lists_its_park_for_deletion() {
2541        let mut s = State::default();
2542        s.upsert(account("work", Some(park("p"))));
2543        assert_eq!(s.remove(&claude("work")).unwrap().label, "work");
2544        assert!(s.accounts.is_empty());
2545        assert_eq!(discarded(&s), ["p"]);
2546    }
2547
2548    /// A park `repair` gave back may be another Pitboard's. Replaced by a newer one, or
2549    /// dropped with its account, it was never used here, so it is let go and not deleted.
2550    #[test]
2551    fn a_park_this_home_did_not_write_is_let_go_and_never_listed_for_deletion() {
2552        let mut s = State::default();
2553        s.upsert(account("work", None));
2554        s.upsert(account("home", None));
2555        s.park_foreign(&claude("work"), park("found"));
2556        s.park_foreign(&claude("home"), park("also-found"));
2557        assert_eq!(s.foreign, ["found", "also-found"]);
2558
2559        s.park(&claude("work"), park("ours"));
2560        assert_eq!(
2561            s.get(&claude("work"))
2562                .unwrap()
2563                .parked
2564                .as_ref()
2565                .unwrap()
2566                .service,
2567            "ours"
2568        );
2569        s.remove(&claude("home"));
2570        s.release("ours");
2571
2572        assert_eq!(discarded(&s), ["ours"], "only the park this home wrote");
2573        assert!(s.foreign.is_empty(), "and nothing here holds the others");
2574    }
2575
2576    /// Installed or renewed, a park has been used up whoever wrote it, and goes the way
2577    /// every used park goes.
2578    #[test]
2579    fn a_park_this_home_did_not_write_is_listed_once_it_is_used() {
2580        let mut s = State::default();
2581        s.upsert(account("work", None));
2582        s.park_foreign(&claude("work"), park("found"));
2583        s.discard("found", ParkKind::Vault);
2584        assert!(s.get(&claude("work")).unwrap().parked.is_none());
2585        assert_eq!(discarded(&s), ["found"]);
2586        assert!(s.foreign.is_empty());
2587    }
2588
2589    /// Schema 4 is new on this branch and gained the record of parks written elsewhere
2590    /// after it was first written, so a file without it has to load as one holding none.
2591    #[test]
2592    fn a_state_file_from_before_foreign_parks_were_recorded_still_loads() {
2593        let written = serde_json::json!({
2594            "schema": 4,
2595            "machine": machine_id(),
2596            "accounts": [{
2597                "label": "work", "account_uuid": "acc-1", "email": "a@b.c",
2598                "provider": "codex", "workspace_id": null, "plan": "pro",
2599                "parked": {
2600                    "service": "pitboard-park-acc-1-1789935600123",
2601                    "parked_at": 1_789_935_600,
2602                    "refresh_fingerprint": "abcd",
2603                    "access_expires_at": null,
2604                    "refresh_expires_at": null
2605                }
2606            }],
2607            "active": {}, "slot": {}, "discarded": []
2608        });
2609        let mut document = written;
2610        migrate(
2611            &mut document,
2612            std::path::Path::new("/tmp/state.json"),
2613            crate::host::OS,
2614        )
2615        .expect("current");
2616        let mut state: State = serde_json::from_value(document).expect("still parses");
2617        assert!(state.foreign.is_empty());
2618        state.remove(&Key::new(ProviderId::Codex, "work"));
2619        assert_eq!(
2620            discarded(&state),
2621            ["pitboard-park-acc-1-1789935600123"],
2622            "a park recorded before is this home's own, and goes as it always did"
2623        );
2624    }
2625
2626    #[test]
2627    fn a_park_is_restorable_until_its_login_expires() {
2628        let p = park("p");
2629        assert!(p.askable_at(199) && !p.askable_at(200));
2630        assert!(p.restorable_at(299) && !p.restorable_at(300));
2631        let unknown = Park {
2632            access_expires_at: None,
2633            refresh_expires_at: None,
2634            ..park("p")
2635        };
2636        assert!(
2637            unknown.restorable_at(i64::MAX),
2638            "no expiry recorded is not expired"
2639        );
2640    }
2641
2642    #[test]
2643    fn a_parked_login_is_due_from_three_days_before_it_expires() {
2644        const NOW: i64 = 1_789_935_600;
2645        assert!(!renewal_due(NOW + RENEW_WITHIN, NOW));
2646        assert!(renewal_due(NOW + RENEW_WITHIN - 1, NOW));
2647        assert!(renewal_due(NOW + 1, NOW));
2648        assert!(!renewal_due(NOW, NOW));
2649        assert!(!renewal_due(NOW - 60, NOW));
2650    }
2651
2652    #[test]
2653    fn accounts_are_replaced_by_label_not_duplicated() {
2654        let mut s = State::default();
2655        s.upsert(account("work", None));
2656        s.upsert(Account {
2657            email: "d@e.f".into(),
2658            ..account("work", None)
2659        });
2660        assert_eq!(s.accounts.len(), 1);
2661        assert_eq!(s.get(&claude("work")).unwrap().email, "d@e.f");
2662    }
2663
2664    fn codex_account(label: &str) -> Account {
2665        Account {
2666            last_used_at: None,
2667            replaced_at: None,
2668            plan: None,
2669            label: label.into(),
2670            id: format!("codex-{label}-uuid"),
2671            account_uuid: format!("codex-{label}-uuid"),
2672            email: format!("{label}@openai.example"),
2673            detail: Detail::Codex { workspace_id: None },
2674            parked: None,
2675        }
2676    }
2677
2678    /// Two tools, one label. Every lookup used to take the label alone and return the
2679    /// first match, so `pitboard use codex/work` could park and install Claude Code's
2680    /// `work` instead, and enrolling Codex's `work` replaced Claude Code's outright.
2681    #[test]
2682    fn two_tools_can_each_have_an_account_of_the_same_name() {
2683        let mut s = State::default();
2684        s.upsert(account("work", Some(park("claude-park"))));
2685        s.upsert(codex_account("work"));
2686        assert_eq!(
2687            s.accounts.len(),
2688            2,
2689            "the second is added, not a replacement"
2690        );
2691
2692        let codex = Key::new(ProviderId::Codex, "work");
2693        assert_eq!(s.get(&codex).unwrap().provider(), ProviderId::Codex);
2694        assert_eq!(
2695            s.get(&claude("work")).unwrap().provider(),
2696            ProviderId::Claude
2697        );
2698
2699        s.park(&codex, park("codex-park"));
2700        assert_eq!(
2701            s.get(&claude("work"))
2702                .unwrap()
2703                .parked
2704                .as_ref()
2705                .unwrap()
2706                .service,
2707            "claude-park",
2708            "parking one tool's account leaves the other's alone"
2709        );
2710
2711        s.remove(&codex);
2712        assert!(s.get(&claude("work")).is_some(), "and so does dropping it");
2713        assert_eq!(discarded(&s), ["codex-park"]);
2714    }
2715
2716    /// A label is unique within a tool, so renaming into a name only another tool uses is
2717    /// not a clash.
2718    #[test]
2719    fn a_rename_clashes_only_within_its_own_tool() {
2720        let mut s = State::default();
2721        s.upsert(account("personal", None));
2722        s.upsert(codex_account("work"));
2723        assert!(s.relabel(&claude("personal"), "work").is_ok());
2724        assert_eq!(
2725            s.get(&claude("work")).unwrap().email,
2726            "personal@example.com"
2727        );
2728    }
2729
2730    /// Forgetting an account leaves the login its tool has stored where it was, and the
2731    /// record says whose it is by owner, so another account given the same label is not in
2732    /// use, and the same account enrolled again is.
2733    #[test]
2734    fn removing_the_account_in_use_leaves_whose_login_is_stored() {
2735        let mut s = State::default();
2736        s.upsert(account("work", None));
2737        s.upsert(codex_account("work"));
2738        let codex = Key::new(ProviderId::Codex, "work");
2739        let found = InUse::of(s.get(&codex).unwrap(), "f", 100);
2740        s.identified(ProviderId::Codex, found.clone(), 100);
2741
2742        let forgotten = s.remove(&codex).expect("enrolled");
2743        assert_eq!(s.in_use(ProviderId::Codex), Some(&found));
2744        assert!(s.account_in_use(ProviderId::Codex).is_none());
2745
2746        s.upsert(Account {
2747            id: "codex-other-uuid".into(),
2748            account_uuid: "codex-other-uuid".into(),
2749            ..codex_account("work")
2750        });
2751        assert!(
2752            s.account_in_use(ProviderId::Codex).is_none(),
2753            "a label is not who is in use"
2754        );
2755        s.upsert(forgotten);
2756        assert_eq!(
2757            s.account_in_use(ProviderId::Codex).map(Account::key),
2758            Some(codex)
2759        );
2760    }
2761
2762    /// A bare name for an account whose label another tool shares would be refused as
2763    /// ambiguous, so the name every message suggests is qualified exactly then.
2764    #[test]
2765    fn a_name_is_qualified_where_a_bare_one_would_be_ambiguous() {
2766        let mut s = State::default();
2767        s.upsert(account("work", None));
2768        s.upsert(account("personal", None));
2769        s.upsert(codex_account("work"));
2770        assert_eq!(s.typed(&claude("work")), "claude/work");
2771        assert_eq!(s.typed(&Key::new(ProviderId::Codex, "work")), "codex/work");
2772        assert_eq!(s.typed(&claude("personal")), "personal");
2773    }
2774
2775    #[test]
2776    fn a_key_reads_the_way_it_would_be_typed() {
2777        assert_eq!(claude("work").to_string(), "work");
2778        assert_eq!(
2779            Key::new(ProviderId::Codex, "work").to_string(),
2780            "codex/work"
2781        );
2782        assert_eq!(claude("work").qualified(), "claude/work");
2783    }
2784}