merry-process 0.1.3

Sandboxed host-process execution (Landlock/seccomp, Seatbelt, Windows Job Objects) for Merry.
Documentation
use crate::process_runner::TokioProcessRunner;
use merry_runtime::{
    ProcessActionIntent, ProcessEnvPolicy, ProcessExitStatus, ProcessRunner, ProcessRunnerContext,
};
use std::ffi::OsString;
use tokio_util::sync::CancellationToken;

#[cfg(unix)]
#[tokio::test]
async fn tokio_process_runner_inherits_current_process_environment() {
    let Ok(path) = std::env::var("PATH") else {
        return;
    };
    let Ok(home) = std::env::var("HOME") else {
        return;
    };
    let intent = ProcessActionIntent::new(
        vec![
            "/bin/sh".to_owned(),
            "-c".to_owned(),
            "printf '%s\n%s' \"${PATH-}\" \"${HOME-}\"".to_owned(),
        ],
        None,
        ProcessEnvPolicy::empty(),
        None,
        64 * 1024,
        1024,
    )
    .expect("process intent should be valid");

    let output = TokioProcessRunner::new()
        .run(intent, ProcessRunnerContext::new(CancellationToken::new()))
        .await
        .expect("process should run");

    assert_eq!(output.status(), ProcessExitStatus::Exited(0));
    assert_eq!(output.stdout_text(), format!("{path}\n{home}"));
}

#[cfg(unix)]
#[tokio::test]
async fn tokio_process_runner_applies_validated_environment_overrides() {
    let intent = ProcessActionIntent::new(
        vec![
            "/bin/sh".to_owned(),
            "-c".to_owned(),
            "printf '%s' \"${MERRY_TEST_MODE-}\"".to_owned(),
        ],
        None,
        ProcessEnvPolicy::empty(),
        None,
        64 * 1024,
        1024,
    )
    .expect("process intent should be valid");

    let output = TokioProcessRunner::new()
        .with_environment_overrides([(OsString::from("MERRY_TEST_MODE"), OsString::from("host"))])
        .expect("environment override should validate")
        .run(intent, ProcessRunnerContext::new(CancellationToken::new()))
        .await
        .expect("process should run");

    assert_eq!(output.status(), ProcessExitStatus::Exited(0));
    assert_eq!(output.stdout_text(), "host");
}

#[cfg(windows)]
#[tokio::test]
async fn tokio_process_runner_executes_powershell_and_applies_env_overrides() {
    let intent = ProcessActionIntent::new(
        vec![
            "powershell.exe".to_owned(),
            "-NoProfile".to_owned(),
            "-NonInteractive".to_owned(),
            "-Command".to_owned(),
            "Write-Output \"$env:MERRY_TEST_MODE|你好\"".to_owned(),
        ],
        None,
        ProcessEnvPolicy::empty(),
        None,
        64 * 1024,
        1024,
    )
    .expect("process intent should be valid");

    let output = TokioProcessRunner::new()
        .with_environment_overrides([(OsString::from("MERRY_TEST_MODE"), OsString::from("host"))])
        .expect("environment override should validate")
        .run(intent, ProcessRunnerContext::new(CancellationToken::new()))
        .await
        .expect("Windows PowerShell process should run");

    assert_eq!(output.status(), ProcessExitStatus::Exited(0));
    assert_eq!(output.stdout_text().trim(), "host|你好");
}

#[cfg(unix)]
#[tokio::test]
async fn tokio_process_runner_preserves_non_utf8_output() {
    let intent = ProcessActionIntent::new(
        vec![
            "/bin/sh".to_owned(),
            "-c".to_owned(),
            "printf '\\377\\000'; printf '\\376\\001' >&2".to_owned(),
        ],
        None,
        ProcessEnvPolicy::empty(),
        None,
        1024,
        1024,
    )
    .expect("process intent should be valid");

    let output = TokioProcessRunner::new()
        .run(intent, ProcessRunnerContext::new(CancellationToken::new()))
        .await
        .expect("binary process output must not fail the runner");

    assert_eq!(output.status(), ProcessExitStatus::Exited(0));
    assert_eq!(output.stdout_data(), &[0xff, 0]);
    assert_eq!(output.stderr_data(), &[0xfe, 1]);
    assert!(!output.stdout_is_utf8());
    assert!(!output.stderr_is_utf8());
    assert!(output.stdout_text().contains('\u{fffd}'));
    assert!(output.stderr_text().contains('\u{fffd}'));
}

#[cfg(unix)]
pub(super) fn background_intent(argv: Vec<String>) -> ProcessActionIntent {
    ProcessActionIntent::new(argv, None, ProcessEnvPolicy::empty(), None, 1024, 1024)
        .expect("process intent should be valid")
        .with_background(true)
}

#[cfg(unix)]
pub(super) fn process_alive(pid: u32) -> bool {
    rustix::process::Pid::from_raw(pid as rustix::process::RawPid)
        .is_some_and(|pid| rustix::process::test_kill_process(pid).is_ok())
}

#[cfg(unix)]
pub(super) async fn wait_until_dead(pid: u32) {
    let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(2);
    loop {
        if !process_alive(pid) {
            return;
        }
        if tokio::time::Instant::now() >= deadline {
            panic!("process {pid} was still alive");
        }
        tokio::time::sleep(std::time::Duration::from_millis(20)).await;
    }
}

#[cfg(unix)]
#[tokio::test]
async fn background_command_returns_while_the_process_stays_alive() {
    let runner = TokioProcessRunner::new();
    let started = std::time::Instant::now();
    let output = runner
        .run(
            background_intent(vec!["/bin/sleep".to_owned(), "30".to_owned()]),
            ProcessRunnerContext::new(CancellationToken::new()),
        )
        .await
        .expect("background sleep should be retained");

    assert!(started.elapsed() < std::time::Duration::from_secs(5));
    assert_eq!(output.status(), ProcessExitStatus::Running);
    assert!(output.ok());
    let pid = output.running_pid().expect("retained process has a pid");
    assert!(process_alive(pid));
    let id = output
        .background_process_id()
        .expect("retained process has an id");
    assert_eq!(id.as_str(), "bg-1");
    assert_eq!(output.wait_timed_out_secs(), None);
    drop(runner);
    wait_until_dead(pid).await;
}

#[cfg(unix)]
#[tokio::test]
async fn foreground_command_wait_timeout_retains_running_process_without_killing_it() {
    let runner = TokioProcessRunner::new();
    let intent = ProcessActionIntent::new(
        vec![
            "/bin/sh".to_owned(),
            "-c".to_owned(),
            "echo started; sleep 30".to_owned(),
        ],
        None,
        ProcessEnvPolicy::empty(),
        None,
        4096,
        4096,
    )
    .expect("valid intent")
    .with_timeout_secs(Some(1))
    .expect("valid timeout_secs");

    let started = std::time::Instant::now();
    let output = runner
        .run(intent, ProcessRunnerContext::new(CancellationToken::new()))
        .await
        .expect("timed-out foreground process should be retained instead of killed");

    assert!(started.elapsed() < std::time::Duration::from_secs(5));
    assert_eq!(output.status(), ProcessExitStatus::Running);
    assert!(output.ok());
    assert_eq!(output.wait_timed_out_secs(), Some(1));
    assert!(output.stdout_text().contains("started"));
    let pid = output.running_pid().expect("retained process has a pid");
    assert!(
        process_alive(pid),
        "timed-out foreground command must stay alive for the LLM to inspect or stop"
    );
    let id = output
        .background_process_id()
        .expect("retained process has a background id")
        .clone();
    assert_eq!(id.as_str(), "proc-1");

    let control = runner.background_control().expect("background control");
    let read = control.read(&id).expect("read retained output");
    assert!(read.stdout().contains("started"));
    assert_eq!(read.summary().display_name(), Some("echo started"));
    let stopped = control.stop(&id).expect("stop retained process");
    assert!(stopped.changed());
    wait_until_dead(pid).await;
}

#[cfg(unix)]
#[tokio::test]
async fn background_command_that_exits_immediately_is_not_retained() {
    let started = std::time::Instant::now();
    let output = TokioProcessRunner::new()
        .run(
            background_intent(vec![
                "/bin/sh".to_owned(),
                "-c".to_owned(),
                "echo hi".to_owned(),
            ]),
            ProcessRunnerContext::new(CancellationToken::new()),
        )
        .await
        .expect("fast background command should finish");

    assert!(started.elapsed() < std::time::Duration::from_secs(5));
    assert_eq!(output.status(), ProcessExitStatus::Exited(0));
    assert_eq!(output.stdout_text(), "hi\n");
    assert!(output.running_pid().is_none());
    assert!(output.background_process_id().is_none());
}

#[cfg(unix)]
#[tokio::test]
async fn dropping_the_runner_kills_background_children() {
    let dir = tempfile::tempdir().expect("tempdir");
    let pidfile = dir.path().join("child.pid");
    let script = format!("sleep 300 & echo $! > '{}'; wait", pidfile.display());
    let runner = TokioProcessRunner::new();
    let output = runner
        .run(
            background_intent(vec!["/bin/sh".to_owned(), "-c".to_owned(), script]),
            ProcessRunnerContext::new(CancellationToken::new()),
        )
        .await
        .expect("background shell should be retained");
    let shell_pid = output.running_pid().expect("shell pid");
    let child_pid = std::fs::read_to_string(&pidfile)
        .expect("grandchild pid file")
        .trim()
        .parse::<u32>()
        .expect("grandchild pid");
    assert!(process_alive(shell_pid));
    assert!(process_alive(child_pid));
    drop(runner);
    wait_until_dead(shell_pid).await;
    wait_until_dead(child_pid).await;
}

#[cfg(unix)]
#[tokio::test]
async fn stop_background_process_kills_the_retained_group() {
    let dir = tempfile::tempdir().expect("tempdir");
    let pidfile = dir.path().join("child.pid");
    let script = format!(
        "echo ready; sleep 300 & echo $! > '{}'; wait",
        pidfile.display()
    );
    let runner = TokioProcessRunner::new();
    let output = runner
        .run(
            background_intent(vec!["/bin/sh".to_owned(), "-c".to_owned(), script]),
            ProcessRunnerContext::new(CancellationToken::new()),
        )
        .await
        .expect("background shell should be retained");
    let id = output.background_process_id().expect("id").clone();
    let shell_pid = output.running_pid().expect("shell pid");
    let child_pid = std::fs::read_to_string(&pidfile)
        .expect("grandchild pid file")
        .trim()
        .parse::<u32>()
        .expect("grandchild pid");
    let control = runner.background_control().expect("background control");
    let read = control.read(&id).expect("read retained output");
    assert!(read.stdout().contains("ready"));
    let stopped = control.stop(&id).expect("stop");
    assert!(stopped.changed());
    assert_eq!(stopped.summary().id(), &id);
    wait_until_dead(shell_pid).await;
    wait_until_dead(child_pid).await;
    let again = control.stop(&id).expect("second stop");
    assert!(!again.changed());
    assert!(
        control
            .read(&merry_runtime::BackgroundProcessId::new("bg-9").expect("id"))
            .is_err()
    );
}