Skip to main content

pitboard_core/
context.rs

1//! Everything Pitboard takes from its environment, read in one place. Every front end builds
2//! its `Context` from the variables it was started with, by the same code: the command line
3//! from its own, once. An app passes the ones it was started with, which are not a shell's,
4//! so it also looks for each tool's program itself, in [`crate::app`].
5//!
6//! This module is where the process's environment is read. `clippy.toml` refuses
7//! `std::env::var` and its kind anywhere else, unless an `#[allow]` there says why.
8#![allow(
9    clippy::disallowed_methods,
10    reason = "the one module that reads this process's environment"
11)]
12
13use crate::api::{Anthropic, Api};
14use crate::host::Host;
15use crate::provider::ProviderId;
16use crate::provider::codex::api::{Network as OpenAiNetwork, OpenAi};
17use crate::time::{Clock, SystemClock};
18use std::collections::HashMap;
19use std::ffi::{OsStr, OsString};
20use std::path::PathBuf;
21use std::sync::Arc;
22
23/// Every variable Pitboard reads from the environment it was started with, besides
24/// [`crate::settings::OVERRIDING_ENV`] and the proxy variables, which [`crate::proxy`] lists
25/// in the order ureq tries them: what [`Context::read`] consults, the shell an app
26/// asks for its `PATH`, and the three read straight from the process: `PATH` where a context
27/// was given no search path, and where Linux's host finds the path Pitboard was started by,
28/// `NO_COLOR` by the command line's status line, and `XPC_SERVICE_NAME` by launchd's host.
29/// Each of those reads carries an `#[allow]` saying why it is not made through
30/// [`Environment`].
31///
32/// [`Environment`] refuses, in a build with debug assertions, to read a name missing here,
33/// so every test that reads a context fails until a new variable is added. The tests take
34/// nothing on this list from whoever runs them, except what they pass on by name.
35const READ: &[&str] = &[
36    "HOME",
37    "USER",
38    "PATH",
39    "SHELL",
40    "PITBOARD_HOME",
41    "PITBOARD_NO_ARGV",
42    "PITBOARD_API_BASE",
43    "PITBOARD_CLAUDE",
44    "PITBOARD_CODEX",
45    "CLAUDE_CONFIG_DIR",
46    "CLAUDE_SECURESTORAGE_CONFIG_DIR",
47    "CLAUDE_CODE_CUSTOM_OAUTH_URL",
48    "CLAUDE_CODE_HOVER_REST",
49    "CODEX_HOME",
50    "NO_COLOR",
51    "XPC_SERVICE_NAME",
52    "SUDO_UID",
53];
54
55/// Every variable Pitboard reads from its environment, by name.
56pub(crate) fn variables() -> impl Iterator<Item = &'static str> {
57    READ.iter()
58        .chain(crate::settings::OVERRIDING_ENV.iter())
59        .chain(crate::proxy::NAMING.iter())
60        .chain(crate::proxy::EXEMPTING.iter())
61        .copied()
62}
63
64/// The variables a process was started with, by name.
65///
66/// The command line has a shell's. An app the system started has launchd's, which name the
67/// home and the login and little else, unless somebody set more with `launchctl setenv`;
68/// whatever is there is read the way the command line reads it.
69#[derive(Clone, Debug, Default, PartialEq, Eq)]
70pub struct Environment(HashMap<OsString, OsString>);
71
72impl Environment {
73    /// This process's own.
74    pub fn of_this_process() -> Environment {
75        std::env::vars_os().collect()
76    }
77
78    /// `name`'s value, whatever bytes it holds, as a path may hold any.
79    pub(crate) fn path(&self, name: &str) -> Option<&OsStr> {
80        debug_assert!(
81            variables().any(|read| read == name),
82            "{name} is read but not listed in context::READ, so the tests would take it \
83             from whoever runs them"
84        );
85        self.0.get(OsStr::new(name)).map(OsString::as_os_str)
86    }
87
88    /// `name`'s value as text. One that is not UTF-8 reads as unset, as `std::env::var`
89    /// reads it.
90    pub(crate) fn text(&self, name: &str) -> Option<&str> {
91        self.path(name).and_then(OsStr::to_str)
92    }
93
94    /// Whether `name` holds anything: empty reads as unset.
95    pub(crate) fn set(&self, name: &str) -> bool {
96        self.text(name).is_some_and(|v| !v.is_empty())
97    }
98
99    /// The person's home: `HOME`, or, where it is unset, the account's own, as the passwd
100    /// database names it and Foundation finds it for an app. Set, even empty, it is what the
101    /// person said, and an empty or relative one is refused where it is used
102    /// ([`crate::home::check_absolute`]), never taken to be the folder Pitboard runs in.
103    pub fn home(&self) -> PathBuf {
104        self.path("HOME")
105            .map(PathBuf::from)
106            .or_else(crate::host::user::home)
107            .unwrap_or_default()
108    }
109
110    /// Pitboard's own directory: `PITBOARD_HOME`, or the system's default for
111    /// [`Environment::home`], `.pitboard` there on macOS and Linux. The path as the
112    /// environment gives it, with any `.`, `..` or trailing `/` it holds.
113    pub fn pitboard_home(&self) -> PathBuf {
114        self.path("PITBOARD_HOME")
115            .map(PathBuf::from)
116            .unwrap_or_else(|| crate::host::default_pitboard_home(&self.home()))
117    }
118
119    /// Every variable, as a program started in this environment is given them.
120    #[cfg_attr(
121        windows,
122        allow(
123            dead_code,
124            reason = "what the login shell is given, and Windows has none (`host::login_path`)"
125        )
126    )]
127    pub(crate) fn iter(&self) -> impl Iterator<Item = (&OsStr, &OsStr)> {
128        self.0
129            .iter()
130            .map(|(name, value)| (name.as_os_str(), value.as_os_str()))
131    }
132}
133
134/// The one folder every home of [`Context::for_unit_test`] names for the test running on
135/// this thread: one per test, since the test harness names each test's thread after the
136/// test, under the temporary directory, and never made by anything here.
137#[cfg(test)]
138fn unit_test_sentinel() -> PathBuf {
139    let thread = std::thread::current();
140    let test = thread.name().map_or_else(
141        || format!("{:?}", thread.id()),
142        |name| {
143            name.chars()
144                .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
145                .collect()
146        },
147    );
148    std::env::temp_dir()
149        .join(format!("pitboard-unit-test-{}", std::process::id()))
150        .join(test)
151}
152
153impl<K: Into<OsString>, V: Into<OsString>> FromIterator<(K, V)> for Environment {
154    fn from_iter<I: IntoIterator<Item = (K, V)>>(pairs: I) -> Environment {
155        Environment(
156            pairs
157                .into_iter()
158                .map(|(name, value)| (name.into(), value.into()))
159                .collect(),
160        )
161    }
162}
163
164#[derive(Clone, Debug)]
165pub struct Context {
166    pub(crate) home: PathBuf,
167    pub(crate) pitboard_home: PathBuf,
168    /// `CLAUDE_CONFIG_DIR`, held as it is set, empty included. Claude Code reads an empty
169    /// value as unset for its config file and its credential slot's name, but takes it as
170    /// the empty path for its config dir, which then is whatever folder it runs in, as the
171    /// register's `config_file_location` says. So an empty one is a home that is not a full
172    /// path, and refused as one ([`crate::home::check_absolute`]).
173    pub(crate) claude_config_dir: Option<String>,
174    /// `CLAUDE_SECURESTORAGE_CONFIG_DIR`, which Claude Code reads with `!== undefined`:
175    /// empty is set, and pins the default credential slot.
176    pub(crate) secure_storage_dir: Option<String>,
177    /// `$USER`, which names Claude Code's keychain account once screened by `slot`.
178    pub(crate) user: Option<String>,
179    /// `CLAUDE_CODE_CUSTOM_OAUTH_URL`. Set, it renames both the keychain item and the config
180    /// file Claude Code uses, so Pitboard would be reading and writing the wrong ones.
181    pub(crate) custom_oauth: bool,
182    /// Environment variables this process was started with that make Claude Code use
183    /// something other than the login Pitboard moves. Only half the answer: the rest is in
184    /// files, which [`crate::settings::overrides`] reads and an app can see too.
185    pub(crate) overriding_auth: Vec<String>,
186    /// Whether a login too large for `security -i` may be written the way Claude Code
187    /// writes it: as a command argument, where `ps` can see it for the length of the call.
188    /// On by default, because there is no third way and Claude Code writes the same
189    /// document that way itself on every token refresh.
190    pub(crate) argv_fallback: bool,
191    /// Which front end asked, for the audit log. A change made from the menu bar and one
192    /// typed at a prompt read the same otherwise.
193    pub(crate) caller: String,
194    /// The `claude` that runs a sign-in; a bare name is looked up on the search path.
195    pub(crate) claude_program: PathBuf,
196    /// Where Anthropic's endpoints are reached instead, for tests; `api` honours loopback only.
197    pub(crate) api_base: Option<String>,
198    /// The proxy the environment names for Pitboard's requests, read as ureq 3.4.2 reads one.
199    /// None in a context made without an environment.
200    pub(crate) proxy: crate::proxy::Proxies,
201    /// The agent this context's requests go out on, made with `proxy` for the first request
202    /// and shared by every copy of the context.
203    pub(crate) agent: crate::api::Agents,
204    /// `CLAUDE_CODE_HOVER_REST`, which switches on Claude Code's successor credential backend.
205    pub(crate) hover_rest: bool,
206    /// `CODEX_HOME`, which moves everything Codex keeps, including its keyring account.
207    pub(crate) codex_home: Option<String>,
208    /// The `codex` that runs a sign-in; a bare name is looked up on the search path.
209    pub(crate) codex_program: PathBuf,
210    /// The Pitboard the daily renewal schedule runs. `None` is this program, which is right
211    /// for the command line and wrong for an app: the schedule runs `pitboard renew`, so an
212    /// app names the command line it comes with.
213    pub(crate) schedule_program: Option<PathBuf>,
214    /// Where a tool's program is looked for, in `PATH`'s form, and what its sign-in is given
215    /// as `PATH`, behind the program's own directory where that is not on it. `None` is this
216    /// process's own `PATH`: an app opened from Finder has almost nothing on it, so it
217    /// passes the one the person's login shell would have.
218    pub(crate) search_path: Option<std::ffi::OsString>,
219    /// The scheduler's job this process runs as, where a test says. `None` is whatever the
220    /// scheduler said when it started this process.
221    pub(crate) scheduled_job: Option<String>,
222    /// Whether this process was started with the marker the schedule's job carries where
223    /// what the system says of the job it started is not to be relied on
224    /// ([`crate::schedule::SCHEDULED_RUN`]), as the front end it was started as read it.
225    pub(crate) marked_as_scheduled: bool,
226    /// Whether this process was started under sudo, which sets `SUDO_UID`. Part of what the
227    /// host answers when the one gate every change passes asks whether this process runs as
228    /// the person themselves.
229    pub(crate) sudo: bool,
230    /// Where the time comes from. The machine's clock in every real context; a test puts
231    /// its own here to reach the judgements that only happen at a particular moment.
232    pub(crate) clock: Arc<dyn Clock>,
233    /// The machine: its stores, its processes, its scheduler. This build's host in every
234    /// real context.
235    pub(crate) host: Arc<dyn Host>,
236    /// Who answers for Anthropic. The network in every real context.
237    pub(crate) api: Arc<dyn Api>,
238    /// Who answers for OpenAI. The network in every real context.
239    pub(crate) openai: Arc<dyn OpenAi>,
240    /// Who plays each tool's own sign-in in place of its program, where a test or a fixture
241    /// says. `None` in every real context, and in any build without `test-support` there is
242    /// nothing here at all.
243    #[cfg(any(test, feature = "test-support"))]
244    pub(crate) sign_in_script: Option<Arc<dyn crate::switch::SignInScript>>,
245}
246
247impl Context {
248    /// Epoch seconds, from this context's clock.
249    pub(crate) fn now(&self) -> i64 {
250        self.clock.now()
251    }
252
253    /// Epoch milliseconds, from this context's clock.
254    pub(crate) fn now_millis(&self) -> i64 {
255        self.clock.now_millis()
256    }
257
258    /// The person's home directory, which is where a platform's own scheduler lives.
259    pub(crate) fn home(&self) -> &std::path::Path {
260        &self.home
261    }
262
263    /// The machine this context reaches.
264    pub(crate) fn host(&self) -> &dyn Host {
265        self.host.as_ref()
266    }
267
268    /// Who this context asks about a login.
269    pub(crate) fn openai(&self) -> &dyn OpenAi {
270        self.openai.as_ref()
271    }
272
273    pub(crate) fn api(&self) -> &dyn Api {
274        self.api.as_ref()
275    }
276
277    /// Claude Code's defaults for a person whose home is `home`: `~/.pitboard`, `~/.claude`,
278    /// the default credential slot, `claude` looked up on `PATH`, and no proxy. An app starts
279    /// here and sets only what differs. Pitboard's own directory is the system's default for
280    /// `home`, the home handed in and never this account's own.
281    pub fn new(home: PathBuf) -> Context {
282        Context {
283            pitboard_home: crate::host::default_pitboard_home(&home),
284            home,
285            claude_config_dir: None,
286            secure_storage_dir: None,
287            user: None,
288            custom_oauth: false,
289            argv_fallback: true,
290            overriding_auth: Vec::new(),
291            caller: "unknown".into(),
292            claude_program: PathBuf::from("claude"),
293            api_base: None,
294            proxy: crate::proxy::Proxies::default(),
295            agent: crate::api::Agents::default(),
296            hover_rest: false,
297            codex_home: None,
298            codex_program: PathBuf::from("codex"),
299            schedule_program: None,
300            search_path: None,
301            scheduled_job: None,
302            marked_as_scheduled: false,
303            sudo: false,
304            clock: Arc::new(SystemClock),
305            host: crate::host::current(),
306            api: Arc::new(Anthropic),
307            openai: Arc::new(OpenAiNetwork),
308            #[cfg(any(test, feature = "test-support"))]
309            sign_in_script: None,
310        }
311    }
312
313    /// Where Codex keeps its login. Empty means unset, as Codex reads it.
314    pub fn with_codex_home(mut self, dir: String) -> Context {
315        self.codex_home = Some(dir).filter(|d| !d.is_empty());
316        self
317    }
318
319    pub(crate) fn codex_home(&self) -> Option<&str> {
320        self.codex_home.as_deref()
321    }
322
323    pub fn with_pitboard_home(mut self, dir: PathBuf) -> Context {
324        self.pitboard_home = dir;
325        self
326    }
327
328    /// Claude Code's config directory, as `CLAUDE_CONFIG_DIR` names it. Empty is kept, as
329    /// Claude Code keeps it: unset for its config file and its credential slot's name, but
330    /// the empty path for its config dir, as the register's `config_file_location` says,
331    /// which is refused as a home that is not a full path.
332    pub fn with_claude_config_dir(mut self, dir: String) -> Context {
333        self.claude_config_dir = Some(dir);
334        self
335    }
336
337    /// Empty is set, and pins the default slot, as Claude Code reads
338    /// `CLAUDE_SECURESTORAGE_CONFIG_DIR`.
339    pub fn with_secure_storage_dir(mut self, dir: String) -> Context {
340        self.secure_storage_dir = Some(dir);
341        self
342    }
343
344    /// The login name whose keychain account Claude Code stores under.
345    /// Allows the argument-line write for a login too large for the stdin one.
346    pub fn with_argv_fallback(mut self, allowed: bool) -> Context {
347        self.argv_fallback = allowed;
348        self
349    }
350
351    /// Whether a custom OAuth endpoint is configured, which moves Claude Code's login.
352    pub fn custom_oauth(&self) -> bool {
353        self.custom_oauth
354    }
355
356    /// The `claude` Pitboard would run to sign someone in.
357    pub fn claude_program(&self) -> &std::path::Path {
358        &self.claude_program
359    }
360
361    /// Whether the argument-line write is allowed for an oversized login.
362    pub fn argv_fallback(&self) -> bool {
363        self.argv_fallback
364    }
365
366    /// Environment variables that authenticate Claude Code some other way, if any.
367    pub fn overriding_auth(&self) -> &[String] {
368        &self.overriding_auth
369    }
370
371    /// Names the front end in the audit log.
372    pub fn with_caller(mut self, caller: String) -> Context {
373        self.caller = caller;
374        self
375    }
376
377    pub fn with_user(mut self, user: String) -> Context {
378        self.user = Some(user);
379        self
380    }
381
382    /// An app started from Finder does not see the shell's `PATH`, so it names `claude` itself.
383    pub fn with_claude_program(mut self, program: PathBuf) -> Context {
384        self.claude_program = program;
385        self
386    }
387
388    /// The same for `codex`.
389    pub fn with_codex_program(mut self, program: PathBuf) -> Context {
390        self.codex_program = program;
391        self
392    }
393
394    /// The `codex` Pitboard would run to sign someone in.
395    pub fn codex_program(&self) -> &std::path::Path {
396        &self.codex_program
397    }
398
399    /// An app is not a command line, so it names the one it comes with for the schedule to
400    /// run.
401    pub fn with_schedule_program(mut self, program: PathBuf) -> Context {
402        self.schedule_program = Some(program);
403        self
404    }
405
406    /// The Pitboard the daily renewal schedule is written to run, where one was named.
407    pub fn schedule_program(&self) -> Option<&std::path::Path> {
408        self.schedule_program.as_deref()
409    }
410
411    /// Look for a tool's program on `path`, in `PATH`'s form, rather than on this process's
412    /// own `PATH`. An app opened from Finder has only the system's directories there, so a
413    /// tool installed through a version manager or an npm prefix is found only on the `PATH`
414    /// the person's shell has, and a script it runs finds its interpreter only there.
415    pub fn with_search_path(mut self, path: String) -> Context {
416        self.search_path = Some(path.into());
417        self
418    }
419
420    /// Where a tool's program is looked for: the path given, or this process's `PATH`.
421    pub(crate) fn search_path(&self) -> std::ffi::OsString {
422        self.search_path
423            .clone()
424            .or_else(|| std::env::var_os("PATH"))
425            .unwrap_or_default()
426    }
427
428    /// The scheduler's job this process runs as, where a test has said. The scheduler's own
429    /// word for it, where it has one, is its to read.
430    pub(crate) fn scheduled_job(&self) -> Option<&str> {
431        self.scheduled_job.as_deref()
432    }
433
434    /// Whether this process was started under sudo.
435    pub(crate) fn sudo(&self) -> bool {
436        self.sudo
437    }
438
439    /// Say this process runs as the scheduler's job `label`, which no test does.
440    #[cfg(test)]
441    pub(crate) fn with_scheduled_job(mut self, label: String) -> Context {
442        self.scheduled_job = Some(label);
443        self
444    }
445
446    /// Say this process is a run of the daily renewal schedule, as the marker its job is
447    /// started with says where what the system says of the job it started is not to be
448    /// relied on: the command line does this for `pitboard renew --scheduled`. Such a run
449    /// renews the default home whatever `PITBOARD_HOME` says
450    /// ([`crate::schedule::SCHEDULED_RUN`]).
451    pub fn started_by_the_schedule(mut self) -> Context {
452        self.marked_as_scheduled = true;
453        self
454    }
455
456    /// Whether this process was started with the schedule's marker.
457    pub(crate) fn marked_as_scheduled(&self) -> bool {
458        self.marked_as_scheduled
459    }
460
461    /// The program named for this tool, found or not.
462    pub fn program_for(&self, tool: ProviderId) -> &std::path::Path {
463        match tool {
464            ProviderId::Claude => &self.claude_program,
465            ProviderId::Codex => &self.codex_program,
466        }
467    }
468
469    /// Run `program` for this tool, where an app found it.
470    pub(crate) fn set_program(&mut self, tool: ProviderId, program: PathBuf) {
471        match tool {
472            ProviderId::Claude => self.claude_program = program,
473            ProviderId::Codex => self.codex_program = program,
474        }
475    }
476
477    /// The command line's context, from this process's own environment.
478    pub fn from_env() -> Context {
479        Context::for_command_line(&Environment::of_this_process())
480    }
481
482    /// The command line's context, from the environment it was started with: a shell's, so
483    /// each tool's program is looked for on its `PATH` when it runs.
484    pub fn for_command_line(env: &Environment) -> Context {
485        Context::read(env, "cli")
486    }
487
488    /// The command line's context for a unit test: this process's environment, less every
489    /// variable Pitboard reads, so what the person running the tests exported changes
490    /// nothing a test checks. `PITBOARD_NO_ARGV=1` would fail a keychain test, and
491    /// `PITBOARD_CLAUDE` would name the program a test runs.
492    ///
493    /// Every home is this test's sentinel ([`unit_test_sentinel`]): the person's home,
494    /// Pitboard's own directory, Claude Code's config directory and Codex's home. So a test
495    /// that forgets to make a scratch home of its own reads nothing real, and anything it
496    /// writes lands in a folder of its own. Taking the home from the environment, as this
497    /// did, gave every such test the real `~/.pitboard`, `~/.claude` and `~/.codex`.
498    #[cfg(test)]
499    pub(crate) fn for_unit_test() -> Context {
500        let sentinel = unit_test_sentinel().into_os_string();
501        let homes = ["HOME", "PITBOARD_HOME", "CLAUDE_CONFIG_DIR", "CODEX_HOME"];
502        let kept: Environment = std::env::vars_os()
503            .filter(|(name, _)| !variables().any(|read| name == read))
504            .chain(homes.map(|home| (home.into(), sentinel.clone())))
505            .collect();
506        Context::for_command_line(&kept)
507    }
508
509    /// Everything `env` says, read the same way for every front end; `caller` names the one
510    /// asking, for the audit log.
511    ///
512    /// Each tool's program is the one its own variable names, `PITBOARD_CLAUDE` or
513    /// `PITBOARD_CODEX`, or else its bare name, looked for on `PATH` when it runs. Where
514    /// to look is all a front end adds: an app has no shell's `PATH`, and finds the
515    /// programs before it runs anything.
516    pub(crate) fn read(env: &Environment, caller: &str) -> Context {
517        let home = env.home();
518        let owned = |name: &str| env.text(name).map(str::to_owned);
519        let program = |tool: ProviderId| {
520            env.path(tool.program_variable())
521                .filter(|named| !named.is_empty())
522                .map_or_else(|| PathBuf::from(tool.program()), PathBuf::from)
523        };
524        Context {
525            pitboard_home: env.pitboard_home(),
526            home,
527            claude_config_dir: owned("CLAUDE_CONFIG_DIR"),
528            secure_storage_dir: owned("CLAUDE_SECURESTORAGE_CONFIG_DIR"),
529            user: owned("USER"),
530            custom_oauth: env.set("CLAUDE_CODE_CUSTOM_OAUTH_URL"),
531            argv_fallback: env.text("PITBOARD_NO_ARGV") != Some("1"),
532            overriding_auth: crate::settings::OVERRIDING_ENV
533                .iter()
534                .filter(|name| env.set(name))
535                .map(|name| (*name).to_string())
536                .collect(),
537            caller: caller.into(),
538            claude_program: program(ProviderId::Claude),
539            api_base: owned("PITBOARD_API_BASE"),
540            proxy: crate::proxy::Proxies::read(env),
541            agent: crate::api::Agents::default(),
542            hover_rest: matches!(env.text("CLAUDE_CODE_HOVER_REST"), Some("1" | "true")),
543            codex_home: owned("CODEX_HOME").filter(|v| !v.is_empty()),
544            codex_program: program(ProviderId::Codex),
545            schedule_program: None,
546            // Unset is nowhere, as it is to the shell: nothing is found on an empty `PATH`.
547            search_path: Some(env.path("PATH").unwrap_or_default().to_os_string()),
548            scheduled_job: None,
549            marked_as_scheduled: false,
550            sudo: env.set("SUDO_UID"),
551            clock: Arc::new(SystemClock),
552            host: crate::host::current(),
553            api: Arc::new(Anthropic),
554            openai: Arc::new(OpenAiNetwork),
555            #[cfg(any(test, feature = "test-support"))]
556            sign_in_script: None,
557        }
558    }
559
560    /// Answer for every service from a script, where a test can produce a 429 or a
561    /// refusal. One script for all of them, so a test that forgets to script a tool's
562    /// service gets a refusal rather than a request to the real one.
563    #[cfg(any(test, feature = "test-support"))]
564    #[doc(hidden)]
565    pub fn with_scripted_api(mut self, api: Arc<crate::api::scripted::ScriptedApi>) -> Context {
566        self.api = api.clone();
567        self.openai = api;
568        self
569    }
570
571    /// Put the credential stores in memory, where a test can make them fail. Only the
572    /// tests do this, which is why the trait behind it is not public.
573    #[cfg(any(test, feature = "test-support"))]
574    #[doc(hidden)]
575    pub fn with_memory_stores(mut self, memory: Arc<crate::host::memory::MemoryHost>) -> Context {
576        self.host = memory;
577        self
578    }
579
580    /// Read the time from somewhere else. Only the tests do this, which is why it is not
581    /// part of the builder a front end uses.
582    #[cfg(any(test, feature = "test-support"))]
583    #[doc(hidden)]
584    pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Context {
585        self.clock = clock;
586        self
587    }
588
589    /// Play each tool's own sign-in with `script` rather than start its program: what the
590    /// tool says, what it reads typed back, and the login it stores where the tool would. A
591    /// test or a fixture that may start no program does this, and nothing else does, which is
592    /// why it is not part of the builder a front end uses.
593    #[cfg(any(test, feature = "test-support"))]
594    #[doc(hidden)]
595    pub fn with_sign_in_script(mut self, script: Arc<dyn crate::switch::SignInScript>) -> Context {
596        self.sign_in_script = Some(script);
597        self
598    }
599
600    /// Who plays each tool's own sign-in, where somebody said.
601    #[cfg(any(test, feature = "test-support"))]
602    pub(crate) fn sign_in_script(&self) -> Option<&Arc<dyn crate::switch::SignInScript>> {
603        self.sign_in_script.as_ref()
604    }
605
606    /// Whether this context reaches no machine but `memory` and no service but `api`. A
607    /// fixture asks it of the context it made before it puts a login anywhere, so that an
608    /// edit leaving either out of the builder fails there, rather than writing Claude Code's
609    /// login to this machine's keychain under the real one's service name, or asking
610    /// Anthropic.
611    #[cfg(any(test, feature = "test-support"))]
612    #[doc(hidden)]
613    pub fn reaches_only(
614        &self,
615        memory: &Arc<crate::host::memory::MemoryHost>,
616        api: &Arc<crate::api::scripted::ScriptedApi>,
617    ) -> bool {
618        std::ptr::addr_eq(Arc::as_ptr(&self.host), Arc::as_ptr(memory))
619            && std::ptr::addr_eq(Arc::as_ptr(&self.api), Arc::as_ptr(api))
620            && std::ptr::addr_eq(Arc::as_ptr(&self.openai), Arc::as_ptr(api))
621    }
622}
623
624#[cfg(test)]
625mod tests {
626    use super::*;
627    use std::path::Path;
628
629    /// An empty `CLAUDE_CONFIG_DIR` is kept, by the builder as by the environment, since
630    /// Claude Code takes it as the empty path for its config dir; the context is then
631    /// refused as one whose home is not a full path. It was read as unset, which pointed
632    /// Pitboard at `~/.claude`, where no Claude Code started with it keeps anything.
633    #[test]
634    fn an_explicit_context_reads_claude_codes_settings_the_way_the_environment_does() {
635        let ctx = Context::new(PathBuf::from("/home/x"))
636            .with_claude_config_dir(String::new())
637            .with_secure_storage_dir(String::new());
638        assert_eq!(ctx.pitboard_home, PathBuf::from("/home/x/.pitboard"));
639        assert_eq!(
640            ctx.claude_config_dir.as_deref(),
641            Some(""),
642            "empty is the empty path for the config dir"
643        );
644        assert_eq!(
645            ctx.secure_storage_dir.as_deref(),
646            Some(""),
647            "empty is set, and pins the default slot"
648        );
649        assert_eq!(ctx.claude_program, PathBuf::from("claude"));
650        let env: Environment = [("HOME", "/home/x"), ("CLAUDE_CONFIG_DIR", "")]
651            .into_iter()
652            .collect();
653        let read = Context::for_command_line(&env);
654        assert_eq!(read.claude_config_dir, ctx.claude_config_dir);
655        for ctx in [ctx, read] {
656            assert!(
657                matches!(
658                    crate::home::check_absolute(&ctx),
659                    Err(crate::error::Error::HomeNotAbsolute {
660                        variable: "CLAUDE_CONFIG_DIR",
661                        ..
662                    })
663                ),
664                "refused"
665            );
666        }
667    }
668
669    /// What a fixture asks of the context it made: whether it reaches nothing but the machine
670    /// in memory and the scripted services it was given, which leaving out either, or giving
671    /// another, makes false.
672    #[test]
673    fn a_context_says_whether_it_reaches_only_the_machine_and_services_it_was_given() {
674        use crate::api::scripted::ScriptedApi;
675        use crate::host::memory::MemoryHost;
676        let (memory, api) = (MemoryHost::new(), ScriptedApi::new());
677        let home = PathBuf::from("/home/x");
678        let both = Context::new(home.clone())
679            .with_memory_stores(Arc::clone(&memory))
680            .with_scripted_api(Arc::clone(&api));
681        assert!(both.reaches_only(&memory, &api));
682        assert!(
683            !Context::new(home.clone())
684                .with_scripted_api(Arc::clone(&api))
685                .reaches_only(&memory, &api),
686            "this machine"
687        );
688        assert!(
689            !Context::new(home)
690                .with_memory_stores(Arc::clone(&memory))
691                .reaches_only(&memory, &api),
692            "the network"
693        );
694        assert!(
695            !both.reaches_only(&MemoryHost::new(), &api),
696            "another machine"
697        );
698        assert!(
699            !both.reaches_only(&memory, &ScriptedApi::new()),
700            "other services"
701        );
702    }
703
704    #[test]
705    fn only_a_front_end_that_names_one_changes_what_the_schedule_runs() {
706        assert_eq!(Context::for_unit_test().schedule_program(), None);
707        let ctx = Context::new(PathBuf::from("/Users/x"));
708        assert_eq!(ctx.schedule_program(), None);
709        let bundled = PathBuf::from("/Applications/Pitboard.app/Contents/Helpers/pitboard");
710        assert_eq!(
711            ctx.with_schedule_program(bundled.clone())
712                .schedule_program(),
713            Some(bundled.as_path())
714        );
715    }
716
717    /// The command line reads the environment it is handed rather than this process's, so
718    /// every variable can be tried without changing what the tests themselves run in.
719    #[test]
720    fn the_command_line_reads_the_environment_it_is_given() {
721        let env: Environment = [
722            ("HOME", "/Users/x"),
723            ("PITBOARD_CLAUDE", "/elsewhere/claude"),
724            ("PITBOARD_CODEX", ""),
725            ("CLAUDE_CODE_CUSTOM_OAUTH_URL", "https://oauth.example"),
726            ("ANTHROPIC_API_KEY", "not-a-key"),
727            ("ANTHROPIC_AUTH_TOKEN", ""),
728            ("PATH", "/opt/tools/bin:/usr/bin"),
729        ]
730        .into_iter()
731        .collect();
732        let ctx = Context::for_command_line(&env);
733        assert_eq!(ctx.claude_program(), Path::new("/elsewhere/claude"));
734        assert_eq!(
735            ctx.codex_program(),
736            Path::new("codex"),
737            "empty names nothing"
738        );
739        assert!(ctx.custom_oauth());
740        assert_eq!(
741            ctx.overriding_auth(),
742            ["ANTHROPIC_API_KEY"],
743            "empty is unset"
744        );
745        assert_eq!(ctx.search_path(), "/opt/tools/bin:/usr/bin");
746        assert_eq!(ctx.pitboard_home, PathBuf::from("/Users/x/.pitboard"));
747        assert_eq!(ctx.caller, "cli");
748        let no_path: Environment = [("HOME", "/Users/x")].into_iter().collect();
749        assert_eq!(
750            Context::for_command_line(&no_path).search_path(),
751            "",
752            "no PATH is nowhere, not this process's"
753        );
754    }
755
756    /// A variable read without being listed is caught the first time a test reads it, so the
757    /// list the tests withhold from every command they run cannot fall behind what is read.
758    #[test]
759    #[cfg(debug_assertions)]
760    #[should_panic(expected = "PITBOARD_SOMETHING_NEW is read but not listed")]
761    fn a_variable_read_without_being_listed_is_caught() {
762        let _ = Environment::default().path("PITBOARD_SOMETHING_NEW");
763    }
764
765    /// With no `HOME`, the home is the account's own, as the passwd database names it, which
766    /// is where the app has always looked. The command line took an empty path instead, and
767    /// so kept its files in `.pitboard` wherever it was run from.
768    #[test]
769    fn without_home_the_home_is_the_accounts_own() {
770        let _real = crate::host::user::testing::reaching_the_real_home();
771        let own = crate::host::user::home().expect("this account has a home");
772        let ctx = Context::for_command_line(&Environment::default());
773        assert_eq!(ctx.home, own);
774        assert_eq!(ctx.pitboard_home, own.join(".pitboard"));
775        let empty: Environment = [("HOME", "")].into_iter().collect();
776        assert_eq!(
777            Context::for_command_line(&empty).home,
778            PathBuf::new(),
779            "set, even empty, it is what the person said"
780        );
781    }
782
783    /// A unit test's context names one folder for every home, its own, under the temporary
784    /// directory, and makes nothing there, so a test that forgets to give a scratch home of
785    /// its own reads none of the real ones and writes only there. It took the person's real
786    /// home from the passwd database, and every home under it.
787    #[test]
788    fn a_unit_tests_homes_are_a_folder_of_its_own_that_nothing_makes() {
789        let ctx = Context::for_unit_test();
790        let sentinel = ctx.home.clone();
791        assert!(
792            sentinel.starts_with(std::env::temp_dir()),
793            "{}",
794            sentinel.display()
795        );
796        assert!(!sentinel.exists(), "{}", sentinel.display());
797        assert_eq!(ctx.pitboard_home, sentinel);
798        assert_eq!(
799            crate::provider::claude::paths::config_dir(&ctx),
800            sentinel,
801            "Claude Code's"
802        );
803        assert_eq!(
804            crate::provider::codex::paths::home(&ctx),
805            sentinel,
806            "Codex's"
807        );
808        assert_eq!(Context::for_unit_test().home, sentinel, "the same test's");
809        let another = std::thread::Builder::new()
810            .name("another::test".into())
811            .spawn(|| Context::for_unit_test().home)
812            .expect("a thread")
813            .join()
814            .expect("its context");
815        assert_ne!(another, sentinel, "another test's");
816        assert!(another.ends_with("another--test"), "{}", another.display());
817    }
818
819    /// The home and Pitboard directory an app asks of the environment it was started with
820    /// are the ones the context it is given reads, path for path, so an app that keys records
821    /// of its own by Pitboard's directory keys them by the core's.
822    #[test]
823    fn the_homes_an_app_asks_for_are_the_contexts() {
824        let _real = crate::host::user::testing::reaching_the_real_home();
825        let cases: [&[(&str, &str)]; 5] = [
826            &[],
827            &[("HOME", "/Users/x")],
828            &[("HOME", "/Users/x/")],
829            &[
830                ("HOME", "/Users/x"),
831                ("PITBOARD_HOME", "/elsewhere/./pitboard/"),
832            ],
833            &[("PITBOARD_HOME", "")],
834        ];
835        for pairs in cases {
836            let env: Environment = pairs.iter().copied().collect();
837            let ctx = Context::for_command_line(&env);
838            assert_eq!(env.home(), ctx.home, "{pairs:?}");
839            assert_eq!(env.pitboard_home(), ctx.pitboard_home, "{pairs:?}");
840        }
841        let given: Environment = [("PITBOARD_HOME", "/elsewhere/./pitboard/")]
842            .into_iter()
843            .collect();
844        assert_eq!(
845            given.pitboard_home().as_os_str(),
846            "/elsewhere/./pitboard/",
847            "as the environment gives it"
848        );
849    }
850}