pitboard_core/provider/mod.rs
1//! The boundary between pitboard's own machinery and one particular coding tool's login.
2//!
3//! pitboard was written against Claude Code, and for a long time that was the whole of it:
4//! the keychain slot hashing, the five keys a logout deletes, the write lock and its
5//! constants, the config file whose identity cache has to be spliced after a switch. None
6//! of that is a fact about parking a login. It is a fact about Claude Code.
7//!
8//! This module names the small set of things that genuinely differ between one tool and
9//! the next, so the rest of the crate can stop knowing which tool it is serving.
10//!
11//! # What is here and what deliberately is not
12//!
13//! Five operations: read the live credential, learn whose it is, measure what it has left,
14//! renew it, install it. Every one of them is something the engine has to call without
15//! caring how it is done underneath, and every one was checked against all three tools'
16//! measured shapes before it was written down rather than derived from Claude Code alone.
17//! [`Provider::usage`] takes the whole credential and the context rather than a bare access
18//! token for exactly that reason: Gemini's quota call needs a project id out of a second
19//! file that has nothing to do with the token, and a signature that looked sufficient after
20//! Claude and Codex would have been wrong.
21//!
22//! Three facts, as values rather than code paths: [`Adoption`], [`ParkSemantics`],
23//! [`Isolation`]. These are things the engine and the front ends must branch on, and a
24//! value lets them branch on the fact instead of on the provider's name. Nothing anywhere
25//! should read `if provider == Claude`.
26//!
27//! Four pure functions over a login document: which part of it belongs to the account,
28//! how to put another account's part in, a non-secret handle on its refresh token, and when
29//! it stops working. These are here because pitboard's own bookkeeping needs them and they
30//! are genuinely different per tool: Claude Code's login sits in a document the machine
31//! shares with unrelated keys, while Codex and Gemini keep one account per file. They were
32//! not in the first sketch of this trait, which is how it came to be a boundary nothing
33//! could actually park through.
34//!
35//! What is not here: a `park` method. Parking is pitboard's own bookkeeping, built out of
36//! the pieces above, and a method for it would have to hide the difference between splicing
37//! a shared document and replacing a whole file behind a flag. Also absent: Claude Code's
38//! config-file identity cache, its supervisor daemon, its status line hook. A method most
39//! implementations no-op is a sign it does not belong on a shared trait.
40
41pub(crate) mod claude;
42pub(crate) mod codex;
43pub(crate) mod jwt;
44
45use crate::context::Context;
46use crate::usage;
47use serde_json::Value;
48
49/// Which tool's login this is.
50///
51/// `non_exhaustive` from the first day it exists, while there is still only one variant, so
52/// every caller outside this crate is made to write a fallback arm before there is a second
53/// variant to catch them out.
54#[derive(
55 Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, serde::Serialize, serde::Deserialize,
56)]
57#[serde(rename_all = "snake_case")]
58#[non_exhaustive]
59pub enum ProviderId {
60 Claude,
61 Codex,
62}
63
64impl ProviderId {
65 /// Every provider pitboard knows, in the order a listing shows them.
66 ///
67 /// Named rather than written out at each call site, because resolving a bare label has
68 /// to look at all of them and a provider missing from one such list would simply never
69 /// be found, with nothing failing to say so.
70 pub const ALL: &'static [ProviderId] = &[ProviderId::Claude, ProviderId::Codex];
71
72 /// The one spelling used in a label prefix, in the state file, in a park's name and in
73 /// the audit log. Written once so those four cannot drift, and chosen from the command
74 /// a person types rather than the company behind it, because the command is the thing
75 /// that is stable.
76 pub fn code(self) -> &'static str {
77 match self {
78 ProviderId::Claude => "claude",
79 ProviderId::Codex => "codex",
80 }
81 }
82
83 /// The service behind the tool, as a person would name it.
84 ///
85 /// Not the same as the tool: `claude` talks to Anthropic, `codex` to OpenAI. Messages
86 /// about a failed request name this, because "could not reach OpenAI" is something
87 /// somebody can act on and "could not reach the service" is not.
88 pub fn service(self) -> &'static str {
89 match self {
90 ProviderId::Claude => "Anthropic",
91 ProviderId::Codex => "OpenAI",
92 }
93 }
94
95 /// The tool, as its own documentation names it.
96 pub fn name(self) -> &'static str {
97 match self {
98 ProviderId::Claude => "Claude Code",
99 ProviderId::Codex => "Codex",
100 }
101 }
102
103 /// The command a person types to run the tool.
104 pub fn program(self) -> &'static str {
105 match self {
106 ProviderId::Claude => "claude",
107 ProviderId::Codex => "codex",
108 }
109 }
110
111 /// The environment variable that moves where the tool keeps its login.
112 pub fn home_variable(self) -> &'static str {
113 match self {
114 ProviderId::Claude => "CLAUDE_CONFIG_DIR",
115 ProviderId::Codex => "CODEX_HOME",
116 }
117 }
118
119 /// What a person runs to sign in with the tool's own command. Claude Code signs in from
120 /// inside the program it starts; Codex has a subcommand for it.
121 pub fn login_command(self) -> &'static str {
122 match self {
123 ProviderId::Claude => "claude",
124 ProviderId::Codex => "codex login",
125 }
126 }
127
128 pub fn parse(code: &str) -> Option<ProviderId> {
129 match code {
130 "claude" => Some(ProviderId::Claude),
131 "codex" => Some(ProviderId::Codex),
132 _ => None,
133 }
134 }
135}
136
137impl std::fmt::Display for ProviderId {
138 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
139 f.write_str(self.code())
140 }
141}
142
143/// One tool's login document, carried without being understood.
144///
145/// The provider it came from travels with it, so a value crossing this boundary can always
146/// say which shape it is, and a credential can never be handed to the wrong engine by
147/// accident. What is inside is that engine's business and nothing else's.
148#[derive(Debug, Clone, PartialEq)]
149pub struct Credential {
150 pub provider: ProviderId,
151 pub raw: Value,
152}
153
154impl Credential {
155 pub fn new(provider: ProviderId, raw: Value) -> Credential {
156 Credential { provider, raw }
157 }
158}
159
160/// Who a credential belongs to, as the tool's own service understands it.
161///
162/// How this is learned is deliberately not part of the answer. Claude Code's is a network
163/// call to Anthropic on every switch, because its local config can lag the credential by a
164/// day. Codex's is a local decode of the ID token it already holds. Gemini's is a local
165/// decode when the token carries one and a network call when it does not. The engine wants
166/// the answer, not the method.
167#[derive(Debug, Clone, PartialEq, Eq)]
168pub struct Identity {
169 /// Stable for the life of the account. A UUID for Claude, a UUID for Codex's
170 /// `chatgpt_account_id`, Google's `sub` for Gemini.
171 pub account_id: String,
172 pub email: String,
173 /// Claude's organisation, Codex's ChatGPT workspace, Gemini's project. `None` where the
174 /// tool has no such concept or did not say, which is not the same as an empty one.
175 pub group: Option<String>,
176}
177
178/// Why an answer about a login could not be had.
179///
180/// Every variant says whether asking again later could answer differently, because that is
181/// the difference between a switch that should wait and one that should stop.
182#[derive(Debug, thiserror::Error)]
183#[non_exhaustive]
184pub enum ProviderError {
185 #[error("the session has expired")]
186 Unauthorized,
187 /// `retry_after` is what the service said to wait, in seconds, where it said anything.
188 #[error("{service} is rate limiting this request")]
189 RateLimited {
190 service: &'static str,
191 retry_after: Option<i64>,
192 },
193 #[error("could not reach {service}: {detail}")]
194 Network {
195 service: &'static str,
196 detail: String,
197 },
198 #[error("{service} answered {status}")]
199 Unexpected { service: &'static str, status: u16 },
200 #[error("{service}'s answer was not understood: {detail}")]
201 Malformed {
202 service: &'static str,
203 detail: String,
204 },
205 /// Refused for good: revoked, or already spent somewhere else.
206 #[error("{service} no longer accepts this login")]
207 InvalidGrant { service: &'static str },
208 /// The credential is not the shape this provider stores.
209 #[error("the stored login is not the shape {provider} keeps: {detail}")]
210 ShapeUnexpected {
211 provider: ProviderId,
212 detail: String,
213 },
214 /// The tool is configured to keep its login somewhere pitboard does not handle.
215 #[error("{reason}")]
216 Unsupported {
217 provider: ProviderId,
218 reason: String,
219 },
220 /// The document holds no account's login at all, which is what signing out leaves in a
221 /// document the machine also keeps other things in. Not a malformed login: none.
222 #[error("nothing is signed in")]
223 NoLogin { provider: ProviderId },
224}
225
226/// When a session that is already running picks a switch up.
227///
228/// Measured, not assumed, and it differs enough between tools that a single number would be
229/// a lie for two of the three. Claude Code serves its credential from a 30 second cache, so
230/// a session follows on its own. Codex caches for the life of the process, watches no file
231/// and refuses a reload whose account id has changed; Gemini caches its client for the
232/// process with no expiry. Neither ever notices.
233#[derive(Debug, Clone, Copy, PartialEq, Eq)]
234pub enum Adoption {
235 /// A session already running follows within this many seconds, with no action.
236 PollingWithin(u32),
237 /// Nothing follows until the program is started again. Never rendered as a countdown.
238 RestartRequired { program: &'static str },
239}
240
241/// Whether a parked copy may exist while the same account is still live.
242///
243/// For Claude Code it may: the live document holds the machine's other keys too, and
244/// nothing revokes for presenting either copy. For Codex it must not. `codex login` and
245/// `codex logout` both revoke the stored refresh token at OpenAI before clearing it, so a
246/// copy left live while its twin sits in the vault is a token the person's own next login
247/// can kill in both places at once.
248#[derive(Debug, Clone, Copy, PartialEq, Eq)]
249pub enum ParkSemantics {
250 /// A park may be a copy; the live credential can keep working.
251 CopyWhileLive,
252 /// There must never be two usable copies of one account's credential at rest on this
253 /// machine, not even between two steps of a switch.
254 MoveOnly,
255}
256
257/// Whether signing in to a second account in a private directory really leaves the live
258/// login alone.
259///
260/// The trick pitboard uses for enrolment is to point the tool's own sign-in at a scratch
261/// directory through its home variable, let it write there, and read back what it wrote.
262/// That works for `CLAUDE_CONFIG_DIR` and for `CODEX_HOME`. It does not work for Gemini
263/// when its optional keychain backend is in use: that backend's service and account names
264/// are global constants which `GEMINI_CLI_HOME` does not namespace, so the "private"
265/// sign-in would write over the live login instead of beside it.
266#[derive(Debug, Clone, PartialEq, Eq)]
267pub enum Isolation {
268 /// A home override fully isolates a sign-in from the live credential.
269 Isolated,
270 /// It does not, and here is what to tell the person.
271 NotIsolated { reason: String },
272}
273
274/// When a login stops working, in epoch seconds. `None` where the tool does not say.
275#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
276pub struct Expiry {
277 /// Until then its usage can be asked without renewing it first.
278 pub access_expires_at: Option<i64>,
279 /// Until then it can be restored at all.
280 pub refresh_expires_at: Option<i64>,
281}
282
283/// Where one tool keeps its live login: the backends it reads, in the order it reads them,
284/// and the name the login is filed under in each.
285///
286/// Every tool pitboard knows keeps its login this way: Claude Code in a keychain item with
287/// a file behind it, Codex in a file or a keychain item depending on its configuration,
288/// Gemini in a file. Handing the switch the store itself, rather than a pair of read and
289/// write methods, is what lets one switch ask the questions a store answers the same way
290/// for every tool: what is there byte for byte, what a write would cost, whether it held.
291pub(crate) struct LiveStore {
292 pub(crate) chain: crate::store::Live,
293 pub(crate) service: String,
294}
295
296/// A store that could not be read, as the provider boundary reports it.
297pub(crate) fn store_error(error: crate::store::Error) -> ProviderError {
298 const STORE: &str = "this machine's credential store";
299 match error {
300 crate::store::Error::Malformed(detail) => ProviderError::Malformed {
301 service: STORE,
302 detail,
303 },
304 other => ProviderError::Network {
305 service: STORE,
306 detail: other.to_string(),
307 },
308 }
309}
310
311/// One coding tool's login, as the rest of pitboard needs to touch it.
312///
313/// Implementations live in `provider::<name>`. Nothing here knows about pitboard's state
314/// file, its lock, its journal or its audit log: those are pitboard's own bookkeeping and
315/// do not vary by tool.
316pub(crate) trait Provider: Send + Sync + std::fmt::Debug {
317 fn id(&self) -> ProviderId;
318
319 /// Where this tool's live login is kept on this machine, right now.
320 ///
321 /// Resolved on every call and never cached: which backend holds the login depends on
322 /// the tool's own configuration and home variables, and either can change between two
323 /// commands. An error means this tool keeps nothing at rest here that pitboard could
324 /// park, which is not the same as nothing being signed in.
325 fn live(&self, ctx: &Context) -> Result<LiveStore, ProviderError>;
326
327 /// The credential this tool would authenticate with right now.
328 ///
329 /// `Ok(None)` means nothing is signed in, which is an answer. A store that could not be
330 /// read is an error and must never collapse into `None`: reading one as the other tells
331 /// somebody their login is gone when it is merely unreadable.
332 fn read_live(&self, ctx: &Context) -> Result<Option<Credential>, ProviderError> {
333 let live = self.live(ctx)?;
334 crate::store::read(&live.chain, &live.service)
335 .map(|found| found.map(|raw| Credential::new(self.id(), raw)))
336 .map_err(store_error)
337 }
338
339 /// Whose credential this is.
340 fn identify(&self, ctx: &Context, credential: &Credential) -> Result<Identity, ProviderError>;
341
342 /// Whose credential this is, confirmed by the service still accepting it.
343 ///
344 /// The same answer as [`Provider::identify`] where that already asks the service, which
345 /// it does for Claude Code. A tool whose login names its own account can say whose it
346 /// is without anybody's agreement, and that is not enough before installing it: a login
347 /// the service has stopped accepting would be switched to, read back, found present,
348 /// and fail the next time the person ran the tool, with nothing parked to go back to.
349 fn verify(&self, ctx: &Context, credential: &Credential) -> Result<Identity, ProviderError> {
350 self.identify(ctx, credential)
351 }
352
353 /// What this credential has left, normalised into pitboard's own shape.
354 ///
355 /// Takes the whole credential and the context, not an access token, because what a
356 /// usage call needs is not the same everywhere: Codex sends an account id header it
357 /// reads out of the credential, and Gemini needs a project id the credential never
358 /// mentions.
359 fn usage(
360 &self,
361 ctx: &Context,
362 credential: &Credential,
363 ) -> Result<usage::Snapshot, ProviderError>;
364
365 /// Fresh tokens for a parked login.
366 ///
367 /// Only ever called on a park. Renewing what is signed in is the tool's own job, and
368 /// racing it there is how a refresh chain gets spent twice.
369 fn renew(&self, ctx: &Context, credential: &Credential) -> Result<Credential, ProviderError>;
370
371 /// A name for where this tool's live login is on this machine right now.
372 ///
373 /// One state file serves every place a tool can keep its login, and a home variable
374 /// changes which one is live, so a record of which account was switched to in one
375 /// says nothing about another. Claude Code's is the keychain item its directory hashes
376 /// to; Codex's is the file its home puts the login in.
377 fn slot(&self, ctx: &Context) -> String;
378
379 /// The lock this tool takes around its own writes to the live login, which pitboard
380 /// must hold too while it writes there. `None` for a tool that takes none, where there
381 /// is nothing to hold and nothing it could wait for.
382 fn write_lock(&self, ctx: &Context) -> Option<std::path::PathBuf>;
383
384 /// Who this tool itself says is signed in, read from its own files without asking
385 /// anybody.
386 ///
387 /// A cache for a tool that keeps one apart from its login, and can lag it; the login's
388 /// own claims for a tool whose login names its account. Good enough to decide which of
389 /// two messages to show and whether an account may be forgotten, never good enough to
390 /// file a login under.
391 fn recorded_identity(&self, ctx: &Context) -> Option<Identity>;
392
393 /// Correct whatever this tool caches about who is signed in, now that `incoming`'s
394 /// login is live in place of `outgoing`'s.
395 ///
396 /// Runs after the login has moved and cannot undo it, so a failure here is reported
397 /// and never rolled back: the tool would otherwise name an account whose login is no
398 /// longer there.
399 fn after_switch(
400 &self,
401 ctx: &Context,
402 incoming: &crate::state::Account,
403 outgoing: &Identity,
404 ) -> Result<(), crate::error::Error>;
405
406 /// The tool's own program, where it is installed. A private sign-in runs it, so its
407 /// absence is worth saying before anybody opens a browser.
408 fn program(&self, ctx: &Context) -> Option<std::path::PathBuf>;
409
410 /// The tool's own sign-in, pointed at `dir` so the live login is never touched.
411 ///
412 /// `dir` exists and is private when this is called, and it is where the tool writes the
413 /// new login: every tool pitboard handles lets a home variable move its whole store,
414 /// which is the only reason a second account can be signed in without signing the first
415 /// one out. Whether that really isolates the live login is
416 /// [`Provider::private_signin_isolation`]'s question, asked first.
417 fn sign_in(&self, ctx: &Context, dir: &std::path::Path) -> std::process::Command;
418
419 /// The login a sign-in left in `dir`, as the tool stored it.
420 fn read_signin(
421 &self,
422 ctx: &Context,
423 dir: &std::path::Path,
424 ) -> Result<Option<String>, crate::store::Error>;
425
426 /// Take away whatever a sign-in into `dir` left outside it. The directory itself is the
427 /// caller's to remove.
428 fn discard_signin(&self, ctx: &Context, dir: &std::path::Path);
429
430 /// Names of whatever on this machine makes the tool sign in with something other than
431 /// the login pitboard moves: an environment variable or a setting holding a key of its
432 /// own. Read from files as well as this process's environment, so the app, which has no
433 /// shell environment at all, gets the same answer as the command line.
434 fn overridden_by(&self, ctx: &Context) -> Vec<String>;
435
436 /// When a running session follows a switch. A fact about the tool, not a setting.
437 fn adoption(&self) -> Adoption;
438
439 /// Whether a park may coexist with the same account still live.
440 fn park_semantics(&self) -> ParkSemantics;
441
442 /// Whether a private sign-in on this machine, right now, is really private.
443 ///
444 /// Takes the context because the answer is not a constant: it depends on which backend
445 /// the tool is configured to use here.
446 fn private_signin_isolation(&self, ctx: &Context) -> Isolation;
447
448 /// The part of a live document that belongs to the account signed in.
449 ///
450 /// For Claude Code that is a slice: its credential document also holds MCP tokens and
451 /// other keys that belong to the machine, and parking those would take them away from
452 /// whoever switches in. For a tool that keeps one account per file it is the whole
453 /// document.
454 fn slice(&self, live: &Value) -> Result<Value, ProviderError>;
455
456 /// `live` with `incoming` in place of whatever account was there, and nothing of the
457 /// outgoing account left behind.
458 fn splice(&self, live: &Value, incoming: &Value) -> Result<Value, ProviderError>;
459
460 /// A short, non-secret handle on the refresh token inside a slice.
461 ///
462 /// Two slices with the same handle hold the same refresh chain. It is what lets an
463 /// interrupted switch work out which side landed without asking anybody.
464 fn fingerprint(&self, slice: &Value) -> String;
465
466 /// When a slice stops being askable and stops being restorable.
467 fn expiry(&self, slice: &Value) -> Expiry;
468}
469
470/// Where a program somebody named is: the path itself, made absolute, when it has a
471/// directory in it, or the first file on `search`, a list in `PATH`'s form, that can be run.
472///
473/// Found the way `execvp` finds one, which passes over a directory of that name and a file
474/// nobody may run, so what is found here is what starts. Only a directory named from the
475/// root is looked in: a relative one names a place relative to wherever pitboard was
476/// started, which says nothing about where a tool is installed, and a sign-in that runs
477/// from a directory of its own would read it as somewhere else again.
478pub(crate) fn find_program(
479 named: &std::path::Path,
480 search: &std::ffi::OsStr,
481) -> Option<std::path::PathBuf> {
482 find_in(named, search, runnable)
483}
484
485/// `find_program` with the question of whether a file can be run handed in, so a test can
486/// see every place it looks.
487fn find_in(
488 named: &std::path::Path,
489 search: &std::ffi::OsStr,
490 mut runnable: impl FnMut(&std::path::Path) -> bool,
491) -> Option<std::path::PathBuf> {
492 if named.components().count() > 1 {
493 let named = std::path::absolute(named).ok()?;
494 return runnable(&named).then_some(named);
495 }
496 std::env::split_paths(search)
497 .filter(|dir| dir.is_absolute())
498 .map(|dir| dir.join(named))
499 .find(|candidate| runnable(candidate))
500}
501
502/// Whether `path` is a file somebody may run.
503fn runnable(path: &std::path::Path) -> bool {
504 use std::os::unix::fs::PermissionsExt;
505 std::fs::metadata(path)
506 .is_ok_and(|found| found.is_file() && found.permissions().mode() & 0o111 != 0)
507}
508
509/// Where `tool`'s own program is, looked for the way the context says to look.
510pub(crate) fn program_of(ctx: &Context, tool: ProviderId) -> Option<std::path::PathBuf> {
511 find_program(ctx.program_for(tool), &ctx.search_path())
512}
513
514/// A command that runs `tool`'s own program, by the path it was found at, with the search
515/// path as its `PATH`, and the program's own directory in front of it when it is not on it
516/// already.
517///
518/// An npm install is a script that starts `#!/usr/bin/env node`, and npm puts it beside the
519/// `node` that installed it, under whatever prefix or version manager that was. So a
520/// program found somewhere the search path does not reach, where an app finds one its
521/// installer put there, finds its interpreter in its own directory, even for an app whose
522/// `PATH` has neither. The directory as found, never the script it links to: npm links
523/// `<prefix>/bin/codex` to a file deep inside `lib/node_modules`, where no `node` is. A
524/// program found on the search path runs with that path as it is, so `env` finds the `node`
525/// the person's own terminal would, and not an older one that happens to sit beside it.
526///
527/// A program that was not found is left to the search path, where starting it fails the
528/// way a missing program does.
529pub(crate) fn command(ctx: &Context, tool: ProviderId) -> std::process::Command {
530 let search = ctx.search_path();
531 let Some(program) = program_of(ctx, tool) else {
532 let mut command = std::process::Command::new(ctx.program_for(tool));
533 command.env("PATH", search);
534 return command;
535 };
536 let mut path = std::ffi::OsString::new();
537 if let Some(dir) = program
538 .parent()
539 .filter(|dir| !std::env::split_paths(&search).any(|entry| entry == *dir))
540 {
541 path.push(dir);
542 if !search.is_empty() {
543 path.push(":");
544 }
545 }
546 path.push(&search);
547 let mut command = std::process::Command::new(program);
548 command.env("PATH", path);
549 command
550}
551
552/// The implementation for one tool.
553///
554/// An exhaustive match rather than a lookup, so a tool added to [`ProviderId`] and not to
555/// here stops compiling instead of being silently absent.
556pub(crate) fn of(provider: ProviderId) -> &'static dyn Provider {
557 match provider {
558 ProviderId::Claude => &claude::engine::Claude,
559 ProviderId::Codex => &codex::engine::Codex,
560 }
561}
562
563#[cfg(test)]
564mod tests {
565 use super::*;
566
567 /// The code is written into a label prefix, the state file, a park's name and the audit
568 /// log. If it ever stopped round-tripping, a state file would load with an account
569 /// nothing could name.
570 #[test]
571 fn every_provider_code_parses_back_to_itself() {
572 for &id in ProviderId::ALL {
573 assert_eq!(ProviderId::parse(id.code()), Some(id), "{id}");
574 assert!(
575 id.code().chars().all(|c| c.is_ascii_lowercase()),
576 "{id} is not a plain lowercase code"
577 );
578 }
579 assert_eq!(ProviderId::parse("nothing"), None);
580 }
581
582 /// `ALL` is what resolving a bare label walks. A provider missing from it would never
583 /// be found and nothing would say so.
584 #[test]
585 fn every_provider_is_in_all() {
586 // Exhaustive by construction: adding a variant without adding it here stops
587 // compiling, which is the point.
588 for &id in ProviderId::ALL {
589 match id {
590 ProviderId::Claude | ProviderId::Codex => {}
591 }
592 }
593 assert_eq!(ProviderId::ALL.len(), 2, "add the new provider to ALL");
594 }
595
596 /// A code is also what serde writes, so the two spellings must not drift.
597 #[test]
598 fn the_code_is_what_serde_writes() {
599 for &id in ProviderId::ALL {
600 let written = serde_json::to_value(id).expect("a provider id serialises");
601 assert_eq!(written, serde_json::json!(id.code()), "{id}");
602 }
603 }
604
605 /// A registry entry pointing at the wrong implementation would be silent: every
606 /// account of that tool would be handled by another tool's rules.
607 #[test]
608 fn every_implementation_agrees_about_which_tool_it_is() {
609 for &id in ProviderId::ALL {
610 assert_eq!(of(id).id(), id, "{id} is registered against another tool");
611 }
612 }
613
614 /// The three facts, asserted against what was measured, so a change to one is a change
615 /// to a test rather than a surprise on somebody's machine.
616 #[test]
617 fn claude_code_follows_a_switch_on_its_own_and_tolerates_a_copy() {
618 let claude = of(ProviderId::Claude);
619 assert_eq!(
620 claude.adoption(),
621 Adoption::PollingWithin(33),
622 "measured: a session serves its credential from a 30 second cache"
623 );
624 assert_eq!(
625 claude.park_semantics(),
626 ParkSemantics::CopyWhileLive,
627 "nothing of Claude Code's revokes for presenting either copy, and the live document holds the machine's other keys"
628 );
629 assert_eq!(
630 claude.private_signin_isolation(&Context::from_env()),
631 Isolation::Isolated,
632 "CLAUDE_CONFIG_DIR picks the keychain item by hashing the directory, and there is no second backend that escapes it"
633 );
634 }
635
636 /// A restart-required provider has no number of seconds to show, and a caller that
637 /// treated one as zero would render "follows in 0 seconds", which is the opposite of
638 /// what is true.
639 #[test]
640 fn a_restart_is_not_a_countdown_of_zero() {
641 let restart = Adoption::RestartRequired { program: "codex" };
642 assert_ne!(restart, Adoption::PollingWithin(0));
643 assert!(matches!(Adoption::PollingWithin(33), Adoption::PollingWithin(s) if s == 33));
644 }
645
646 /// A scratch directory standing in for an npm prefix's `bin`, with an empty file for
647 /// each tool's program that anybody may run. Nothing here is ever run.
648 struct Prefix(std::path::PathBuf);
649
650 impl Prefix {
651 fn new(name: &str) -> Prefix {
652 use std::os::unix::fs::PermissionsExt;
653 let root = std::env::temp_dir().join(format!(
654 "pitboard-search-path-{name}-{}-{:?}",
655 std::process::id(),
656 std::thread::current().id()
657 ));
658 let _ = std::fs::remove_dir_all(&root);
659 let bin = root.join("npm/bin");
660 std::fs::create_dir_all(&bin).expect("a scratch prefix");
661 for &tool in ProviderId::ALL {
662 let program = bin.join(tool.program());
663 std::fs::write(&program, "").expect("a program");
664 std::fs::set_permissions(&program, std::fs::Permissions::from_mode(0o755))
665 .expect("a program that can be run");
666 }
667 Prefix(root)
668 }
669
670 fn bin(&self) -> std::path::PathBuf {
671 self.0.join("npm/bin")
672 }
673
674 /// A directory beside `bin` holding something named for each tool's program that
675 /// cannot be run: a directory of that name, or a file with no execute bit.
676 fn decoys(&self) -> (std::path::PathBuf, std::path::PathBuf) {
677 let (dirs, files) = (self.0.join("dirs"), self.0.join("files"));
678 for &tool in ProviderId::ALL {
679 std::fs::create_dir_all(dirs.join(tool.program())).expect("a directory");
680 std::fs::create_dir_all(&files).expect("a directory");
681 std::fs::write(files.join(tool.program()), "").expect("a file");
682 }
683 (dirs, files)
684 }
685 }
686
687 impl Drop for Prefix {
688 fn drop(&mut self) {
689 let _ = std::fs::remove_dir_all(&self.0);
690 }
691 }
692
693 fn env_of<'a>(command: &'a std::process::Command, name: &str) -> Option<&'a std::ffi::OsStr> {
694 command
695 .get_envs()
696 .find(|(key, _)| *key == name)
697 .and_then(|(_, value)| value)
698 }
699
700 /// A program is looked for where the caller says, not on this process's own `PATH`: an
701 /// app opened from Finder has only the system's directories there.
702 #[test]
703 fn a_program_is_looked_for_on_the_search_path_it_is_given() {
704 let prefix = Prefix::new("find");
705 let search = format!("/nowhere/at/all::{}", prefix.bin().display());
706 let found = find_program(std::path::Path::new("codex"), search.as_ref());
707 assert_eq!(found, Some(prefix.bin().join("codex")));
708 assert_eq!(
709 find_program(std::path::Path::new("ls"), search.as_ref()),
710 None,
711 "ls is on this process's PATH and not on the one given"
712 );
713 }
714
715 /// Only a directory named from the root is looked in. An empty entry and a relative one
716 /// both name somewhere relative to wherever pitboard was started, and a sign-in that
717 /// runs from a directory of its own would start something else from there.
718 #[test]
719 fn only_a_directory_named_from_the_root_is_looked_in() {
720 let mut looked = Vec::new();
721 let found = find_in(
722 std::path::Path::new("codex"),
723 "::bin:./node_modules/.bin:/usr/bin:".as_ref(),
724 |candidate| {
725 looked.push(candidate.to_path_buf());
726 false
727 },
728 );
729 assert_eq!(found, None);
730 assert_eq!(looked, [std::path::PathBuf::from("/usr/bin/codex")]);
731 }
732
733 /// A directory named for the program, or a file of that name nobody may run, is passed
734 /// over the way `execvp` passes over it, so what is found is what a sign-in can start.
735 #[test]
736 fn what_cannot_be_run_is_passed_over() {
737 let prefix = Prefix::new("decoys");
738 let (dirs, files) = prefix.decoys();
739 let search = format!(
740 "{}:{}:{}",
741 dirs.display(),
742 files.display(),
743 prefix.bin().display()
744 );
745 assert_eq!(
746 find_program(std::path::Path::new("codex"), search.as_ref()),
747 Some(prefix.bin().join("codex"))
748 );
749 for decoy in [dirs.join("codex"), files.join("codex")] {
750 assert_eq!(
751 find_program(&decoy, "".as_ref()),
752 None,
753 "{}",
754 decoy.display()
755 );
756 }
757 }
758
759 /// A program named with a directory relative to where pitboard was started is found as
760 /// that place, by its full path, so the sign-in that runs from a directory of its own
761 /// starts the same program.
762 #[test]
763 fn a_program_named_relative_to_here_is_found_by_its_full_path() {
764 let found =
765 find_in(std::path::Path::new("./bin/codex"), "".as_ref(), |_| true).expect("found");
766 assert!(found.is_absolute(), "{}", found.display());
767 assert_eq!(
768 found,
769 std::env::current_dir()
770 .expect("a working directory")
771 .join("bin/codex")
772 );
773 }
774
775 /// Every tool's sign-in runs the program found, by its full path. Found on the search
776 /// path, it runs with that path as it is: its directory is on it already, and putting it
777 /// first would only change which `node` an npm install's `env` finds from the one the
778 /// person's own terminal finds.
779 #[test]
780 fn a_sign_in_runs_the_program_found_with_the_search_path_as_it_is() {
781 let prefix = Prefix::new("sign-in");
782 let search = format!("/nowhere/before:{}", prefix.bin().display());
783 let ctx =
784 Context::new(std::path::PathBuf::from("/nowhere")).with_search_path(search.clone());
785 let dir = std::path::Path::new("/tmp/pitboard-signin-scratch");
786 for &tool in ProviderId::ALL {
787 let command = of(tool).sign_in(&ctx, dir);
788 let program = prefix.bin().join(tool.program());
789 assert_eq!(command.get_program(), program.as_os_str(), "{tool}");
790 assert_eq!(env_of(&command, "PATH"), Some(search.as_ref()), "{tool}");
791 assert_eq!(of(tool).program(&ctx), Some(program), "{tool}");
792 }
793 }
794
795 /// A program named outright where the search path does not reach is run with its own
796 /// directory first on `PATH`, which is how an app that found it where its installer
797 /// puts it starts it: an npm install's script names `node` through `env`, and `node` is
798 /// beside it. Named outright on the search path, it runs with that path as it is.
799 #[test]
800 fn a_program_named_outright_is_run_with_its_own_directory_on_path() {
801 let prefix = Prefix::new("named");
802 let ctx = Context::new(std::path::PathBuf::from("/nowhere"))
803 .with_claude_program(prefix.bin().join("claude"))
804 .with_codex_program(prefix.bin().join("codex"))
805 .with_search_path("/usr/bin:/bin".into());
806 let dir = std::path::Path::new("/tmp/pitboard-signin-scratch");
807 for &tool in ProviderId::ALL {
808 let command = of(tool).sign_in(&ctx, dir);
809 assert_eq!(
810 command.get_program(),
811 prefix.bin().join(tool.program()).as_os_str(),
812 "{tool}"
813 );
814 assert_eq!(
815 env_of(&command, "PATH"),
816 Some(format!("{}:/usr/bin:/bin", prefix.bin().display()).as_ref()),
817 "{tool}"
818 );
819 }
820 let on_it = format!("/usr/bin:{}/", prefix.bin().display());
821 let ctx = ctx.with_search_path(on_it.clone());
822 for &tool in ProviderId::ALL {
823 let command = of(tool).sign_in(&ctx, dir);
824 assert_eq!(env_of(&command, "PATH"), Some(on_it.as_ref()), "{tool}");
825 }
826 }
827
828 /// A program found nowhere is left to the search path, so starting it fails the way a
829 /// missing program does rather than running whatever this process's `PATH` has.
830 #[test]
831 fn a_program_found_nowhere_is_left_to_the_search_path() {
832 let ctx = Context::new(std::path::PathBuf::from("/nowhere"))
833 .with_search_path("/nowhere/at/all".into());
834 let dir = std::path::Path::new("/tmp/pitboard-signin-scratch");
835 for &tool in ProviderId::ALL {
836 let command = of(tool).sign_in(&ctx, dir);
837 assert_eq!(command.get_program(), tool.program(), "{tool}");
838 assert_eq!(
839 env_of(&command, "PATH"),
840 Some("/nowhere/at/all".as_ref()),
841 "{tool}"
842 );
843 assert_eq!(of(tool).program(&ctx), None, "{tool}");
844 }
845 }
846
847 /// Without a search path of its own, a context looks where this process would, which
848 /// is what the command line has always done.
849 #[test]
850 fn the_search_path_is_this_processs_own_path_unless_given() {
851 let ctx = Context::new(std::path::PathBuf::from("/nowhere"));
852 assert_eq!(
853 ctx.search_path(),
854 std::env::var_os("PATH").unwrap_or_default()
855 );
856 assert_eq!(
857 ctx.with_search_path("/opt/tools/bin".into()).search_path(),
858 "/opt/tools/bin"
859 );
860 }
861}