rho-coding-agent 3.13.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
//! Installation evidence shared by update and uninstall. Policy stays with callers.
use std::{
    ffi::OsString,
    io,
    path::{Path, PathBuf},
    process::{Command, Output},
};

#[path = "installation_mise.rs"]
mod mise;
pub(crate) use mise::mise_tool;
use mise::{mise_install_path, mise_installs_roots};

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ScoopInstallScope {
    User,
    Global,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum ManagedInstallation {
    Cargo {
        root: Option<PathBuf>,
    },
    /// `install_path` is mise's `<installs>/<tool>/<version>` directory holding the binary.
    Mise {
        install_path: PathBuf,
    },
    Pacman,
    /// An RPM package, updated through dnf.
    Dnf,
    Scoop(ScoopInstallScope),
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum InstallHint {
    Cargo,
    Pacman,
    Dnf,
    Scoop(ScoopInstallScope),
    Script,
    Unknown,
}

pub(crate) fn install_hint(value: &str) -> InstallHint {
    match value.trim().to_ascii_lowercase().as_str() {
        "cargo" => InstallHint::Cargo,
        "pacman" => InstallHint::Pacman,
        "dnf" => InstallHint::Dnf,
        "scoop" => InstallHint::Scoop(ScoopInstallScope::User),
        "scoop-global" | "scoop_global" => InstallHint::Scoop(ScoopInstallScope::Global),
        "script" | "install-script" => InstallHint::Script,
        _ => InstallHint::Unknown,
    }
}

/// What installation evidence asks of its surroundings: the variables that
/// place mise and Scoop, and the tools it runs (`cargo`, `mise`, `pacman`,
/// `rpm`). `rho update` and uninstall ask this process's own
/// ([`ThisProcess`]); the daemon's update asks the user's login's, which
/// a daemon started without a login shell lacks (`update::unattended`).
pub(crate) trait Probe {
    /// The variable `name`, if set.
    fn var(&self, name: &str) -> Option<OsString>;
    /// Runs `command` to its end, nothing on its stdin, its output captured.
    fn output(&self, command: Command) -> io::Result<Output>;
}

/// This process's environment, and its tools run as it would run them.
pub(crate) struct ThisProcess;

impl Probe for ThisProcess {
    fn var(&self, name: &str) -> Option<OsString> {
        std::env::var_os(name)
    }

    fn output(&self, mut command: Command) -> io::Result<Output> {
        command.output()
    }
}

pub(crate) struct InstallationEvidence {
    pub managed: Option<ManagedInstallation>,
    /// A Cargo receipt without confirmed ownership cannot authorize deletion.
    /// Update may still use its script fallback when Cargo cannot identify Rho.
    pub cargo_metadata: bool,
    /// Even an unrecognized pacman or RPM package owns its executable, not uninstall.
    pub system_package_owned: bool,
}

/// A system package database that can own an executable.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum SystemPackageManager {
    Pacman,
    Rpm,
}

/// The package a system package database names as an executable's owner.
#[derive(Clone, Debug, PartialEq, Eq)]
struct SystemPackageOwner {
    manager: SystemPackageManager,
    /// Owning package names, one per line when several packages own the path.
    package: String,
}

#[derive(Default)]
struct ScoopRoots {
    user: Option<String>,
    global: Option<String>,
}

impl ScoopRoots {
    fn of_environment() -> Self {
        Self::of(&ThisProcess)
    }

    /// The roots `probe`'s variables name; one that is not UTF-8 names none.
    fn of(probe: &impl Probe) -> Self {
        let var = |name| probe.var(name).and_then(|value| value.into_string().ok());
        Self {
            user: var("SCOOP"),
            global: var("SCOOP_GLOBAL"),
        }
    }
}

/// The Scoop install `path` belongs to, if any. Unlike [`detect`], this asks
/// no package manager, so it is cheap enough to call before every daemon
/// start.
pub(crate) fn scoop_install_scope(path: &Path) -> Option<ScoopInstallScope> {
    scoop_install_scope_for_path(path, &ScoopRoots::of_environment())
}

/// The Scoop scope rho is installed in, for a daemon that runs from its
/// own copy and so cannot tell from its path: the global one only when rho
/// is installed there and not for the user, as `scoop update -g` needs an
/// administrator; the user's otherwise, also when neither has it.
pub(crate) fn installed_scoop_scope() -> ScoopInstallScope {
    let roots = ScoopRoots::of_environment();
    let user = roots
        .user
        .map(PathBuf::from)
        .or_else(|| Some(crate::paths::home_dir()?.join("scoop")));
    let global = roots
        .global
        .map(PathBuf::from)
        .or_else(|| Some(PathBuf::from(std::env::var_os("ProgramData")?).join("scoop")));
    installed_scoop_scope_in(user.as_deref(), global.as_deref())
}

/// [`installed_scoop_scope`] with the user's and the global Scoop root.
fn installed_scoop_scope_in(user: Option<&Path>, global: Option<&Path>) -> ScoopInstallScope {
    let has_rho = |root: Option<&Path>| {
        root.is_some_and(|root| root.join("apps").join("rho").join("current").exists())
    };
    if has_rho(global) && !has_rho(user) {
        ScoopInstallScope::Global
    } else {
        ScoopInstallScope::User
    }
}

pub(crate) fn detect(path: &Path) -> InstallationEvidence {
    detect_in(path, &ThisProcess)
}

/// [`detect`], asking `probe` what it asks.
pub(crate) fn detect_in(path: &Path, probe: &impl Probe) -> InstallationEvidence {
    let cargo_metadata = cargo_root_from_bin_path(path).is_some_and(|root| {
        root.join(".crates.toml").exists() || root.join(".crates2.json").exists()
    });
    let mut system_package_owned = false;
    let managed = detect_with(
        path,
        &mise_installs_roots(|name| probe.var(name)),
        &ScoopRoots::of(probe),
        |root| cargo_install_root_contains_crate(root, probe),
        |path| {
            let owner = system_package_owner(path, probe);
            system_package_owned = owner.is_some();
            owner
        },
    );
    InstallationEvidence {
        managed,
        cargo_metadata,
        system_package_owned,
    }
}

fn detect_with(
    path: &Path,
    mise_roots: &[PathBuf],
    scoop_roots: &ScoopRoots,
    cargo_owns: impl FnOnce(&Path) -> bool,
    system_package_owner: impl FnOnce(&Path) -> Option<SystemPackageOwner>,
) -> Option<ManagedInstallation> {
    // Before Cargo: mise's cargo backend installs into `<version>/bin/rho`
    // with a Cargo receipt, but mise owns that directory.
    if let Some(install_path) = mise_install_path(path, mise_roots) {
        return Some(ManagedInstallation::Mise { install_path });
    }
    if is_cargo_bin_path(path) {
        return Some(ManagedInstallation::Cargo {
            root: cargo_root_from_bin_path(path),
        });
    }
    if let Some(root) = cargo_update_root_for_exe(path, cargo_owns) {
        return Some(ManagedInstallation::Cargo { root: Some(root) });
    }
    // pacman matches loosely so AUR variants (`-git`, `-bin`) count; the only
    // RPM is mjiang-extras' own, so match its exact name.
    let system_managed = system_package_owner(path).and_then(|owner| match owner.manager {
        SystemPackageManager::Pacman if owner.package.contains("rho") => {
            Some(ManagedInstallation::Pacman)
        }
        SystemPackageManager::Rpm
            if owner.package.lines().any(|name| name == "rho-coding-agent") =>
        {
            Some(ManagedInstallation::Dnf)
        }
        SystemPackageManager::Pacman | SystemPackageManager::Rpm => None,
    });
    if system_managed.is_some() {
        return system_managed;
    }
    scoop_install_scope_for_path(path, scoop_roots).map(ManagedInstallation::Scoop)
}

pub(crate) fn cargo_update_root_for_exe(
    path: &Path,
    cargo_root_contains_crate: impl FnOnce(&Path) -> bool,
) -> Option<PathBuf> {
    if is_cargo_bin_path(path) {
        return None;
    }
    let root = cargo_root_from_bin_path(path)?;
    cargo_root_contains_crate(&root).then_some(root)
}

fn is_cargo_bin_path(path: &Path) -> bool {
    path.to_string_lossy()
        .replace('\\', "/")
        .contains("/.cargo/bin/")
}

pub(crate) fn cargo_root_from_bin_path(path: &Path) -> Option<PathBuf> {
    let bin_dir = path.parent()?;
    (bin_dir.file_name()? == "bin").then(|| bin_dir.parent().map(Path::to_path_buf))?
}

/// Whether Cargo lists rho installed under `root`, as `probe` runs it.
pub(crate) fn cargo_install_root_contains_crate(root: &Path, probe: &impl Probe) -> bool {
    let mut command = Command::new("cargo");
    command.args(["install", "--list", "--root"]).arg(root);
    probe
        .output(command)
        .ok()
        .filter(|output| output.status.success())
        .and_then(|output| String::from_utf8(output.stdout).ok())
        .is_some_and(|stdout| cargo_install_list_contains_crate(&stdout))
}

fn cargo_install_list_contains_crate(output: &str) -> bool {
    output
        .lines()
        .any(|line| line.split_whitespace().next() == Some("rho-coding-agent"))
}

/// Asks pacman, then rpm, which package owns `path`. A missing tool or an
/// unowned path answers `None` (both exit nonzero for an unowned path).
/// Linux only: neither database owns a macOS or Windows install.
fn system_package_owner(path: &Path, probe: &impl Probe) -> Option<SystemPackageOwner> {
    if !cfg!(target_os = "linux") {
        return None;
    }
    let query = |manager, program: &str, args: &[&str]| {
        let mut command = Command::new(program);
        command.args(args).arg(path);
        probe
            .output(command)
            .ok()
            .filter(|output| output.status.success())
            .and_then(|output| String::from_utf8(output.stdout).ok())
            .map(|package| package.trim().to_owned())
            .filter(|package| !package.is_empty())
            .map(|package| SystemPackageOwner { manager, package })
    };
    query(SystemPackageManager::Pacman, "pacman", &["-Qqo"]).or_else(|| {
        query(
            SystemPackageManager::Rpm,
            "rpm",
            &["-qf", "--queryformat", "%{NAME}\n"],
        )
    })
}

fn scoop_install_scope_for_path(path: &Path, roots: &ScoopRoots) -> Option<ScoopInstallScope> {
    let lower = normalized_scoop_path(&path.to_string_lossy());
    // Configured roots need not contain a directory literally named `scoop`.
    // Prefer global when both variables name the same root.
    for (root, scope) in [
        (roots.global.as_deref(), ScoopInstallScope::Global),
        (roots.user.as_deref(), ScoopInstallScope::User),
    ] {
        let Some(root) = root else { continue };
        let root = normalized_scoop_path(root);
        let root = root.trim_end_matches('/');
        if !root.is_empty()
            && lower
                .strip_prefix(&format!("{root}/"))
                .is_some_and(is_scoop_rho_entry)
        {
            return Some(scope);
        }
    }
    // Retain default-layout detection when the launching shell lacks Scoop's
    // environment variables, but require the actual package or shim layout.
    let (root, entry) = lower.rsplit_once("/scoop/")?;
    if !is_scoop_rho_entry(entry) {
        return None;
    }
    Some(if root.ends_with("/programdata") {
        ScoopInstallScope::Global
    } else {
        ScoopInstallScope::User
    })
}

fn normalized_scoop_path(value: &str) -> String {
    let lower = value.replace('\\', "/").to_ascii_lowercase();
    if let Some(unc) = lower.strip_prefix("//?/unc/") {
        format!("//{unc}")
    } else {
        lower.strip_prefix("//?/").unwrap_or(&lower).to_owned()
    }
}

fn is_scoop_rho_entry(entry: &str) -> bool {
    if matches!(entry, "shims/rho" | "shims/rho.exe") {
        return true;
    }
    let Some((version, binary)) = entry
        .strip_prefix("apps/rho/")
        .and_then(|entry| entry.split_once('/'))
    else {
        return false;
    };
    !matches!(version, "" | "." | "..") && matches!(binary, "rho" | "rho.exe")
}

#[cfg(test)]
#[path = "installation_tests.rs"]
mod tests;