agengo 0.5.3

Orchestrate AI coding agents (Claude Code) to build, verify, review and integrate tasks in isolated Git worktrees
//! `agengo setup`: what this Linux or WSL2 machine still needs before agengo
//! runs with the OS sandbox and the agents it can start. By default it only
//! prints the commands; `--apply` runs the package installation (the one step
//! that needs no login and can be repeated safely). It never runs
//! `wsl --install`, never logs in for you and never edits your shell files.

use crate::{
    driver,
    platform::{self, Environment},
    process,
};
use anyhow::{bail, Context, Result};
use std::{ffi::OsStr, path::Path, process::Command};

/// The packages agengo's sandbox and plan commands rely on, with the program
/// each one provides.
const PACKAGES: &[(&str, &str)] = &[
    ("git", "git"),
    ("bubblewrap", "bwrap"),
    ("socat", "socat"),
    ("python3", "python3"),
];

/// What is known about one agent on this machine.
pub struct AgentState {
    pub name: String,
    pub installed: bool,
    /// Resolves to a Windows program through WSL interop.
    pub windows_program: bool,
}

fn install_hint(name: &str) -> Option<&'static str> {
    match name {
        "claude" => Some("npm install -g @anthropic-ai/claude-code"),
        "codex" => Some("npm install -g @openai/codex"),
        _ => None,
    }
}

fn login_hint(name: &str) -> &'static str {
    match name {
        "claude" => "run `claude`, then `/login`",
        "codex" => "run `codex login` (or `codex login --device-auth` without a browser)",
        _ => "run it once and follow its sign-in",
    }
}

/// The steps for this machine, in order, as text. `missing` are the package
/// names (not programs) that are not installed.
pub fn steps(
    environment: &Environment,
    missing: &[&str],
    has_apt: bool,
    agents: &[AgentState],
) -> Vec<String> {
    let mut out = Vec::new();
    if !missing.is_empty() {
        out.push(if has_apt {
            format!(
                "Install what is missing: `sudo apt-get update && sudo apt-get install -y {}` (`agengo setup --apply` runs it).",
                missing.join(" ")
            )
        } else {
            format!(
                "Install what is missing with your package manager: {}.",
                missing.join(", ")
            )
        });
    }
    let windows: Vec<&AgentState> = agents.iter().filter(|a| a.windows_program).collect();
    if !windows.is_empty() {
        out.push(
            "WSL put your Windows folders on PATH, so some agents are the Windows versions. Install the Linux versions inside WSL and put them first:".into(),
        );
        out.push("  npm config set prefix ~/.npm-global".into());
        for agent in &windows {
            match install_hint(&agent.name) {
                Some(command) => out.push(format!("  {command}   # {}", agent.name)),
                None => out.push(format!(
                    "  # {}: there is no Linux version; it keeps running through Windows, without a Linux sandbox",
                    agent.name
                )),
            }
        }
        out.push(
            "  echo 'export PATH=\"$HOME/.npm-global/bin:$HOME/.local/bin:$PATH\"' >> ~/.bashrc && source ~/.bashrc".into(),
        );
    }
    for agent in agents.iter().filter(|a| a.installed && !a.windows_program) {
        out.push(format!(
            "Log in to {} inside {}: {}.{}",
            agent.name,
            environment.describe(),
            login_hint(&agent.name),
            if matches!(environment, Environment::Wsl2(_)) {
                " This is separate from any login on Windows."
            } else {
                ""
            }
        ));
    }
    if agents.iter().all(|a| !a.installed) {
        out.push("No agent is installed: install Claude Code (`npm install -g @anthropic-ai/claude-code`) or Codex (`npm install -g @openai/codex`), then log in.".into());
    }
    out.push(
        "Then check the result: `agengo doctor`, and `agengo agent check` for each agent you use."
            .into(),
    );
    out
}

pub fn run_setup(repo: &Path, apply: bool) -> Result<()> {
    let environment = platform::detect();
    if !matches!(
        environment,
        Environment::Linux | Environment::Wsl2(_) | Environment::Container
    ) {
        bail!(
            "agengo setup is for Linux and WSL2 (this is {}); on Windows, follow docs/platforms.md to set up WSL2 first",
            environment.describe()
        );
    }
    let found = |program: &str| process::resolve(OsStr::new(program), repo).is_some();
    let missing: Vec<&str> = PACKAGES
        .iter()
        .filter(|(_, program)| !found(program))
        .map(|(package, _)| *package)
        .collect();
    let has_apt = found("apt-get");
    let installed = driver::installed(repo);
    let agents: Vec<AgentState> = driver::known()
        .into_iter()
        .map(|name| {
            let program = driver::program(&name).unwrap_or_else(|| name.clone());
            let path = process::resolve(OsStr::new(&program), repo);
            AgentState {
                installed: installed.contains(&name),
                windows_program: path
                    .as_deref()
                    .is_some_and(|p| platform::is_windows_program_in_wsl(&environment, p)),
                name,
            }
        })
        .collect();
    println!("[SETUP] {} ({})", environment.describe(), repo.display());
    for (number, step) in steps(&environment, &missing, has_apt, &agents)
        .iter()
        .enumerate()
    {
        if step.starts_with(' ') {
            println!("{step}");
        } else {
            println!("{}. {step}", number + 1);
        }
    }
    if apply {
        if missing.is_empty() {
            println!("agengo: nothing to install");
        } else if !has_apt {
            bail!(
                "--apply needs apt-get; install {} with your package manager",
                missing.join(", ")
            );
        } else {
            let sudo = if found("sudo") && !is_root() {
                Some("sudo")
            } else {
                None
            };
            for args in [
                vec!["update"],
                [vec!["install", "-y"], missing.clone()].concat(),
            ] {
                let mut command = match sudo {
                    Some(sudo) => {
                        let mut command = Command::new(sudo);
                        command.arg("apt-get");
                        command
                    }
                    None => Command::new("apt-get"),
                };
                let status = command
                    .args(&args)
                    .status()
                    .context("could not start apt-get")?;
                if !status.success() {
                    bail!("apt-get {} failed", args.join(" "));
                }
            }
        }
    }
    Ok(())
}

fn is_root() -> bool {
    #[cfg(unix)]
    {
        // SAFETY: geteuid has no preconditions and cannot fail.
        unsafe { libc::geteuid() == 0 }
    }
    #[cfg(not(unix))]
    {
        false
    }
}

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

    fn agent(name: &str, installed: bool, windows_program: bool) -> AgentState {
        AgentState {
            name: name.into(),
            installed,
            windows_program,
        }
    }

    #[test]
    fn missing_packages_become_one_apt_command() {
        let steps = steps(
            &Environment::Linux,
            &["bubblewrap", "socat"],
            true,
            &[agent("claude", true, false)],
        );
        assert!(
            steps[0].contains("apt-get install -y bubblewrap socat"),
            "{steps:?}"
        );
        let without = super::steps(
            &Environment::Linux,
            &["socat"],
            false,
            &[agent("claude", true, false)],
        );
        assert!(without[0].contains("package manager") && !without[0].contains("apt-get"));
    }

    #[test]
    fn windows_agents_get_the_linux_install_and_path_fix() {
        let wsl = Environment::Wsl2(None);
        let steps = steps(
            &wsl,
            &[],
            true,
            &[agent("codex", true, true), agent("agy", true, true)],
        );
        let text = steps.join("\n");
        assert!(text.contains("npm install -g @openai/codex"), "{text}");
        assert!(text.contains("no Linux version"), "{text}");
        assert!(text.contains(".npm-global/bin"), "{text}");
        // Windows programs are not asked to log in as Linux ones.
        assert!(!text.contains("Log in to codex"), "{text}");
    }

    #[test]
    fn linux_agents_get_a_login_step_and_the_last_step_is_the_check() {
        let steps = steps(
            &Environment::Wsl2(Some("Ubuntu".into())),
            &[],
            true,
            &[agent("claude", true, false), agent("codex", false, false)],
        );
        assert!(steps
            .iter()
            .any(|s| s.contains("Log in to claude inside WSL2 (Ubuntu)")));
        assert!(!steps.iter().any(|s| s.contains("Log in to codex")));
        assert!(steps.last().unwrap().contains("agengo doctor"));
        let none = super::steps(
            &Environment::Linux,
            &[],
            true,
            &[agent("claude", false, false)],
        );
        assert!(none.iter().any(|s| s.contains("No agent is installed")));
    }
}