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