rho-coding-agent 3.11.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
use std::{
    fs,
    io::Write,
    path::{Path, PathBuf},
};

use pretty_assertions::assert_eq;

use super::{
    extract_executable, install, remove_update_leftovers, sibling, swap, verify_checksum,
    SwapError, ARCHIVE_EXECUTABLE,
};

/// The file names in `dir`, sorted.
fn names(dir: &Path) -> Vec<String> {
    let mut names: Vec<String> = fs::read_dir(dir)
        .unwrap()
        .map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned())
        .collect();
    names.sort();
    names
}

fn sorted<const N: usize>(mut names: [String; N]) -> Vec<String> {
    names.sort();
    names.into()
}

fn file_name(path: &Path) -> String {
    path.file_name().unwrap().to_string_lossy().into_owned()
}

// Covers: a downloaded rho that does not run is never swapped in: the
// installed rho stays, and the staged file is removed.
// Owner: in-place update probe gate
#[tokio::test]
async fn install_refuses_a_rho_that_does_not_run() {
    let dir = tempfile::tempdir().unwrap();
    let installed = dir.path().join("rho.exe");
    fs::write(&installed, "old").unwrap();

    install(&installed, b"not a program", "3.10.0")
        .await
        .expect_err("a file that cannot run is refused");

    assert_eq!(fs::read_to_string(&installed).unwrap(), "old");
    assert_eq!(names(dir.path()), ["rho.exe"]);
}

/// `rho.exe` holding "old" and a staged new rho holding "new" in a fresh
/// directory, beside unrelated files a cleanup must keep.
fn installed_and_staged(dir: &Path) -> (PathBuf, PathBuf) {
    let installed = dir.join("rho.exe");
    fs::write(&installed, "old").unwrap();
    let staged = sibling(&installed, "new-1");
    fs::write(&staged, "new").unwrap();
    fs::write(dir.join("rho.txt"), "kept").unwrap();
    fs::write(dir.join("rho.old-mine.exe"), "kept").unwrap();
    (installed, staged)
}

// Covers: the new rho takes the installed name, and the old one survives
// beside it, which a rollback and the processes still running it need.
// Owner: in-place update swap
#[test]
fn swap_puts_the_new_rho_in_place_and_keeps_the_old_beside_it() {
    let dir = tempfile::tempdir().unwrap();
    let (installed, staged) = installed_and_staged(dir.path());

    let aside = swap(&installed, &staged).expect("the swap succeeds");

    assert_eq!(fs::read_to_string(&installed).unwrap(), "new");
    assert_eq!(fs::read_to_string(&aside).unwrap(), "old");
    assert_eq!(
        names(dir.path()),
        sorted([
            file_name(&aside),
            "rho.exe".into(),
            "rho.txt".into(),
            "rho.old-mine.exe".into()
        ])
    );
}

/// The pid of a process that ran and exited.
fn exited_pid() -> u32 {
    // This test binary prints its usage and exits.
    let mut child = std::process::Command::new(std::env::current_exe().unwrap())
        .arg("--help")
        .stdout(std::process::Stdio::null())
        .spawn()
        .unwrap();
    child.wait().unwrap();
    child.id()
}

// Covers: every rho start sweeps, also while an update runs, as rho-ui's
// commands do during one. The sweep keeps what a running update moved
// aside (its rollback) or staged (its swap), removes what an update that
// ended left, and leaves files a person named alike.
// Owner: in-place update leftover sweep
#[test]
fn the_sweep_removes_only_what_ended_updates_left() {
    let dir = tempfile::tempdir().unwrap();
    let installed = dir.path().join("rho.exe");
    fs::write(&installed, "rho").unwrap();
    // This test process stands in for the running update.
    let running = std::process::id();
    let ended = exited_pid();
    let kept = [
        format!("rho.old-1796147852247597900-{running}.exe"),
        format!("rho.new-{running}.exe"),
        "rho.old-2026-12-01.exe".to_owned(),
        "rho.old-mine.exe".to_owned(),
        "rho.new-+1.exe".to_owned(),
    ];
    let removed = [
        format!("rho.old-1796147852247597900-{ended}.exe"),
        format!("rho.new-{ended}.exe"),
    ];
    for name in kept.iter().chain(&removed) {
        fs::write(dir.path().join(name), "left").unwrap();
    }

    remove_update_leftovers(&installed);

    let mut expected = kept.to_vec();
    expected.push("rho.exe".to_owned());
    expected.sort();
    assert_eq!(names(dir.path()), expected);
}

// Covers: a swap that fails at either step leaves the installed rho as it
// was, under its own name, with nothing moved aside.
// Owner: in-place update rollback
#[test]
fn failed_swap_leaves_the_installed_rho() {
    let dir = tempfile::tempdir().unwrap();
    let (installed, staged) = installed_and_staged(dir.path());
    let missing = dir.path().join("missing");

    // The new rho vanished before it could take the name, as when security
    // software quarantines it: the old one moves back.
    let error = swap(&installed, &missing).expect_err("there is nothing to place");
    assert!(matches!(error, SwapError::Place { .. }), "{error:?}");
    assert_eq!(fs::read_to_string(&installed).unwrap(), "old");
    assert_eq!(
        names(dir.path()),
        sorted([
            file_name(&staged),
            "rho.exe".into(),
            "rho.txt".into(),
            "rho.old-mine.exe".into(),
        ])
    );

    // The installed rho could not move aside: nothing changed.
    let error = swap(&missing, &staged).expect_err("there is nothing to move aside");
    assert!(matches!(error, SwapError::MoveAside { .. }), "{error:?}");
    assert_eq!(
        names(dir.path()),
        sorted([
            file_name(&staged),
            "rho.exe".into(),
            "rho.txt".into(),
            "rho.old-mine.exe".into(),
        ])
    );
}

// Covers: Windows lets a running program's file move aside but not be
// removed, so the swap works under a running rho and the cleanup of an
// ended update's file waits until the program running it exits.
// Owner: in-place update swap, Windows file semantics
#[cfg(windows)]
#[test]
fn swap_moves_a_running_program_aside_and_removes_it_once_it_exits() {
    let dir = tempfile::tempdir().unwrap();
    let (installed, staged) = installed_and_staged(dir.path());
    // A program that keeps running until killed stands in for rho.
    let system = std::env::var_os("SystemRoot").expect("Windows names its directory");
    fs::copy(
        Path::new(&system).join("System32").join("ping.exe"),
        &installed,
    )
    .unwrap();
    /// Kills the program on drop, so a failed assertion leaves none running.
    struct Running(std::process::Child);
    impl Drop for Running {
        fn drop(&mut self) {
            let _ = self.0.kill();
            let _ = self.0.wait();
        }
    }
    let mut running = Running(
        std::process::Command::new(&installed)
            .args(["-n", "600", "127.0.0.1"])
            .stdout(std::process::Stdio::null())
            .spawn()
            .unwrap(),
    );
    // Writing over the running file is what Windows refuses.
    assert!(fs::write(&installed, "new").is_err());

    let aside = swap(&installed, &staged).expect("a running program's file moves aside");
    assert_eq!(fs::read_to_string(&installed).unwrap(), "new");
    assert_eq!(
        running.0.try_wait().unwrap(),
        None,
        "the program still runs"
    );

    // Once the update ended, only the program still running the file
    // keeps it: Windows refuses to delete a running program's file.
    let ended = sibling(&installed, &format!("old-1-{}", exited_pid()));
    fs::rename(&aside, &ended).unwrap();
    remove_update_leftovers(&installed);
    assert!(ended.exists(), "a running program's file is kept");

    drop(running);
    remove_update_leftovers(&installed);
    assert!(!ended.exists(), "removed once nothing runs it");
}

// Covers: the archive is trusted only when its SHA-256 matches the
// release's `.sha256`, read as install.ps1 reads it.
// Owner: in-place update verification
#[test]
fn verifies_the_archive_against_the_published_checksum() {
    let actual = hex::encode(<sha2::Sha256 as sha2::Digest>::digest(b"rho"));
    let cases = [
        (
            format!("{actual}  rho-x86_64-pc-windows-msvc.zip\r\n"),
            true,
        ),
        (actual.to_uppercase(), true),
        (format!("{}0", &actual[..63]), false),
        (String::new(), false),
        ("   \n".to_owned(), false),
    ];
    for (checksum, verified) in cases {
        assert_eq!(
            verify_checksum(b"rho", &checksum).is_ok(),
            verified,
            "{checksum:?}"
        );
    }
}

// Covers: the executable comes out of the release's zip by its name, and
// an archive without it is refused rather than installed as nothing.
// Owner: in-place update unpacking
#[test]
fn extracts_rho_exe_from_the_release_archive() {
    let zip = |name: &str| {
        let mut writer = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
        writer
            .start_file(name, zip::write::SimpleFileOptions::default())
            .unwrap();
        writer.write_all(b"MZ rho").unwrap();
        writer.finish().unwrap().into_inner()
    };

    assert_eq!(
        extract_executable(&zip(ARCHIVE_EXECUTABLE)).unwrap(),
        b"MZ rho"
    );
    assert!(extract_executable(&zip("other.exe")).is_err());
    assert!(extract_executable(b"not a zip").is_err());
}