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::host::{Host, Os};
14use crate::provider::ProviderId;
15use crate::provider::claude::api::{Anthropic, Api};
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    "CLAUDE_CODE_FORCE_WINDOWS_CREDMAN",
50    "CLAUDE_CODE_GIT_BASH_PATH",
51    "WSL_DISTRO_NAME",
52    "CODEX_HOME",
53    "CODEX_INSTALL_DIR",
54    "NO_COLOR",
55    "XPC_SERVICE_NAME",
56    "SUDO_UID",
57    "USERPROFILE",
58    "USERNAME",
59    "APPDATA",
60    "LOCALAPPDATA",
61    "ProgramData",
62    "SystemRoot",
63    "PATHEXT",
64    "TEMP",
65    "TMP",
66    "OneDrive",
67    "OneDriveCommercial",
68    "OneDriveConsumer",
69];
70
71// Read only by a build for tests: a release lists none and reads none.
72#[cfg(any(test, feature = "test-support"))]
73const READ_BY_BUILDS_FOR_TESTS: &[&str] = &[TEST_CLAUDE_DESKTOP];
74#[cfg(not(any(test, feature = "test-support")))]
75const READ_BY_BUILDS_FOR_TESTS: &[&str] = &[];
76
77#[cfg(any(test, feature = "test-support"))]
78const TEST_CLAUDE_DESKTOP: &str = "PITBOARD_TEST_CLAUDE_DESKTOP";
79
80/// Every variable Pitboard reads from its environment, by name.
81pub(crate) fn variables() -> impl Iterator<Item = &'static str> {
82    READ.iter()
83        .chain(READ_BY_BUILDS_FOR_TESTS.iter())
84        .chain(crate::settings::OVERRIDING_ENV.iter())
85        .chain(crate::proxy::NAMING.iter())
86        .chain(crate::proxy::EXEMPTING.iter())
87        .copied()
88}
89
90/// The variables a process was started with, by name.
91///
92/// The command line has a shell's. An app the system started has launchd's, which name the
93/// home and the login and little else, unless somebody set more with `launchctl setenv`;
94/// whatever is there is read the way the command line reads it.
95#[derive(Clone, Debug, PartialEq, Eq)]
96pub struct Environment {
97    os: Os,
98    variables: HashMap<OsString, (OsString, OsString)>,
99}
100
101impl Default for Environment {
102    fn default() -> Environment {
103        Environment::on(crate::host::OS, std::iter::empty::<(OsString, OsString)>())
104    }
105}
106
107impl Environment {
108    /// This process's own.
109    pub fn of_this_process() -> Environment {
110        std::env::vars_os().collect()
111    }
112
113    pub(crate) fn on<K: Into<OsString>, V: Into<OsString>>(
114        os: Os,
115        pairs: impl IntoIterator<Item = (K, V)>,
116    ) -> Environment {
117        let mut variables = HashMap::new();
118        for (name, value) in pairs {
119            let (name, value) = (name.into(), value.into());
120            let key = os.variable_key(&name);
121            match os {
122                Os::MacOs | Os::Linux => {
123                    variables.insert(key, (name, value));
124                }
125                // RF-B4: Windows hands a program the first of two spellings of a name.
126                Os::Windows => {
127                    variables.entry(key).or_insert((name, value));
128                }
129            }
130        }
131        Environment { os, variables }
132    }
133
134    pub(crate) fn os(&self) -> Os {
135        self.os
136    }
137
138    /// `name`'s value, whatever bytes it holds, as a path may hold any.
139    pub(crate) fn path(&self, name: &str) -> Option<&OsStr> {
140        debug_assert!(
141            variables().any(|read| read == name),
142            "{name} is read but not listed in context::READ, so the tests would take it \
143             from whoever runs them"
144        );
145        self.variables
146            .get(&self.os.variable_key(OsStr::new(name)))
147            .map(|(_, value)| value.as_os_str())
148    }
149
150    /// `name`'s value as text. One that is not UTF-8 reads as unset, as `std::env::var`
151    /// reads it.
152    pub(crate) fn text(&self, name: &str) -> Option<&str> {
153        self.path(name).and_then(OsStr::to_str)
154    }
155
156    // On Windows `all_proxy` may be how `ALL_PROXY` was set.
157    pub(crate) fn spelling(&self, name: &str) -> Option<&OsStr> {
158        self.path(name)?;
159        self.variables
160            .get(&self.os.variable_key(OsStr::new(name)))
161            .map(|(spelled, _)| spelled.as_os_str())
162    }
163
164    /// Whether `name` holds anything: empty reads as unset.
165    pub(crate) fn set(&self, name: &str) -> bool {
166        self.text(name).is_some_and(|v| !v.is_empty())
167    }
168
169    // The folder `name` names, whatever bytes it holds; none where it is unset or empty.
170    pub(crate) fn named_folder(&self, name: &str) -> Option<PathBuf> {
171        self.path(name)
172            .filter(|folder| !folder.is_empty())
173            .map(PathBuf::from)
174    }
175
176    // Set, even empty, it is the person's: `check_absolute` refuses an empty or relative one.
177    pub(crate) fn home(&self) -> PathBuf {
178        self.path(self.os.home_variable())
179            .map(PathBuf::from)
180            .or_else(crate::host::user::home)
181            .unwrap_or_default()
182    }
183
184    // As the environment spells it, any `.`, `..` or trailing separator kept.
185    pub fn pitboard_home(&self) -> PathBuf {
186        self.path("PITBOARD_HOME")
187            .map(PathBuf::from)
188            .unwrap_or_else(|| self.os.default_pitboard_home(&self.home()))
189    }
190
191    /// Every variable, as a program started in this environment is given them.
192    #[cfg_attr(
193        windows,
194        allow(
195            dead_code,
196            reason = "what the login shell is given, and Windows has none (`host::login_path`)"
197        )
198    )]
199    pub(crate) fn iter(&self) -> impl Iterator<Item = (&OsStr, &OsStr)> {
200        self.variables
201            .values()
202            .map(|(name, value)| (name.as_os_str(), value.as_os_str()))
203    }
204}
205
206/// The one folder every home of [`Context::for_unit_test`] names for the test running on
207/// this thread: one per test, since the test harness names each test's thread after the
208/// test, under the temporary directory, and never made by anything here.
209#[cfg(test)]
210fn unit_test_sentinel() -> PathBuf {
211    let thread = std::thread::current();
212    let test = thread.name().map_or_else(
213        || format!("{:?}", thread.id()),
214        |name| {
215            name.chars()
216                .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
217                .collect()
218        },
219    );
220    std::env::temp_dir()
221        .join(format!("pitboard-unit-test-{}", std::process::id()))
222        .join(test)
223}
224
225impl<K: Into<OsString>, V: Into<OsString>> FromIterator<(K, V)> for Environment {
226    fn from_iter<I: IntoIterator<Item = (K, V)>>(pairs: I) -> Environment {
227        Environment::on(crate::host::OS, pairs)
228    }
229}
230
231// Declared in every build, so code behind `cfg!` compiles in a release too.
232#[derive(Debug, Clone)]
233pub struct ScratchClaude {
234    pub data: PathBuf,
235    pub app: PathBuf,
236}
237
238// Through every link, against the home the system names whatever the environment says.
239#[cfg(any(test, feature = "test-support"))]
240pub(crate) fn refuse_a_real_claude(path: &std::path::Path) {
241    use crate::host::user;
242    assert!(
243        !path
244            .components()
245            .any(|part| part == std::path::Component::ParentDir),
246        "a test named {} for Claude through `..`, which may lead anywhere once a folder is made: \
247         give it a folder of its own",
248        path.display()
249    );
250    #[cfg(test)]
251    let fake = testing::guarded_home();
252    #[cfg(not(test))]
253    let fake: Option<PathBuf> = None;
254    let real = match crate::host::OS {
255        Os::MacOs | Os::Linux => {
256            ["Library/Application Support", "Applications/Claude.app"]
257                .into_iter()
258                .any(|below| {
259                    user::lies_in_the_accounts_own(path, below)
260                        || fake
261                            .as_ref()
262                            .is_some_and(|home| crate::host::lies_in(path, &home.join(below)))
263                })
264                || crate::host::lies_in(path, std::path::Path::new("/Applications/Claude.app"))
265        }
266        Os::Windows => {
267            let (mut roaming, mut local) = user::app_data_folders(true);
268            if let Some(home) = &fake {
269                roaming.push(home.join("AppData").join("Roaming"));
270                local.push(home.join("AppData").join("Local"));
271            }
272            crate::host::claude_desktop_on_windows(&roaming, &local)
273                .iter()
274                .any(|place| crate::host::lies_in(path, place))
275        }
276    };
277    assert!(
278        !real,
279        "a test named {} for Claude, which is, holds or lies in where this account's own \
280         Claude Desktop keeps its data or its app: give it a folder of its own",
281        path.display()
282    );
283}
284
285#[cfg(test)]
286pub(crate) mod testing {
287    use std::cell::RefCell;
288    use std::path::{Path, PathBuf};
289
290    thread_local! {
291        static GUARDED: RefCell<Option<PathBuf>> = const { RefCell::new(None) };
292    }
293
294    // While what this returns is kept, the guards on this thread's test refuse `home`'s places
295    // as well as the account's own, so a test of them need name no real place.
296    pub(crate) fn also_guarding(home: &Path) -> AlsoGuarding {
297        GUARDED.with(|guarded| *guarded.borrow_mut() = Some(home.to_path_buf()));
298        AlsoGuarding(())
299    }
300
301    pub(crate) struct AlsoGuarding(());
302
303    impl Drop for AlsoGuarding {
304        fn drop(&mut self) {
305            GUARDED.with(|guarded| guarded.borrow_mut().take());
306        }
307    }
308
309    pub(super) fn guarded_home() -> Option<PathBuf> {
310        GUARDED.with(|guarded| guarded.borrow().clone())
311    }
312}
313
314#[derive(Clone, Debug)]
315pub struct Context {
316    // This build's system, but where a test reads an environment as another's.
317    pub(crate) os: Os,
318    pub(crate) home: PathBuf,
319    pub(crate) pitboard_home: PathBuf,
320    /// `CLAUDE_CONFIG_DIR`, held as it is set, empty included. Claude Code reads an empty
321    /// value as unset for its config file and its credential slot's name, but takes it as
322    /// the empty path for its config dir, which then is whatever folder it runs in, as the
323    /// register's `config_file_location` says. So an empty one is a home that is not a full
324    /// path, and refused as one ([`crate::home::check_absolute`]).
325    pub(crate) claude_config_dir: Option<String>,
326    /// `CLAUDE_SECURESTORAGE_CONFIG_DIR`, which Claude Code reads with `!== undefined`:
327    /// empty is set, and pins the default credential slot.
328    pub(crate) secure_storage_dir: Option<String>,
329    /// `$USER`, which names Claude Code's keychain account once screened by `slot`.
330    pub(crate) user: Option<String>,
331    /// `CLAUDE_CODE_CUSTOM_OAUTH_URL`. Set, it renames both the keychain item and the config
332    /// file Claude Code uses, so Pitboard would be reading and writing the wrong ones.
333    pub(crate) custom_oauth: bool,
334    /// Environment variables this process was started with that make Claude Code use
335    /// something other than the login Pitboard moves. Only half the answer: the rest is in
336    /// files, which [`crate::settings::overrides`] reads and an app can see too.
337    pub(crate) overriding_auth: Vec<String>,
338    /// Whether a login too large for `security -i` may be written the way Claude Code
339    /// writes it: as a command argument, where `ps` can see it for the length of the call.
340    /// On by default, because there is no third way and Claude Code writes the same
341    /// document that way itself on every token refresh.
342    pub(crate) argv_fallback: bool,
343    /// Which front end asked, for the audit log. A change made from the menu bar and one
344    /// typed at a prompt read the same otherwise.
345    pub(crate) caller: String,
346    // each tool's program for a sign-in; a bare name is looked up on the search path
347    pub(crate) programs: std::collections::BTreeMap<ProviderId, PathBuf>,
348    /// Where Anthropic's endpoints are reached instead, for tests; `api` honours loopback only.
349    pub(crate) api_base: Option<String>,
350    /// The proxy the environment names for Pitboard's requests, read as ureq 3.4.2 reads one.
351    /// None in a context made without an environment.
352    pub(crate) proxy: crate::proxy::Proxies,
353    /// The agent this context's requests go out on, made with `proxy` for the first request
354    /// and shared by every copy of the context.
355    pub(crate) agent: crate::api::Agents,
356    /// `CLAUDE_CODE_HOVER_REST`, which switches on Claude Code's successor credential backend.
357    pub(crate) hover_rest: bool,
358    // `CLAUDE_CODE_FORCE_WINDOWS_CREDMAN` as exactly `1`, which turns Claude Code's Credential
359    // Manager store on (`windows_backend_choice`).
360    pub(crate) credential_manager_forced: bool,
361    /// `CODEX_HOME`, which moves everything Codex keeps, including its keyring account.
362    pub(crate) codex_home: Option<String>,
363    // Windows' `FOLDERID_Profile`, where Codex finds its home with `CODEX_HOME` unset.
364    pub(crate) profile: Option<PathBuf>,
365    // Windows' `LOCALAPPDATA`, as the environment gives it.
366    pub(crate) local_app_data: Option<PathBuf>,
367    // The person's Windows SID, which an `icacls` line names and a report hides.
368    pub(crate) sid: Option<String>,
369    // The folders OneDrive syncs on Windows, as its variables name them.
370    pub(crate) one_drive: Vec<PathBuf>,
371    /// The Pitboard the daily renewal schedule runs. `None` is this program, which is right
372    /// for the command line and wrong for an app: the schedule runs `pitboard renew`, so an
373    /// app names the command line it comes with.
374    pub(crate) schedule_program: Option<PathBuf>,
375    /// Where a tool's program is looked for, in `PATH`'s form, and what its sign-in is given
376    /// as `PATH`, behind the program's own directory where that is not on it. `None` is this
377    /// process's own `PATH`: an app opened from Finder has almost nothing on it, so it
378    /// passes the one the person's login shell would have.
379    pub(crate) search_path: Option<OsString>,
380    // Where each tool's installers put its program, which an app also looks in and a command
381    // line leaves to the shell's `PATH`.
382    pub(crate) installer_places: std::collections::BTreeMap<ProviderId, Vec<PathBuf>>,
383    // `PATHEXT`, which orders the names a Windows shell tries for a program.
384    pub(crate) path_ext: Option<OsString>,
385    // `CLAUDE_CODE_GIT_BASH_PATH`, the Git Bash Claude Code looks at first on Windows.
386    pub(crate) git_bash: Option<PathBuf>,
387    // `WSL_DISTRO_NAME` on Linux, set even empty, which WSL gives its programs.
388    pub(crate) wsl_distro: Option<String>,
389    /// The scheduler's job this process runs as, where a test says. `None` is whatever the
390    /// scheduler said when it started this process.
391    pub(crate) scheduled_job: Option<String>,
392    /// Whether this process was started with the marker the schedule's job carries where
393    /// what the system says of the job it started is not to be relied on
394    /// ([`crate::schedule::SCHEDULED_RUN`]), as the front end it was started as read it.
395    pub(crate) marked_as_scheduled: bool,
396    /// Whether this process was started under sudo, which sets `SUDO_UID`. Part of what the
397    /// host answers when the one gate every change passes asks whether this process runs as
398    /// the person themselves.
399    pub(crate) sudo: bool,
400    /// Where the time comes from. The machine's clock in every real context; a test puts
401    /// its own here to reach the judgements that only happen at a particular moment.
402    pub(crate) clock: Arc<dyn Clock>,
403    /// How Claude Code's locks are kept and waited for: as Claude Code does in every real
404    /// context.
405    pub(crate) locks: crate::lock::Locks,
406    /// The machine: its stores, its processes, its scheduler. This build's host in every
407    /// real context.
408    pub(crate) host: Arc<dyn Host>,
409    /// Who answers for Anthropic. The network in every real context.
410    pub(crate) api: Arc<dyn Api>,
411    /// Who answers for OpenAI. The network in every real context.
412    pub(crate) openai: Arc<dyn OpenAi>,
413    /// Who plays each tool's own sign-in in place of its program, where a test or a fixture
414    /// says. `None` in every real context, and in any build without `test-support` there is
415    /// nothing here at all.
416    #[cfg(any(test, feature = "test-support"))]
417    pub(crate) sign_in_script: Option<Arc<dyn crate::switch::SignInScript>>,
418    #[cfg(any(test, feature = "test-support"))]
419    scratch_claude: Option<ScratchClaude>,
420    #[cfg(any(test, feature = "test-support"))]
421    awaited_every: Option<std::time::Duration>,
422    #[cfg(test)]
423    unknown_machine: bool,
424    /// Who plays a warm-up's run in place of the tool's program, where a test or a fixture
425    /// says. `None` in every real context, and in any build without `test-support` there is
426    /// nothing here at all.
427    #[cfg(any(test, feature = "test-support"))]
428    pub(crate) warm_script: Option<Arc<dyn crate::duty::warm::run::WarmScript>>,
429}
430
431fn programs(
432    named: impl Fn(ProviderId, crate::provider::Cli) -> PathBuf,
433) -> std::collections::BTreeMap<ProviderId, PathBuf> {
434    ProviderId::ALL
435        .iter()
436        .filter_map(|&tool| Some((tool, named(tool, tool.cli()?))))
437        .collect()
438}
439
440impl Context {
441    /// Epoch seconds, from this context's clock.
442    pub(crate) fn now(&self) -> i64 {
443        self.clock.now()
444    }
445
446    /// Epoch milliseconds, from this context's clock.
447    pub(crate) fn now_millis(&self) -> i64 {
448        self.clock.now_millis()
449    }
450
451    /// The time zone of this context's clock: the machine's, unless a test says otherwise.
452    pub(crate) fn zone(&self) -> jiff::tz::TimeZone {
453        self.clock.zone()
454    }
455
456    /// The person's home directory, which is where a platform's own scheduler lives.
457    pub(crate) fn home(&self) -> &std::path::Path {
458        &self.home
459    }
460
461    // The one the schedule renews, whatever `PITBOARD_HOME` says.
462    pub(crate) fn default_pitboard_home(&self) -> PathBuf {
463        self.os.default_pitboard_home(&self.home)
464    }
465
466    /// The machine this context reaches.
467    pub(crate) fn host(&self) -> &dyn Host {
468        self.host.as_ref()
469    }
470
471    /// Who this context asks about a login.
472    pub(crate) fn openai(&self) -> &dyn OpenAi {
473        self.openai.as_ref()
474    }
475
476    pub(crate) fn api(&self) -> &dyn Api {
477        self.api.as_ref()
478    }
479
480    #[cfg(any(test, feature = "test-support"))]
481    #[doc(hidden)]
482    pub fn new(home: PathBuf) -> Context {
483        Context {
484            os: crate::host::OS,
485            pitboard_home: crate::host::OS.default_pitboard_home(&home),
486            home,
487            claude_config_dir: None,
488            secure_storage_dir: None,
489            user: None,
490            custom_oauth: false,
491            argv_fallback: true,
492            overriding_auth: Vec::new(),
493            caller: "unknown".into(),
494            programs: programs(|tool, _| PathBuf::from(tool.program())),
495            api_base: None,
496            proxy: crate::proxy::Proxies::default(),
497            agent: crate::api::Agents::default(),
498            hover_rest: false,
499            credential_manager_forced: false,
500            codex_home: None,
501            profile: None,
502            local_app_data: None,
503            sid: None,
504            one_drive: Vec::new(),
505            schedule_program: None,
506            search_path: None,
507            installer_places: std::collections::BTreeMap::new(),
508            path_ext: None,
509            git_bash: None,
510            wsl_distro: None,
511            scheduled_job: None,
512            marked_as_scheduled: false,
513            sudo: false,
514            clock: Arc::new(SystemClock),
515            locks: crate::lock::Locks::CLAUDE_CODE,
516            host: crate::host::current(),
517            api: Arc::new(Anthropic),
518            openai: Arc::new(OpenAiNetwork),
519            #[cfg(any(test, feature = "test-support"))]
520            sign_in_script: None,
521            #[cfg(any(test, feature = "test-support"))]
522            scratch_claude: None,
523            #[cfg(any(test, feature = "test-support"))]
524            awaited_every: None,
525            #[cfg(test)]
526            unknown_machine: false,
527            #[cfg(any(test, feature = "test-support"))]
528            warm_script: None,
529        }
530    }
531
532    /// Where Codex keeps its login. Empty means unset, as Codex reads it.
533    pub fn with_codex_home(mut self, dir: String) -> Context {
534        self.codex_home = Some(dir).filter(|d| !d.is_empty());
535        self
536    }
537
538    pub(crate) fn codex_home(&self) -> Option<&str> {
539        self.codex_home.as_deref()
540    }
541
542    #[cfg(test)]
543    pub(crate) fn with_profile(mut self, profile: PathBuf) -> Context {
544        self.profile = Some(profile);
545        self
546    }
547
548    pub fn with_pitboard_home(mut self, dir: PathBuf) -> Context {
549        self.pitboard_home = dir;
550        self
551    }
552
553    /// Claude Code's config directory, as `CLAUDE_CONFIG_DIR` names it. Empty is kept, as
554    /// Claude Code keeps it: unset for its config file and its credential slot's name, but
555    /// the empty path for its config dir, as the register's `config_file_location` says,
556    /// which is refused as a home that is not a full path.
557    #[cfg(any(test, feature = "test-support"))]
558    #[doc(hidden)]
559    pub fn with_claude_config_dir(mut self, dir: String) -> Context {
560        self.claude_config_dir = Some(dir);
561        self
562    }
563
564    /// Where a sign-in Pitboard ran keeps Claude Code's config, as `CLAUDE_CONFIG_DIR` named
565    /// it for that sign-in, for reading what the sign-in recorded.
566    pub(crate) fn signed_in_at(&self, dir: &std::path::Path) -> Context {
567        let mut ctx = self.clone();
568        ctx.claude_config_dir = Some(dir.to_string_lossy().into_owned());
569        ctx
570    }
571
572    /// Empty is set, and pins the default slot, as Claude Code reads
573    /// `CLAUDE_SECURESTORAGE_CONFIG_DIR`.
574    #[cfg(test)]
575    pub(crate) fn with_secure_storage_dir(mut self, dir: String) -> Context {
576        self.secure_storage_dir = Some(dir);
577        self
578    }
579
580    /// Allows the argument-line write for a login too large for the stdin one.
581    #[cfg(any(test, feature = "test-support"))]
582    #[doc(hidden)]
583    pub fn with_argv_fallback(mut self, allowed: bool) -> Context {
584        self.argv_fallback = allowed;
585        self
586    }
587
588    /// Whether a custom OAuth endpoint is configured, which moves Claude Code's login.
589    pub(crate) fn custom_oauth(&self) -> bool {
590        self.custom_oauth
591    }
592
593    /// The `claude` Pitboard would run to sign someone in.
594    pub fn claude_program(&self) -> &std::path::Path {
595        &self.programs[&ProviderId::Claude]
596    }
597
598    /// Whether the argument-line write is allowed for an oversized login.
599    pub(crate) fn argv_fallback(&self) -> bool {
600        self.argv_fallback
601    }
602
603    /// Environment variables that authenticate Claude Code some other way, if any.
604    pub(crate) fn overriding_auth(&self) -> &[String] {
605        &self.overriding_auth
606    }
607
608    /// Names the front end in the audit log.
609    #[cfg(any(test, feature = "test-support"))]
610    #[doc(hidden)]
611    pub fn with_caller(mut self, caller: String) -> Context {
612        self.caller = caller;
613        self
614    }
615
616    #[cfg(any(test, feature = "test-support"))]
617    #[doc(hidden)]
618    pub fn with_user(mut self, user: String) -> Context {
619        self.user = Some(user);
620        self
621    }
622
623    /// An app started from Finder does not see the shell's `PATH`, so it names `claude` itself.
624    #[cfg(any(test, feature = "test-support"))]
625    #[doc(hidden)]
626    pub fn with_claude_program(mut self, program: PathBuf) -> Context {
627        self.programs.insert(ProviderId::Claude, program);
628        self
629    }
630
631    /// The same for `codex`.
632    #[cfg(any(test, feature = "test-support"))]
633    #[doc(hidden)]
634    pub fn with_codex_program(mut self, program: PathBuf) -> Context {
635        self.programs.insert(ProviderId::Codex, program);
636        self
637    }
638
639    /// The `codex` Pitboard would run to sign someone in.
640    pub fn codex_program(&self) -> &std::path::Path {
641        &self.programs[&ProviderId::Codex]
642    }
643
644    /// An app is not a command line, so it names the one it comes with for the schedule to
645    /// run.
646    #[cfg(any(test, feature = "test-support"))]
647    #[doc(hidden)]
648    pub fn with_schedule_program(mut self, program: PathBuf) -> Context {
649        self.schedule_program = Some(program);
650        self
651    }
652
653    /// The Pitboard the daily renewal schedule is written to run, where one was named.
654    pub fn schedule_program(&self) -> Option<&std::path::Path> {
655        self.schedule_program.as_deref()
656    }
657
658    /// Look for a tool's program on `path`, in `PATH`'s form, rather than on this process's
659    /// own `PATH`. An app opened from Finder has only the system's directories there, so a
660    /// tool installed through a version manager or an npm prefix is found only on the `PATH`
661    /// the person's shell has, and a script it runs finds its interpreter only there.
662    #[cfg(any(test, feature = "test-support"))]
663    #[doc(hidden)]
664    pub fn with_search_path(mut self, path: String) -> Context {
665        self.search_path = Some(path.into());
666        self
667    }
668
669    // How a shell on this context's system spells a program it looks for.
670    pub(crate) fn lookup(&self) -> crate::host::program::Lookup {
671        crate::host::program::Lookup::new(self.os, self.path_ext.as_deref())
672    }
673
674    /// Where a tool's program is looked for: the path given, or this process's `PATH`.
675    pub(crate) fn search_path(&self) -> OsString {
676        self.search_path
677            .clone()
678            .or_else(|| std::env::var_os("PATH"))
679            .unwrap_or_default()
680    }
681
682    /// The scheduler's job this process runs as, where a test has said. The scheduler's own
683    /// word for it, where it has one, is its to read.
684    pub(crate) fn scheduled_job(&self) -> Option<&str> {
685        self.scheduled_job.as_deref()
686    }
687
688    /// Whether this process was started under sudo.
689    pub(crate) fn sudo(&self) -> bool {
690        self.sudo
691    }
692
693    /// Say this process runs as the scheduler's job `label`, which no test does.
694    #[cfg(test)]
695    pub(crate) fn with_scheduled_job(mut self, label: String) -> Context {
696        self.scheduled_job = Some(label);
697        self
698    }
699
700    /// Say this process is a run of the daily renewal schedule, as the marker its job is
701    /// started with says where what the system says of the job it started is not to be
702    /// relied on: the command line does this for `pitboard renew --scheduled`. Such a run
703    /// renews the default home whatever `PITBOARD_HOME` says
704    /// ([`crate::schedule::SCHEDULED_RUN`]).
705    pub fn started_by_the_schedule(mut self) -> Context {
706        self.marked_as_scheduled = true;
707        self
708    }
709
710    /// Whether this process was started with the schedule's marker.
711    pub(crate) fn marked_as_scheduled(&self) -> bool {
712        self.marked_as_scheduled
713    }
714
715    // `given` over this context's own proxy variables, as a job's are given over the system's.
716    pub(crate) fn with_proxy_variables_over(mut self, given: &[(String, String)]) -> Context {
717        let os = self.os;
718        let key = |name: &str| os.variable_key(OsStr::new(name));
719        let own = self
720            .proxy
721            .variables()
722            .iter()
723            .filter(|(name, _)| !given.iter().any(|(over, _)| key(over) == key(name)))
724            .map(|(name, value)| ((*name).to_string(), value.clone()));
725        let env = Environment::on(os, given.iter().cloned().chain(own));
726        self.proxy = crate::proxy::Proxies::read(&env);
727        self.agent = crate::api::Agents::default();
728        self
729    }
730
731    // The program named for this tool, found or not; None for a tool with no program to run.
732    pub fn program_for(&self, tool: ProviderId) -> Option<&std::path::Path> {
733        self.programs.get(&tool).map(PathBuf::as_path)
734    }
735
736    // The Claude a test named; None in a release.
737    pub(crate) fn scratch_claude(&self) -> Option<&ScratchClaude> {
738        #[cfg(any(test, feature = "test-support"))]
739        {
740            self.scratch_claude.as_ref()
741        }
742        #[cfg(not(any(test, feature = "test-support")))]
743        {
744            None
745        }
746    }
747
748    // Refuses before anything there is listed or opened.
749    #[cfg(any(test, feature = "test-support"))]
750    #[doc(hidden)]
751    pub fn with_scratch_claude(mut self, folder: PathBuf) -> Context {
752        assert!(
753            folder.is_absolute(),
754            "a test named its Claude folder {} relative to wherever it runs: name it in full",
755            folder.display()
756        );
757        let scratch = ScratchClaude {
758            data: folder.join("data"),
759            app: folder.join("Claude.app"),
760        };
761        for named in [&folder, &scratch.data, &scratch.app] {
762            refuse_a_real_claude(named);
763        }
764        self.scratch_claude = Some(scratch);
765        self
766    }
767
768    // How often a sign-in waited for asks the process list: a second, unless a test said.
769    pub(crate) fn awaited_every(&self) -> std::time::Duration {
770        #[cfg(any(test, feature = "test-support"))]
771        if let Some(every) = self.awaited_every {
772            return every;
773        }
774        std::time::Duration::from_secs(1)
775    }
776
777    #[cfg(any(test, feature = "test-support"))]
778    #[doc(hidden)]
779    pub fn with_awaited_every(mut self, every: std::time::Duration) -> Context {
780        self.awaited_every = Some(every);
781        self
782    }
783
784    // What every park's manifest names its Mac by; `unknown` where a unit test said so.
785    pub(crate) fn this_machine(&self) -> String {
786        #[cfg(test)]
787        if self.unknown_machine {
788            return crate::state::UNKNOWN_MACHINE.into();
789        }
790        crate::state::machine_id()
791    }
792
793    #[cfg(test)]
794    pub(crate) fn with_unknown_machine(mut self) -> Context {
795        self.unknown_machine = true;
796        self
797    }
798
799    /// The command line's context, from this process's own environment.
800    pub fn from_env() -> Context {
801        Context::for_command_line(&Environment::of_this_process())
802    }
803
804    /// The command line's context, from the environment it was started with: a shell's, so
805    /// each tool's program is looked for on its `PATH` when it runs.
806    pub fn for_command_line(env: &Environment) -> Context {
807        Context::read(env, "cli")
808    }
809
810    /// The command line's context for a unit test: this process's environment, less every
811    /// variable Pitboard reads, so what the person running the tests exported changes
812    /// nothing a test checks. `PITBOARD_NO_ARGV=1` would fail a keychain test, and
813    /// `PITBOARD_CLAUDE` would name the program a test runs.
814    ///
815    /// Every home is this test's sentinel ([`unit_test_sentinel`]): the person's home,
816    /// Pitboard's own directory, Claude Code's config directory and Codex's home. So a test
817    /// that forgets to make a scratch home of its own reads nothing real, and anything it
818    /// writes lands in a folder of its own. Taking the home from the environment, as this
819    /// did, gave every such test the real `~/.pitboard`, `~/.claude` and `~/.codex`.
820    #[cfg(test)]
821    pub(crate) fn for_unit_test() -> Context {
822        let sentinel = unit_test_sentinel().into_os_string();
823        let homes = [
824            "HOME",
825            "USERPROFILE",
826            "PITBOARD_HOME",
827            "CLAUDE_CONFIG_DIR",
828            "CODEX_HOME",
829        ];
830        let kept: Environment = std::env::vars_os()
831            .filter(|(name, _)| !variables().any(|read| name == read))
832            .chain(homes.map(|home| (home.into(), sentinel.clone())))
833            .collect();
834        Context::for_command_line(&kept)
835    }
836
837    /// Everything `env` says, read the same way for every front end; `caller` names the one
838    /// asking, for the audit log.
839    ///
840    /// Each tool's program is the one its own variable names, `PITBOARD_CLAUDE` or
841    /// `PITBOARD_CODEX`, or else its bare name, looked for on `PATH` when it runs. Where
842    /// to look is all a front end adds: an app has no shell's `PATH`, and finds the
843    /// programs before it runs anything.
844    pub(crate) fn read(env: &Environment, caller: &str) -> Context {
845        let home = env.home();
846        let owned = |name: &str| env.text(name).map(str::to_owned);
847        let program = |tool: ProviderId, cli: crate::provider::Cli| {
848            env.path(cli.program_variable)
849                .filter(|named| !named.is_empty())
850                .map_or_else(|| PathBuf::from(tool.program()), PathBuf::from)
851        };
852        let read = Context {
853            os: env.os(),
854            pitboard_home: env.pitboard_home(),
855            home,
856            claude_config_dir: owned("CLAUDE_CONFIG_DIR"),
857            secure_storage_dir: owned("CLAUDE_SECURESTORAGE_CONFIG_DIR"),
858            user: owned(env.os().user_variable()),
859            custom_oauth: env.set("CLAUDE_CODE_CUSTOM_OAUTH_URL"),
860            argv_fallback: env.text("PITBOARD_NO_ARGV") != Some("1"),
861            overriding_auth: crate::settings::OVERRIDING_ENV
862                .iter()
863                .filter(|name| env.set(name))
864                .map(|name| (*name).to_string())
865                .collect(),
866            caller: caller.into(),
867            programs: programs(program),
868            api_base: owned("PITBOARD_API_BASE"),
869            proxy: crate::proxy::Proxies::read(env),
870            agent: crate::api::Agents::default(),
871            hover_rest: matches!(env.text("CLAUDE_CODE_HOVER_REST"), Some("1" | "true")),
872            credential_manager_forced: env.text("CLAUDE_CODE_FORCE_WINDOWS_CREDMAN") == Some("1"),
873            codex_home: owned("CODEX_HOME").filter(|v| !v.is_empty()),
874            profile: (env.os() == Os::Windows)
875                .then(crate::host::user::profile)
876                .flatten(),
877            local_app_data: env
878                .path("LOCALAPPDATA")
879                .filter(|_| env.os() == Os::Windows)
880                .map(PathBuf::from),
881            sid: (env.os() == Os::Windows)
882                .then(crate::host::user::sid)
883                .flatten(),
884            one_drive: ["OneDrive", "OneDriveCommercial", "OneDriveConsumer"]
885                .into_iter()
886                .filter(|_| env.os() == Os::Windows)
887                .filter_map(|name| env.path(name).filter(|folder| !folder.is_empty()))
888                .map(PathBuf::from)
889                .collect(),
890            schedule_program: None,
891            // Unset is nowhere, as it is to the shell: nothing is found on an empty `PATH`.
892            search_path: Some(env.path("PATH").unwrap_or_default().to_os_string()),
893            installer_places: std::collections::BTreeMap::new(),
894            path_ext: env.path("PATHEXT").map(OsStr::to_os_string),
895            git_bash: env
896                .path("CLAUDE_CODE_GIT_BASH_PATH")
897                .filter(|named| env.os() == Os::Windows && !named.is_empty())
898                .map(PathBuf::from),
899            wsl_distro: env
900                .path("WSL_DISTRO_NAME")
901                .filter(|_| env.os() == Os::Linux)
902                .map(|named| named.to_string_lossy().into_owned()),
903            scheduled_job: None,
904            marked_as_scheduled: false,
905            sudo: env.set("SUDO_UID"),
906            clock: Arc::new(SystemClock),
907            locks: crate::lock::Locks::CLAUDE_CODE,
908            host: crate::host::current(),
909            api: Arc::new(Anthropic),
910            openai: Arc::new(OpenAiNetwork),
911            #[cfg(any(test, feature = "test-support"))]
912            sign_in_script: None,
913            #[cfg(any(test, feature = "test-support"))]
914            scratch_claude: None,
915            #[cfg(any(test, feature = "test-support"))]
916            awaited_every: None,
917            #[cfg(test)]
918            unknown_machine: false,
919            #[cfg(any(test, feature = "test-support"))]
920            warm_script: None,
921        };
922        #[cfg(any(test, feature = "test-support"))]
923        if let Some(folder) = env.path(TEST_CLAUDE_DESKTOP).filter(|f| !f.is_empty()) {
924            return read.with_scratch_claude(PathBuf::from(folder));
925        }
926        read
927    }
928
929    /// Answer for every service from a script, where a test can produce a 429 or a
930    /// refusal. One script for all of them, so a test that forgets to script a tool's
931    /// service gets a refusal rather than a request to the real one.
932    #[cfg(any(test, feature = "test-support"))]
933    #[doc(hidden)]
934    pub fn with_scripted_api(mut self, api: Arc<crate::api::scripted::ScriptedApi>) -> Context {
935        self.api = api.clone();
936        self.openai = api;
937        self
938    }
939
940    /// Put the credential stores in memory, where a test can make them fail. Only the
941    /// tests do this, which is why the trait behind it is not public.
942    #[cfg(any(test, feature = "test-support"))]
943    #[doc(hidden)]
944    pub fn with_memory_stores(mut self, memory: Arc<crate::host::memory::MemoryHost>) -> Context {
945        self.host = memory;
946        self
947    }
948
949    /// Read the time from somewhere else. Only the tests do this, which is why it is not
950    /// part of the builder a front end uses.
951    #[cfg(any(test, feature = "test-support"))]
952    #[doc(hidden)]
953    pub fn with_clock(mut self, clock: Arc<dyn Clock>) -> Context {
954        self.clock = clock;
955        self
956    }
957
958    /// Ask for a lock of Claude Code's somebody holds `retries` times more, `every` apart,
959    /// rather than as Claude Code does. Only the tests do this: one that holds a lock lets go
960    /// of it at a moment of its own, not after a while.
961    #[cfg(any(test, feature = "test-support"))]
962    #[doc(hidden)]
963    pub fn with_lock_waiting(mut self, retries: u32, every: std::time::Duration) -> Context {
964        self.locks = crate::lock::Locks {
965            write: self.locks.write.asked(retries, every),
966            refresh: self.locks.refresh.asked(retries, every),
967        };
968        self
969    }
970
971    /// Play each tool's own sign-in with `script` rather than start its program: what the
972    /// tool says, what it reads typed back, and the login it stores where the tool would. A
973    /// test or a fixture that may start no program does this, and nothing else does, which is
974    /// why it is not part of the builder a front end uses.
975    #[cfg(any(test, feature = "test-support"))]
976    #[doc(hidden)]
977    pub fn with_sign_in_script(
978        mut self,
979        script: Arc<dyn crate::switch::enroll::SignInScript>,
980    ) -> Context {
981        self.sign_in_script = Some(script);
982        self
983    }
984
985    /// Who plays each tool's own sign-in, where somebody said.
986    #[cfg(any(test, feature = "test-support"))]
987    pub(crate) fn sign_in_script(&self) -> Option<&Arc<dyn crate::switch::enroll::SignInScript>> {
988        self.sign_in_script.as_ref()
989    }
990
991    /// Play each warm-up's run with `script` rather than start the tool's program. A test or a
992    /// fixture that may start no program does this, and nothing else does.
993    #[cfg(any(test, feature = "test-support"))]
994    #[doc(hidden)]
995    pub fn with_warm_script(
996        mut self,
997        script: Arc<dyn crate::duty::warm::run::WarmScript>,
998    ) -> Context {
999        self.warm_script = Some(script);
1000        self
1001    }
1002
1003    /// Who plays a warm-up's run, where somebody said.
1004    #[cfg(any(test, feature = "test-support"))]
1005    pub(crate) fn warm_script(&self) -> Option<&Arc<dyn crate::duty::warm::run::WarmScript>> {
1006        self.warm_script.as_ref()
1007    }
1008
1009    /// Whether this context reaches no machine but `memory` and no service but `api`. A
1010    /// fixture asks it of the context it made before it puts a login anywhere, so that an
1011    /// edit leaving either out of the builder fails there, rather than writing Claude Code's
1012    /// login to this machine's keychain under the real one's service name, or asking
1013    /// Anthropic.
1014    #[cfg(any(test, feature = "test-support"))]
1015    #[doc(hidden)]
1016    pub fn reaches_only(
1017        &self,
1018        memory: &Arc<crate::host::memory::MemoryHost>,
1019        api: &Arc<crate::api::scripted::ScriptedApi>,
1020    ) -> bool {
1021        std::ptr::addr_eq(Arc::as_ptr(&self.host), Arc::as_ptr(memory))
1022            && std::ptr::addr_eq(Arc::as_ptr(&self.api), Arc::as_ptr(api))
1023            && std::ptr::addr_eq(Arc::as_ptr(&self.openai), Arc::as_ptr(api))
1024    }
1025}
1026
1027#[cfg(test)]
1028mod tests {
1029    use super::*;
1030    use std::path::Path;
1031
1032    #[test]
1033    fn the_test_variable_is_listed_only_in_a_build_for_tests() {
1034        assert!(variables().any(|name| name == "PITBOARD_TEST_CLAUDE_DESKTOP"));
1035        assert!(!READ.contains(&"PITBOARD_TEST_CLAUDE_DESKTOP"));
1036        assert!(Context::for_unit_test().scratch_claude().is_none());
1037        let folder = std::env::temp_dir().join("pitboard-scratch-claude");
1038        let named = folder.to_string_lossy().into_owned();
1039        let env: Environment = [
1040            ("HOME", "/home/x"),
1041            ("PITBOARD_TEST_CLAUDE_DESKTOP", named.as_str()),
1042        ]
1043        .into_iter()
1044        .collect();
1045        let read = Context::for_command_line(&env);
1046        let scratch = read.scratch_claude().expect("named");
1047        assert_eq!(scratch.data, folder.join("data"));
1048        assert_eq!(scratch.app, folder.join("Claude.app"));
1049    }
1050
1051    // It panics before anything there is listed or opened.
1052    #[test]
1053    #[cfg_attr(
1054        windows,
1055        ignore = "Claude Desktop is macOS only: Windows names no Application Support"
1056    )]
1057    fn a_scratch_inside_the_real_application_support_panics() {
1058        let home = {
1059            let _reaching = crate::host::user::testing::reaching_the_real_home();
1060            crate::host::user::home().expect("this account has a home")
1061        };
1062        let support = home.join("Library/Application Support");
1063        let named = |folder: PathBuf| {
1064            std::panic::catch_unwind(move || {
1065                Context::new("/nowhere".into()).with_scratch_claude(folder)
1066            })
1067            .is_err()
1068        };
1069        assert!(named(support.join("pitboard-test-never-made")));
1070        assert!(named(support.clone()));
1071        assert!(named(home.join("Library")), "it holds it");
1072        // The home is linked, since Linux has no `Library` for a link to resolve through.
1073        let link = std::env::temp_dir().join(format!("pitboard-home-link-{}", std::process::id()));
1074        let _ = std::fs::remove_file(&link);
1075        crate::host::fs::testing::link_dir(&home, &link).expect("a link");
1076        let through = named(link.join("Library/Application Support/pitboard-test-never-made"));
1077        let _ = std::fs::remove_file(&link);
1078        assert!(through, "through a link");
1079        assert!(!named(
1080            std::env::temp_dir().join("pitboard-scratch-elsewhere")
1081        ));
1082        let _guarding = testing::also_guarding(&std::env::temp_dir().join("pitboard-fake-home"));
1083        assert!(
1084            named(support.join("pitboard-test-never-made")),
1085            "while a test guards a fake home too"
1086        );
1087    }
1088
1089    #[test]
1090    #[cfg(windows)]
1091    fn a_scratch_in_claude_desktops_windows_folders_panics() {
1092        let named = |folder: PathBuf| {
1093            std::panic::catch_unwind(move || {
1094                Context::new(PathBuf::from(r"C:\nowhere")).with_scratch_claude(folder)
1095            })
1096            .is_err()
1097        };
1098        let (roaming, local) = crate::host::user::app_data_folders(true);
1099        assert!(!roaming.is_empty() && !local.is_empty());
1100        for dir in &roaming {
1101            assert!(named(dir.join("Claude").join("pitboard-test-never-made")));
1102            assert!(named(dir.join("claude-3p")), "in any case");
1103        }
1104        for dir in &local {
1105            assert!(named(dir.join("AnthropicClaude")));
1106        }
1107        assert!(!named(
1108            std::env::temp_dir().join("pitboard-scratch-elsewhere")
1109        ));
1110        let fake = std::env::temp_dir().join("pitboard-fake-profile");
1111        let _guarding = testing::also_guarding(&fake);
1112        let roaming = fake.join("AppData").join("Roaming");
1113        assert!(named(roaming.join("Claude").join("x")), "a fake profile's");
1114    }
1115
1116    // `..` past a folder not made yet is resolved only once something makes that folder.
1117    #[test]
1118    fn a_scratch_named_through_a_folder_not_made_yet_panics() {
1119        let home =
1120            std::env::temp_dir().join(format!("pitboard-scratch-climb-{}", std::process::id()));
1121        let _guarding = testing::also_guarding(&home);
1122        let climbed = std::panic::catch_unwind(|| {
1123            Context::new("/nowhere".into())
1124                .with_scratch_claude(home.join("never-made/../Library/Application Support/x"))
1125        });
1126        assert!(climbed.is_err());
1127    }
1128
1129    // As a helper given the name would write it: from the working directory.
1130    #[test]
1131    fn a_relative_name_lies_where_the_working_directory_puts_it() {
1132        let here = std::env::current_dir().expect("a working directory");
1133        let name = Path::new("pitboard-never-made");
1134        assert!(crate::host::lies_in(name, &here));
1135        assert!(!crate::host::lies_in(name, &here.join("elsewhere")));
1136    }
1137
1138    // A relative name lands wherever the test runs.
1139    #[test]
1140    fn a_relative_scratch_panics() {
1141        let named = std::panic::catch_unwind(|| {
1142            Context::new("/nowhere".into()).with_scratch_claude("pitboard-scratch".into())
1143        });
1144        assert!(named.is_err());
1145    }
1146
1147    #[test]
1148    #[cfg_attr(
1149        windows,
1150        ignore = "Claude Desktop is macOS only: Windows makes no link"
1151    )]
1152    fn a_scratch_whose_data_or_app_links_to_a_real_place_panics() {
1153        let root =
1154            std::env::temp_dir().join(format!("pitboard-scratch-links-{}", std::process::id()));
1155        let _ = std::fs::remove_dir_all(&root);
1156        let home = root.join("home");
1157        let support = home.join("Library/Application Support/Claude");
1158        let app = home.join("Applications/Claude.app");
1159        let other = root.join("other");
1160        for made in [&support, &app, &other] {
1161            std::fs::create_dir_all(made).expect("a folder to link to");
1162        }
1163        let _guarding = testing::also_guarding(&home);
1164        let linked = |scratch: &str, name: &str, to: &Path| {
1165            let scratch = root.join(scratch);
1166            std::fs::create_dir_all(&scratch).expect("a scratch");
1167            crate::host::fs::testing::link_dir(to, &scratch.join(name)).expect("a link");
1168            std::panic::catch_unwind(|| {
1169                Context::new("/nowhere".into()).with_scratch_claude(scratch)
1170            })
1171            .is_err()
1172        };
1173        let data = linked("one", "data", &support);
1174        let claude = linked("two", "Claude.app", &app);
1175        let elsewhere = linked("three", "data", &other);
1176        let not_made = linked("four", "data", &support.join("never-made"));
1177        let not_made_relative = linked(
1178            "five",
1179            "data",
1180            Path::new("../home/Library/Application Support/Claude/never-made"),
1181        );
1182        std::fs::remove_dir_all(&root).expect("the scratch removed");
1183        assert!(data, "data linked into Application Support");
1184        assert!(claude, "Claude.app linked to ~/Applications/Claude.app");
1185        assert!(!elsewhere, "data linked to a folder of the test's own");
1186        assert!(not_made, "data linked to a folder not made yet there");
1187        assert!(not_made_relative, "the same, by a relative link");
1188    }
1189
1190    #[test]
1191    #[cfg_attr(
1192        windows,
1193        ignore = "Claude Desktop is macOS only: Windows has no `/Applications`"
1194    )]
1195    fn a_scratch_of_an_applications_folder_panics() {
1196        let home =
1197            std::env::temp_dir().join(format!("pitboard-scratch-apps-{}", std::process::id()));
1198        let _guarding = testing::also_guarding(&home);
1199        let named = |folder: PathBuf| {
1200            std::panic::catch_unwind(move || {
1201                Context::new("/nowhere".into()).with_scratch_claude(folder)
1202            })
1203            .is_err()
1204        };
1205        assert!(named("/Applications".into()));
1206        assert!(named(home.join("Applications")));
1207        assert!(!named(home.join("Applications/elsewhere")));
1208    }
1209
1210    // /System/Volumes/Data/Users is /Users, and `canonicalize` keeps either name as it is.
1211    #[test]
1212    #[cfg_attr(
1213        not(target_os = "macos"),
1214        ignore = "a firmlink to the Data volume is macOS's own"
1215    )]
1216    fn a_scratch_named_through_the_data_volume_panics() {
1217        let root =
1218            std::env::temp_dir().join(format!("pitboard-scratch-data-{}", std::process::id()));
1219        let _ = std::fs::remove_dir_all(&root);
1220        let support = root.join("home/Library/Application Support/Claude");
1221        let scratch = root.join("scratch");
1222        for made in [&support, &scratch] {
1223            std::fs::create_dir_all(made).expect("a folder of the test's own");
1224        }
1225        let through = |place: &Path| {
1226            let real = std::fs::canonicalize(place).expect("a folder of the test's own");
1227            Path::new("/System/Volumes/Data").join(real.strip_prefix("/").expect("from the root"))
1228        };
1229        crate::host::fs::testing::link_dir(&through(&support), &scratch.join("data"))
1230            .expect("a link");
1231        let _guarding = testing::also_guarding(&root.join("home"));
1232        let named = |folder: PathBuf| {
1233            std::panic::catch_unwind(move || {
1234                Context::new("/nowhere".into()).with_scratch_claude(folder)
1235            })
1236            .is_err()
1237        };
1238        let linked = named(scratch);
1239        let inside = named(through(&support).join("pitboard-test"));
1240        let own = named(through(&root).join("own"));
1241        let applications = named("/System/Volumes/Data/Applications".into());
1242        std::fs::remove_dir_all(&root).expect("the scratch removed");
1243        assert!(
1244            linked,
1245            "data linked into Application Support through the Data volume"
1246        );
1247        assert!(
1248            inside,
1249            "a scratch in Application Support named through the Data volume"
1250        );
1251        assert!(
1252            !own,
1253            "a folder of the test's own named through the Data volume"
1254        );
1255        assert!(applications, "/Applications named through the Data volume");
1256    }
1257
1258    /// An empty `CLAUDE_CONFIG_DIR` is kept, by the builder as by the environment, since
1259    /// Claude Code takes it as the empty path for its config dir; the context is then
1260    /// refused as one whose home is not a full path. It was read as unset, which pointed
1261    /// Pitboard at `~/.claude`, where no Claude Code started with it keeps anything.
1262    #[test]
1263    fn an_explicit_context_reads_claude_codes_settings_the_way_the_environment_does() {
1264        let (home, named) = full_home();
1265        let ctx = Context::new(home.clone())
1266            .with_claude_config_dir(String::new())
1267            .with_secure_storage_dir(String::new());
1268        assert_eq!(
1269            ctx.pitboard_home,
1270            crate::host::OS.default_pitboard_home(&home)
1271        );
1272        assert_eq!(
1273            ctx.claude_config_dir.as_deref(),
1274            Some(""),
1275            "empty is the empty path for the config dir"
1276        );
1277        assert_eq!(
1278            ctx.secure_storage_dir.as_deref(),
1279            Some(""),
1280            "empty is set, and pins the default slot"
1281        );
1282        assert_eq!(ctx.claude_program(), Path::new("claude"));
1283        let env: Environment = [
1284            (crate::host::OS.home_variable(), named.as_str()),
1285            ("CLAUDE_CONFIG_DIR", ""),
1286        ]
1287        .into_iter()
1288        .collect();
1289        let read = Context::for_command_line(&env);
1290        assert_eq!(read.claude_config_dir, ctx.claude_config_dir);
1291        for ctx in [ctx, read] {
1292            assert!(
1293                matches!(
1294                    crate::home::check_absolute(&ctx),
1295                    Err(crate::error::Error::HomeNotAbsolute {
1296                        variable: "CLAUDE_CONFIG_DIR",
1297                        ..
1298                    })
1299                ),
1300                "refused"
1301            );
1302        }
1303    }
1304
1305    /// What a fixture asks of the context it made: whether it reaches nothing but the machine
1306    /// in memory and the scripted services it was given, which leaving out either, or giving
1307    /// another, makes false.
1308    #[test]
1309    fn a_context_says_whether_it_reaches_only_the_machine_and_services_it_was_given() {
1310        use crate::api::scripted::ScriptedApi;
1311        use crate::host::memory::MemoryHost;
1312        let (memory, api) = (MemoryHost::new(), ScriptedApi::new());
1313        let home = PathBuf::from("/home/x");
1314        let both = Context::new(home.clone())
1315            .with_memory_stores(Arc::clone(&memory))
1316            .with_scripted_api(Arc::clone(&api));
1317        assert!(both.reaches_only(&memory, &api));
1318        assert!(
1319            !Context::new(home.clone())
1320                .with_scripted_api(Arc::clone(&api))
1321                .reaches_only(&memory, &api),
1322            "this machine"
1323        );
1324        assert!(
1325            !Context::new(home)
1326                .with_memory_stores(Arc::clone(&memory))
1327                .reaches_only(&memory, &api),
1328            "the network"
1329        );
1330        assert!(
1331            !both.reaches_only(&MemoryHost::new(), &api),
1332            "another machine"
1333        );
1334        assert!(
1335            !both.reaches_only(&memory, &ScriptedApi::new()),
1336            "other services"
1337        );
1338    }
1339
1340    #[test]
1341    fn only_a_front_end_that_names_one_changes_what_the_schedule_runs() {
1342        assert_eq!(Context::for_unit_test().schedule_program(), None);
1343        let ctx = Context::new(PathBuf::from("/Users/x"));
1344        assert_eq!(ctx.schedule_program(), None);
1345        let bundled = PathBuf::from("/Applications/Pitboard.app/Contents/Helpers/pitboard");
1346        assert_eq!(
1347            ctx.with_schedule_program(bundled.clone())
1348                .schedule_program(),
1349            Some(bundled.as_path())
1350        );
1351    }
1352
1353    /// The command line reads the environment it is handed rather than this process's, so
1354    /// every variable can be tried without changing what the tests themselves run in.
1355    #[test]
1356    fn the_command_line_reads_the_environment_it_is_given() {
1357        let (home, named) = full_home();
1358        let env: Environment = [
1359            (crate::host::OS.home_variable(), named.as_str()),
1360            ("PITBOARD_CLAUDE", "/elsewhere/claude"),
1361            ("PITBOARD_CODEX", ""),
1362            ("CLAUDE_CODE_CUSTOM_OAUTH_URL", "https://oauth.example"),
1363            ("ANTHROPIC_API_KEY", "not-a-key"),
1364            ("ANTHROPIC_AUTH_TOKEN", ""),
1365            ("PATH", "/opt/tools/bin:/usr/bin"),
1366        ]
1367        .into_iter()
1368        .collect();
1369        let ctx = Context::for_command_line(&env);
1370        assert_eq!(ctx.claude_program(), Path::new("/elsewhere/claude"));
1371        assert_eq!(
1372            ctx.codex_program(),
1373            Path::new("codex"),
1374            "empty names nothing"
1375        );
1376        assert!(ctx.custom_oauth());
1377        assert_eq!(
1378            ctx.overriding_auth(),
1379            ["ANTHROPIC_API_KEY"],
1380            "empty is unset"
1381        );
1382        assert_eq!(ctx.search_path(), "/opt/tools/bin:/usr/bin");
1383        assert_eq!(
1384            ctx.pitboard_home,
1385            crate::host::OS.default_pitboard_home(&home)
1386        );
1387        assert_eq!(ctx.caller, "cli");
1388        let no_path: Environment = [(crate::host::OS.home_variable(), named.as_str())]
1389            .into_iter()
1390            .collect();
1391        assert_eq!(
1392            Context::for_command_line(&no_path).search_path(),
1393            "",
1394            "no PATH is nowhere, not this process's"
1395        );
1396    }
1397
1398    // RF-B4, run 38418961905: a program gets `Path` alone, and a block holding both spellings
1399    // hands both to a child, whose `var_os` takes the first for either.
1400    #[test]
1401    fn a_windows_environment_has_one_value_per_name_in_any_case_and_the_first_wins() {
1402        let search_path = |os: Os, pairs: &[(&str, &str)]| {
1403            let home = [("HOME", "/home/x"), ("USERPROFILE", "/home/x")];
1404            let env = Environment::on(os, home.iter().chain(pairs).copied());
1405            Context::read(&env, "cli").search_path()
1406        };
1407        let windows = |pairs: &[(&str, &str)]| search_path(Os::Windows, pairs);
1408        assert_eq!(
1409            windows(&[("Path", "C:\\a")]),
1410            "C:\\a",
1411            "as a program gets it"
1412        );
1413        assert_eq!(windows(&[("PATH", "C:\\b")]), "C:\\b");
1414        assert_eq!(windows(&[("Path", "C:\\a"), ("PATH", "C:\\b")]), "C:\\a");
1415        assert_eq!(windows(&[("PATH", "C:\\b"), ("Path", "C:\\a")]), "C:\\b");
1416        for os in [Os::MacOs, Os::Linux] {
1417            assert_eq!(search_path(os, &[("Path", "/a")]), "", "{os:?}");
1418            assert_eq!(search_path(os, &[("Path", "/a"), ("PATH", "/b")]), "/b");
1419        }
1420        let both = Environment::on(Os::Windows, [("Path", "C:\\a"), ("PATH", "C:\\b")]);
1421        let given: Vec<_> = both.iter().collect();
1422        assert_eq!(
1423            given,
1424            [(OsStr::new("Path"), OsStr::new("C:\\a"))],
1425            "a child gets one"
1426        );
1427        assert_eq!(both.text("PATH"), Some("C:\\a"));
1428    }
1429
1430    // Windows names the person in `USERNAME`, and sets no `USER`.
1431    #[test]
1432    fn the_person_is_named_by_the_systems_own_variable() {
1433        let user = |os: Os| {
1434            let pairs = [
1435                ("HOME", "/home/x"),
1436                ("USERPROFILE", "/home/x"),
1437                ("USER", "posix"),
1438                ("username", "windows"),
1439            ];
1440            Context::read(&Environment::on(os, pairs), "cli").user
1441        };
1442        assert_eq!(user(Os::Windows).as_deref(), Some("windows"));
1443        assert_eq!(user(Os::MacOs).as_deref(), Some("posix"));
1444        assert_eq!(user(Os::Linux).as_deref(), Some("posix"));
1445    }
1446
1447    // Git Bash sets `HOME`, which neither tool takes for the home on Windows.
1448    #[test]
1449    fn each_tool_finds_its_home_in_userprofile_on_windows_whatever_home_says() {
1450        let profile = std::env::temp_dir().join("pitboard-profile-tools");
1451        let named = profile.to_string_lossy().into_owned();
1452        let pairs = [("HOME", "/c/Users/x"), ("USERPROFILE", named.as_str())];
1453        let ctx = Context::read(&Environment::on(Os::Windows, pairs), "cli");
1454        assert_eq!(ctx.home, profile);
1455        assert_eq!(
1456            crate::provider::claude::paths::config_dir(&ctx),
1457            profile.join(".claude")
1458        );
1459        assert_eq!(
1460            crate::provider::claude::paths::config_file(&ctx),
1461            profile.join(".claude.json")
1462        );
1463        assert_eq!(
1464            crate::provider::codex::paths::home(&ctx),
1465            profile.join(".codex")
1466        );
1467        assert_eq!(
1468            ctx.pitboard_home,
1469            profile.join("AppData").join("Local").join("Pitboard")
1470        );
1471        let posix = Context::read(&Environment::on(Os::Linux, pairs), "cli");
1472        assert_eq!(posix.home, PathBuf::from("/c/Users/x"));
1473    }
1474
1475    // A full path on every system, which nothing makes.
1476    fn full_home() -> (PathBuf, String) {
1477        let home = std::env::temp_dir().join("pitboard-never-made-home");
1478        let named = home.to_string_lossy().into_owned();
1479        (home, named)
1480    }
1481
1482    /// A variable read without being listed is caught the first time a test reads it, so the
1483    /// list the tests withhold from every command they run cannot fall behind what is read.
1484    #[test]
1485    #[cfg(debug_assertions)]
1486    #[should_panic(expected = "PITBOARD_SOMETHING_NEW is read but not listed")]
1487    fn a_variable_read_without_being_listed_is_caught() {
1488        let _ = Environment::default().path("PITBOARD_SOMETHING_NEW");
1489    }
1490
1491    /// With no `HOME`, the home is the account's own, as the passwd database names it, which
1492    /// is where the app has always looked. The command line took an empty path instead, and
1493    /// so kept its files in `.pitboard` wherever it was run from.
1494    #[test]
1495    fn without_home_the_home_is_the_accounts_own() {
1496        let _real = crate::host::user::testing::reaching_the_real_home();
1497        let own = crate::host::user::home().expect("this account has a home");
1498        let ctx = Context::for_command_line(&Environment::default());
1499        assert_eq!(ctx.home, own);
1500        assert_eq!(
1501            ctx.pitboard_home,
1502            crate::host::OS.default_pitboard_home(&own)
1503        );
1504        let empty: Environment = [(crate::host::OS.home_variable(), "")]
1505            .into_iter()
1506            .collect();
1507        assert_eq!(
1508            Context::for_command_line(&empty).home,
1509            PathBuf::new(),
1510            "set, even empty, it is what the person said"
1511        );
1512    }
1513
1514    /// A unit test's context names one folder for every home, its own, under the temporary
1515    /// directory, and makes nothing there, so a test that forgets to give a scratch home of
1516    /// its own reads none of the real ones and writes only there. It took the person's real
1517    /// home from the passwd database, and every home under it.
1518    #[test]
1519    fn a_unit_tests_homes_are_a_folder_of_its_own_that_nothing_makes() {
1520        let ctx = Context::for_unit_test();
1521        let sentinel = ctx.home.clone();
1522        assert!(
1523            sentinel.starts_with(std::env::temp_dir()),
1524            "{}",
1525            sentinel.display()
1526        );
1527        assert!(!sentinel.exists(), "{}", sentinel.display());
1528        assert_eq!(ctx.pitboard_home, sentinel);
1529        assert_eq!(
1530            crate::provider::claude::paths::config_dir(&ctx),
1531            sentinel,
1532            "Claude Code's"
1533        );
1534        assert_eq!(
1535            crate::provider::codex::paths::home(&ctx),
1536            sentinel,
1537            "Codex's"
1538        );
1539        assert_eq!(Context::for_unit_test().home, sentinel, "the same test's");
1540        let another = std::thread::Builder::new()
1541            .name("another::test".into())
1542            .spawn(|| Context::for_unit_test().home)
1543            .expect("a thread")
1544            .join()
1545            .expect("its context");
1546        assert_ne!(another, sentinel, "another test's");
1547        assert!(another.ends_with("another--test"), "{}", another.display());
1548    }
1549
1550    /// The home and Pitboard directory an app asks of the environment it was started with
1551    /// are the ones the context it is given reads, path for path, so an app that keys records
1552    /// of its own by Pitboard's directory keys them by the core's.
1553    #[test]
1554    fn the_homes_an_app_asks_for_are_the_contexts() {
1555        let _real = crate::host::user::testing::reaching_the_real_home();
1556        let cases: [&[(&str, &str)]; 5] = [
1557            &[],
1558            &[("HOME", "/Users/x")],
1559            &[("HOME", "/Users/x/")],
1560            &[
1561                ("HOME", "/Users/x"),
1562                ("PITBOARD_HOME", "/elsewhere/./pitboard/"),
1563            ],
1564            &[("PITBOARD_HOME", "")],
1565        ];
1566        for pairs in cases {
1567            let env: Environment = pairs.iter().copied().collect();
1568            let ctx = Context::for_command_line(&env);
1569            assert_eq!(env.home(), ctx.home, "{pairs:?}");
1570            assert_eq!(env.pitboard_home(), ctx.pitboard_home, "{pairs:?}");
1571        }
1572        let given: Environment = [("PITBOARD_HOME", "/elsewhere/./pitboard/")]
1573            .into_iter()
1574            .collect();
1575        assert_eq!(
1576            given.pitboard_home().as_os_str(),
1577            "/elsewhere/./pitboard/",
1578            "as the environment gives it"
1579        );
1580    }
1581}