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