Cotton code
179 lines · 6.6 KB · RustRaw
//! THE ONE DECLARED PATH a hosted session — and everything else this host//! runs — gets.//!//! **Why it is declared and not captured.** Until 14 Oct 2026 a session's PATH//! was whatever the person's login shell exported with a list of agent//! directories appended, and the child also inherited this process's own//! environment underneath. Both are accidents: `$SHELL -l` never reads//! `.zshrc`, so a node toolchain from nvm (where `argent`, `codex` and `npx`//! live) was missing from a hosted session while a terminal on the same Mac//! had it, and nothing in the code said which directories a session may rely//! on. Here every directory is an entry with the reason it is there; the PATH//! is exactly these, in this order, and nothing else//! ([`crate::login_env::build`] replaces whatever PATH a shell printed).//!//! **The order is a terminal's.** The Mac's build-policy wrappers come first so//! a session's `cargo`, `swift` and `xcodebuild` keep the Mac's job limits;//! nvm's default node comes before Homebrew's, as it does once `.zshrc` has//! run; the system directories come last.//!//! A directory that does not exist is still listed (an agent installed while//! the host runs is found on the next launch), except the node toolchain,//! which has no path at all until nvm names a default.use std::path::{Path, PathBuf};/// Where an entry's directory is.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum Dir {    /// An absolute directory.    Fixed(&'static str),    /// A directory under the person's home, written without the `~/`.    Home(&'static str),    /// The `bin` of the node version nvm names as its default    /// ([`nvm_default_bin`]).    NvmDefault,}/// One PATH directory and why a hosted session has it.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub struct PathEntry {    pub dir: Dir,    pub why: &'static str,}/// Every directory on a hosted session's PATH, in order.pub const DECLARED_PATH: [PathEntry; 15] = [    PathEntry {        dir: Dir::Home(".cotton-agent/mac-build-policy/bin"),        why: "the Mac's build-policy wrappers for cargo, swift and xcodebuild, first so a \              session's builds keep this Mac's job limits",    },    PathEntry {        dir: Dir::Home(".local/bin"),        why: "where Claude Code's installer puts `claude`",    },    PathEntry {        dir: Dir::NvmDefault,        why: "nvm's default node: `node`, `npx` and every global npm tool installed under it \              (`argent`, `codex`); a login shell never loads nvm, so it is declared here",    },    PathEntry {        dir: Dir::Fixed("/opt/homebrew/bin"),        why: "Homebrew on Apple silicon: git, node, pnpm, gh",    },    PathEntry {        dir: Dir::Fixed("/opt/homebrew/sbin"),        why: "Homebrew's system programs",    },    PathEntry {        dir: Dir::Fixed("/usr/local/bin"),        why: "Homebrew on Intel, and installers that put a program there",    },    PathEntry {        dir: Dir::Home(".npm-global/bin"),        why: "a global npm prefix outside nvm",    },    PathEntry {        dir: Dir::Home("Library/pnpm"),        why: "pnpm's own installer and the tools `pnpm add -g` puts there",    },    PathEntry {        dir: Dir::Home(".cargo/bin"),        why: "rustup and cargo",    },    PathEntry {        dir: Dir::Home(".bun/bin"),        why: "bun and the tools it installs",    },    PathEntry {        dir: Dir::Fixed("/usr/bin"),        why: "the system: git, python3, xcrun, sandbox-exec",    },    PathEntry {        dir: Dir::Fixed("/bin"),        why: "the system shells and core programs",    },    PathEntry {        dir: Dir::Fixed("/usr/sbin"),        why: "the system's administrative programs (sysctl, lsof)",    },    PathEntry {        dir: Dir::Fixed("/sbin"),        why: "the system's low-level programs (mount, ping)",    },    PathEntry {        dir: Dir::Fixed("/Library/Apple/usr/bin"),        why: "programs Apple installs outside the sealed system volume",    },];impl PathEntry {    /// This entry's directory for `home`, or `None` when it has none: a    /// home-relative entry with no home, or nvm with no default.    pub fn resolve(&self, home: &str) -> Option<PathBuf> {        let home = home.trim_end_matches('/');        match self.dir {            Dir::Fixed(dir) => Some(PathBuf::from(dir)),            // With no home there is no `~/.local/bin` — `/.local/bin` is nobody's.            Dir::Home(_) | Dir::NvmDefault if home.is_empty() => None,            Dir::Home(rest) => Some(Path::new(home).join(rest)),            Dir::NvmDefault => nvm_default_bin(Path::new(home)),        }    }}/// The PATH a hosted session gets: [`DECLARED_PATH`] resolved for `home`.pub fn path(home: &str) -> String {    let mut dirs: Vec<String> = Vec::new();    for entry in DECLARED_PATH {        if let Some(dir) = entry.resolve(home) {            let dir = dir.display().to_string();            if !dirs.contains(&dir) {                dirs.push(dir);            }        }    }    dirs.join(":")}/// The `bin` directory of the node version nvm uses by default, the one a/// person's terminal has once `.zshrc` has loaded nvm.////// nvm's own layout, read without running it: `~/.nvm/alias/default` names a/// version (`22`, `v22.23.2`, `node`, `lts/*`), and the newest installed/// `~/.nvm/versions/node/v*` that the name matches is the one. A name that is/// not a version number matches every version, as `node` does. No default, or/// no installed version it matches, is no node toolchain — never a guess.pub fn nvm_default_bin(home: &Path) -> Option<PathBuf> {    let nvm = home.join(".nvm");    let named = std::fs::read_to_string(nvm.join("alias").join("default")).ok()?;    let named = named.trim().trim_start_matches('v');    let wanted: Option<Vec<u64>> = named        .split('.')        .map(|part| part.parse::<u64>().ok())        .collect();    let versions = nvm.join("versions").join("node");    std::fs::read_dir(&versions)        .ok()?        .filter_map(Result::ok)        .filter_map(|entry| {            let name = entry.file_name().to_str()?.to_string();            let parts: Vec<u64> = name                .strip_prefix('v')?                .split('.')                .map(|part| part.parse::<u64>().ok())                .collect::<Option<_>>()?;            let matches = match &wanted {                Some(prefix) => parts.starts_with(prefix),                None => true,            };            matches.then_some((parts, versions.join(&name).join("bin")))        })        .max_by(|a, b| a.0.cmp(&b.0))        .map(|(_, bin)| bin)}#[cfg(test)]#[path = "launch_env_tests.rs"]mod launch_env_tests;