agengo 0.5.4

Orchestrate AI coding agents (Claude Code) to build, verify, review and integrate tasks in isolated Git worktrees
//! Where agengo is running: which environment, how well it is supported and
//! what to tell the user about it (docs/platforms.md). Linux, WSL2 and dev
//! containers are the reference environments; macOS is supported; native
//! Windows is experimental and only ever warned about, never refused.

use std::path::Path;

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Environment {
    Linux,
    /// Linux under WSL2, with the distribution's name when known.
    Wsl2(Option<String>),
    Container,
    MacOs,
    Windows,
    Other(String),
}

impl Environment {
    /// 1 = reference, 2 = supported, 3 = experimental.
    pub fn tier(&self) -> u8 {
        match self {
            Self::Linux | Self::Wsl2(_) | Self::Container => 1,
            Self::MacOs => 2,
            Self::Windows | Self::Other(_) => 3,
        }
    }

    pub fn describe(&self) -> String {
        match self {
            Self::Linux => "Linux".into(),
            Self::Wsl2(Some(distro)) => format!("WSL2 ({distro})"),
            Self::Wsl2(None) => "WSL2".into(),
            Self::Container => "Linux container".into(),
            Self::MacOs => "macOS".into(),
            Self::Windows => "native Windows".into(),
            Self::Other(os) => os.clone(),
        }
    }
}

/// The environment this process runs in.
pub fn detect() -> Environment {
    classify(
        std::env::consts::OS,
        std::env::var("WSL_DISTRO_NAME").ok().as_deref(),
        &std::fs::read_to_string("/proc/version").unwrap_or_default(),
        Path::new("/.dockerenv").exists() || Path::new("/run/.containerenv").exists(),
    )
}

fn classify(
    os: &str,
    wsl_distro: Option<&str>,
    proc_version: &str,
    in_container: bool,
) -> Environment {
    match os {
        "macos" => Environment::MacOs,
        "windows" => Environment::Windows,
        "linux" => {
            // A container on Docker Desktop runs on the WSL2 kernel, so the
            // kernel string alone does not mean a WSL2 distribution.
            let wsl_distro = wsl_distro.filter(|name| !name.is_empty());
            if wsl_distro.is_some() {
                Environment::Wsl2(wsl_distro.map(str::to_owned))
            } else if in_container {
                Environment::Container
            } else if proc_version.to_ascii_lowercase().contains("microsoft") {
                Environment::Wsl2(None)
            } else {
                Environment::Linux
            }
        }
        other => Environment::Other(other.to_owned()),
    }
}

/// Whether the user declared this run to be inside a container that is the
/// boundary (`AGENGO_BOUNDARY=container`, set by the sample dev container).
/// It is never guessed from the presence of a container.
pub fn boundary_is_container() -> bool {
    std::env::var("AGENGO_BOUNDARY").is_ok_and(|value| value == "container")
}

/// Whether `path` is on a Windows drive mounted into WSL (`/mnt/c/...`).
/// Git and builds there are far slower than in the Linux home folder.
pub fn on_windows_mount(path: &Path) -> bool {
    let mut parts = path.components();
    parts.next(); // the root
    let (Some(mnt), Some(drive)) = (parts.next(), parts.next()) else {
        return false;
    };
    mnt.as_os_str() == "mnt"
        && drive
            .as_os_str()
            .to_str()
            .is_some_and(|d| d.len() == 1 && d.chars().all(|c| c.is_ascii_alphabetic()))
}

/// Whether `program`, found at `path`, is a Windows program that WSL2 started
/// through interop: WSL puts the Windows folders on `PATH`, so a `claude`,
/// `codex` or `agy` may be the Windows one, which has its own login and no
/// Linux sandbox.
pub fn is_windows_program_in_wsl(environment: &Environment, path: &Path) -> bool {
    matches!(environment, Environment::Wsl2(_))
        && (on_windows_mount(path)
            || path
                .extension()
                .and_then(|extension| extension.to_str())
                .is_some_and(|extension| {
                    ["exe", "cmd", "bat"]
                        .iter()
                        .any(|known| extension.eq_ignore_ascii_case(known))
                }))
}

/// The warning for such a program, with the fix.
pub fn windows_program_warning(name: &str, path: &Path) -> String {
    format!(
        "{name}: {} is a Windows program started through WSL interop, with its own login and no Linux sandbox. Install the Linux version inside WSL (for example with npm into `~/.npm-global`) and put its folder first in PATH: `export PATH=\"$HOME/.local/bin:$HOME/.npm-global/bin:$PATH\"` in `~/.bashrc`",
        path.display()
    )
}

/// What `agengo doctor` says first: the environment and its support level,
/// plus a warning where it applies.
pub fn doctor_lines(
    environment: &Environment,
    repository: Option<&Path>,
) -> Vec<(super::doctor::Level, String)> {
    use super::doctor::Level;
    let mut out = Vec::new();
    let line = match environment.tier() {
        1 => (
            Level::Ok,
            format!("environment: {} (reference environment)", environment.describe()),
        ),
        2 => (
            Level::Ok,
            format!("environment: {} (supported)", environment.describe()),
        ),
        _ => (
            Level::Warn,
            format!(
                "environment: {} is experimental; Claude Code has no sandbox here and some tools behave differently. Use WSL2 or a dev container; see docs/platforms.md",
                environment.describe()
            ),
        ),
    };
    out.push(line);
    if let (Environment::Wsl2(_), Some(path)) = (environment, repository) {
        if on_windows_mount(path) {
            out.push((
                Level::Warn,
                format!(
                    "repository: {} is on a Windows drive; Git and builds are much slower there. Clone it into your Linux home folder (`~/`) instead",
                    path.display()
                ),
            ));
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn classifies_each_environment() {
        assert_eq!(
            classify("linux", None, "Linux version 6.8 (gcc)", false),
            Environment::Linux
        );
        assert_eq!(
            classify("linux", Some("Ubuntu-24.04"), "", false),
            Environment::Wsl2(Some("Ubuntu-24.04".into()))
        );
        assert_eq!(
            classify(
                "linux",
                None,
                "Linux version 5.15.0-microsoft-standard-WSL2",
                false
            ),
            Environment::Wsl2(None)
        );
        assert_eq!(classify("linux", None, "", true), Environment::Container);
        // Docker Desktop containers report the WSL2 kernel but are containers.
        assert_eq!(
            classify(
                "linux",
                None,
                "Linux version 5.15.0-microsoft-standard-WSL2",
                true
            ),
            Environment::Container
        );
        assert_eq!(classify("macos", None, "", false), Environment::MacOs);
        assert_eq!(classify("windows", None, "", false), Environment::Windows);
        assert!(matches!(
            classify("freebsd", None, "", false),
            Environment::Other(_)
        ));
    }

    #[test]
    fn tiers_follow_the_support_policy() {
        assert_eq!(Environment::Linux.tier(), 1);
        assert_eq!(Environment::Wsl2(None).tier(), 1);
        assert_eq!(Environment::Container.tier(), 1);
        assert_eq!(Environment::MacOs.tier(), 2);
        assert_eq!(Environment::Windows.tier(), 3);
    }

    #[test]
    fn spots_windows_drives_mounted_in_wsl() {
        assert!(on_windows_mount(Path::new("/mnt/c/Users/me/repo")));
        assert!(on_windows_mount(Path::new("/mnt/d")));
        assert!(!on_windows_mount(Path::new("/mnt/wsl/shared")));
        assert!(!on_windows_mount(Path::new("/home/me/repo")));
        assert!(!on_windows_mount(Path::new("/mnt")));
    }

    #[test]
    fn spots_windows_programs_that_wsl_runs_through_interop() {
        let wsl = Environment::Wsl2(None);
        assert!(is_windows_program_in_wsl(
            &wsl,
            Path::new("/mnt/c/Users/me/AppData/Local/agy/bin/agy.exe")
        ));
        assert!(is_windows_program_in_wsl(
            &wsl,
            Path::new("/mnt/c/Users/me/AppData/Roaming/npm/codex")
        ));
        assert!(is_windows_program_in_wsl(
            &wsl,
            Path::new("/somewhere/claude.EXE")
        ));
        assert!(!is_windows_program_in_wsl(
            &wsl,
            Path::new("/home/me/.npm-global/bin/codex")
        ));
        // Only WSL2 has this problem.
        assert!(!is_windows_program_in_wsl(
            &Environment::Linux,
            Path::new("/mnt/c/x/codex")
        ));
        assert!(windows_program_warning("codex", Path::new("/mnt/c/x/codex")).contains("PATH"));
    }

    #[test]
    fn doctor_warns_on_windows_and_on_a_repository_under_a_windows_drive() {
        use crate::doctor::Level;
        let windows = doctor_lines(&Environment::Windows, None);
        assert_eq!(windows[0].0, Level::Warn);
        assert!(windows[0].1.contains("WSL2"));
        let wsl = Environment::Wsl2(None);
        let slow = doctor_lines(&wsl, Some(Path::new("/mnt/c/code/repo")));
        assert_eq!(slow[0].0, Level::Ok);
        assert_eq!(slow[1].0, Level::Warn);
        let fast = doctor_lines(&wsl, Some(Path::new("/home/me/repo")));
        assert_eq!(fast.len(), 1);
        // Outside WSL the mount check does not apply.
        assert_eq!(
            doctor_lines(&Environment::Linux, Some(Path::new("/mnt/c/x"))).len(),
            1
        );
    }
}