From 3936b70cee6f783bec8f0670c6e8a982e299ad38 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Oscar=20Nordstr=C3=B6m?= <13300531+n0rpan@users.noreply.github.com> Date: Sun, 15 Nov 2026 15:18:50 +0000 Subject: [PATCH 01/11] Register oxa-work crate for issue #333 --- oxa/Cargo.lock | 9 +++++++++ oxa/Cargo.toml | 3 ++- oxa/oxa-cli/Cargo.toml | 1 + oxa/oxa-work/Cargo.toml | 14 ++++++++++++++ oxa/oxa-work/src/lib.rs | 1 + 5 files changed, 27 insertions(+), 1 deletion(-) create mode 100644 oxa/oxa-work/Cargo.toml create mode 100644 oxa/oxa-work/src/lib.rs diff --git a/oxa/Cargo.lock b/oxa/Cargo.lock index 485000b98..c5f1ba2d8 100644 --- a/oxa/Cargo.lock +++ b/oxa/Cargo.lock @@ -431,6 +431,7 @@ dependencies = [ "oxa-tools", "oxa-tui", "oxa-web", + "oxa-work", "regex", "serde_json", "sha2", @@ -694,6 +695,14 @@ dependencies = [ "ureq", ] +[[package]] +name = "oxa-work" +version = "0.2.0" +dependencies = [ + "serde", + "serde_json", +] + [[package]] name = "parking_lot" version = "0.12.5" diff --git a/oxa/Cargo.toml b/oxa/Cargo.toml index b4a683d90..27d254cff 100644 --- a/oxa/Cargo.toml +++ b/oxa/Cargo.toml @@ -12,7 +12,7 @@ members = [ "oxa-core", "oxa-tui", "oxa-interactive", "oxa-rpc", "oxa-export", - "oxa-cli", + "oxa-cli", "oxa-work", "oxa-fake", "oxa-parity", ] @@ -45,6 +45,7 @@ oxa-interactive = { path = "oxa-interactive" } oxa-rpc = { path = "oxa-rpc" } oxa-export = { path = "oxa-export" } oxa-cli = { path = "oxa-cli" } +oxa-work = { path = "oxa-work" } oxa-fake = { path = "oxa-fake" } # external (plan sec. 4); no async runtime anywhere serde = { version = "1", features = ["derive"] } diff --git a/oxa/oxa-cli/Cargo.toml b/oxa/oxa-cli/Cargo.toml index f962b13ad..a6085a4db 100644 --- a/oxa/oxa-cli/Cargo.toml +++ b/oxa/oxa-cli/Cargo.toml @@ -17,6 +17,7 @@ name = "oxa" path = "src/main.rs" [dependencies] +oxa-work.workspace = true oxa-proto.workspace = true oxa-engine.workspace = true oxa-session.workspace = true diff --git a/oxa/oxa-work/Cargo.toml b/oxa/oxa-work/Cargo.toml new file mode 100644 index 000000000..6097461ce --- /dev/null +++ b/oxa/oxa-work/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "oxa-work" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +publish.workspace = true + +[dependencies] +serde.workspace = true +serde_json.workspace = true + +[lints] +workspace = true diff --git a/oxa/oxa-work/src/lib.rs b/oxa/oxa-work/src/lib.rs new file mode 100644 index 000000000..90f7f11b9 --- /dev/null +++ b/oxa/oxa-work/src/lib.rs @@ -0,0 +1 @@ +//! Unattended task runner. From fb25b362d9be2fe7c59d4ce3f12e9ce17e50124c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Oscar=20Nordstr=C3=B6m?= <13300531+n0rpan@users.noreply.github.com> Date: Sun, 15 Nov 2026 15:23:27 +0000 Subject: [PATCH 02/11] Add opt-in work task runner with external acceptance checks (#333) --- oxa/docs/work.md | 33 +++++ oxa/oxa-cli/src/args.rs | 7 + oxa/oxa-cli/src/dispatch.rs | 1 + oxa/oxa-cli/src/lib.rs | 1 + oxa/oxa-cli/src/work_cmd.rs | 39 ++++++ oxa/oxa-cli/tests/work_cli.rs | 190 ++++++++++++++++++++++++++ oxa/oxa-work/src/lib.rs | 250 +++++++++++++++++++++++++++++++++- 7 files changed, 520 insertions(+), 1 deletion(-) create mode 100644 oxa/docs/work.md create mode 100644 oxa/oxa-cli/src/work_cmd.rs create mode 100644 oxa/oxa-cli/tests/work_cli.rs diff --git a/oxa/docs/work.md b/oxa/docs/work.md new file mode 100644 index 000000000..4bee57969 --- /dev/null +++ b/oxa/docs/work.md @@ -0,0 +1,33 @@ +# Unattended work + +`oxa work tasks.json` opts into sequential tasks in separate git worktrees. +Run it inside the project repository. The JSON file is an array: + +```json +[{"id":"docs-fix","model":"your-model","branch":"agent/docs-fix","base":"main","prompt":"Fix documentation links."}] +``` + +`base` defaults to `main`. IDs contain letters, digits, hyphens or underscores. +IDs and branches must be unique; branches must be new. For a GitHub issue use +`oxa work --issue 123 --model your-model`. This explicitly invokes your installed, +authenticated `gh` CLI to fetch the issue title and body. + +Each task runs a child `oxa -p` with its model. Normal agent permission, trust and +sandbox rules apply. Configure project trust before unattended use. The runner +executes the base version of `.oxa/settings.json`'s `done` commands outside the +agent after it exits, even without edits. These are trusted project shell commands: +invoking `work` authorizes their execution as your user. `in subdirectory: command` +runs in that worktree subdirectory; escaping it with the directory is rejected. +Agent-internal done checks may also run when the project is trusted. + +Failed acceptance output goes to one additional child run with the original prompt, +then acceptance runs once more. JSON lines report `done`, `nothing_to_do` (no +commits or file changes), `red` (checks still fail), or `blocked` (setup or agent +execution failed). Exit codes are 0 for success, 1 if any task is red or blocked, +and 2 for invalid input or runner errors. + +Worktrees and uncommitted changes remain under the common git directory's +`oxa-work/`. Result receipts are beside them at `.json`. No automatic +cleanup, commit, push, PR creation or continuation is implemented yet. Inspect +retained work before removing it with `git worktree remove`. Review task prompts +and bases before running them. diff --git a/oxa/oxa-cli/src/args.rs b/oxa/oxa-cli/src/args.rs index d62d19272..ecf283560 100644 --- a/oxa/oxa-cli/src/args.rs +++ b/oxa/oxa-cli/src/args.rs @@ -14,6 +14,8 @@ pub enum ModeArg { /// A subcommand (first positional word). #[derive(Debug, Clone, PartialEq, Eq)] pub enum Subcommand { + /// `oxa work | --issue N --model MODEL`. + Work(Vec), /// `oxa mcp add|remove|list|login|logout ..`: the words after `mcp`. Mcp(Vec), /// `oxa install|remove|update|list ..`: the verb and the words after it. @@ -174,6 +176,10 @@ const COMMANDS: &[(&str, &str)] = &[ "oxa report-issue ", "Draft a scrubbed ox-llm issue; submit posts it only after you type yes", ), + ( + "oxa work | --issue N --model MODEL", + "Run tasks in isolated worktrees with external acceptance checks", + ), ( "oxa wipe --session | --all [--yes] [--engine]", "Delete one session (or every session) and its spill files; --engine also drops the engine's state", @@ -340,6 +346,7 @@ fn subcommand(word: &str, rest: &[String]) -> Result, OxaErro "identity" => Subcommand::Identity(rest.to_vec()), "report-issue" => Subcommand::ReportIssue(rest.to_vec()), "wipe" => Subcommand::Wipe(rest.to_vec()), + "work" => Subcommand::Work(rest.to_vec()), "auth" => return Err(OxaError::unsupported("the auth command")), // pi's provider sign-in (`pi login [--api-key] [--no-browser]`, `pi logout`). "login" | "logout" => { diff --git a/oxa/oxa-cli/src/dispatch.rs b/oxa/oxa-cli/src/dispatch.rs index 101f58fe4..4bdc4b7b0 100644 --- a/oxa/oxa-cli/src/dispatch.rs +++ b/oxa/oxa-cli/src/dispatch.rs @@ -125,6 +125,7 @@ pub fn run(argv: &[String], env: &Env, io: Stdio) -> i32 { Err(e) => return report(&mut *stderr, &e), }; let result = match sub { + Subcommand::Work(words) => return crate::work_cmd::run(&words, &cwd, &mut *stdout, &mut *stderr), Subcommand::Mcp(words) => run_mcp(&words, &dirs, &cwd, &mut *stdout, &mut *stderr), Subcommand::Pkg(verb, words) => run_pkg(&verb, &words, &dirs, &cwd, &mut *stdout, &mut *stderr), Subcommand::Config(words) => run_config(&words, &dirs, &cwd, &mut *stdout), diff --git a/oxa/oxa-cli/src/lib.rs b/oxa/oxa-cli/src/lib.rs index b7096b398..f5cc30f16 100644 --- a/oxa/oxa-cli/src/lib.rs +++ b/oxa/oxa-cli/src/lib.rs @@ -31,6 +31,7 @@ mod report_cmd; mod sandbox_layout; mod themes; mod wipe_cmd; +mod work_cmd; pub use args::{parse_args, usage_text, ApiKey, Args, ModeArg, Subcommand}; pub use config_cmd::run_config; diff --git a/oxa/oxa-cli/src/work_cmd.rs b/oxa/oxa-cli/src/work_cmd.rs new file mode 100644 index 000000000..3d8769c5e --- /dev/null +++ b/oxa/oxa-cli/src/work_cmd.rs @@ -0,0 +1,39 @@ +use std::io::Write; +use std::path::{Path, PathBuf}; + +pub(crate) fn run(args: &[String], cwd: &Path, out: &mut dyn Write, err: &mut dyn Write) -> i32 { + let result = (|| -> Result { + let tasks = match args { + [file] if !file.starts_with('-') => oxa_work::read_tasks(&cwd.join(file))?, + [flag, number, model_flag, model] if flag == "--issue" && model_flag == "--model" => { + vec![oxa_work::issue_task( + cwd, + number.parse().map_err(|_| "invalid issue number")?, + model.clone(), + )?] + } + _ => return Err("usage: oxa work | --issue N --model MODEL".into()), + }; + let binary: PathBuf = std::env::current_exe().map_err(|e| e.to_string())?; + let mut code = 0; + for task in tasks { + let record = oxa_work::run_task(cwd, &binary, &task)?; + if matches!( + record.outcome, + oxa_work::Outcome::Red | oxa_work::Outcome::Blocked + ) { + code = 1; + } + serde_json::to_writer(&mut *out, &record).map_err(|e| e.to_string())?; + writeln!(out).map_err(|e| e.to_string())?; + } + Ok(code) + })(); + match result { + Ok(code) => code, + Err(e) => { + let _ = writeln!(err, "oxa work: {e}"); + 2 + } + } +} diff --git a/oxa/oxa-cli/tests/work_cli.rs b/oxa/oxa-cli/tests/work_cli.rs new file mode 100644 index 000000000..fa28e7b54 --- /dev/null +++ b/oxa/oxa-cli/tests/work_cli.rs @@ -0,0 +1,190 @@ +//! Real child oxa with fake engine and local bare git remote; no network. +use oxa_fake::{FakeOpts, FakeServer, ScriptTurn, TestEnv}; +use std::{path::Path, process::Command}; +fn git(env: &TestEnv, dir: &Path, args: &[&str]) { + let out = Command::new("git") + .args(args) + .current_dir(dir) + .env_clear() + .envs(env.envs("http://127.0.0.1:1")) + .env("GIT_AUTHOR_NAME", "Test") + .env("GIT_AUTHOR_EMAIL", "test@example.invalid") + .env("GIT_COMMITTER_NAME", "Test") + .env("GIT_COMMITTER_EMAIL", "test@example.invalid") + .output() + .unwrap(); + assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); +} +fn setup(env: &TestEnv, done: &str) { + git(env, &env.work(), &["init", "--bare", "remote.git"]); + git(env, &env.work(), &["init", "-b", "main", "project"]); + let project = env.work().join("project"); + env.write( + "work/project/.oxa/settings.json", + &format!(r#"{{"done":{done}}}"#), + ); + git(env, &project, &["add", "."]); + git(env, &project, &["commit", "-m", "fixture"]); + git(env, &project, &["remote", "add", "origin", "../remote.git"]); + git(env, &project, &["push", "origin", "main"]); + env.write( + "work/tasks.json", + r#"[{"id":"test","branch":"agent/test","model":"fake","prompt":"Finish task"}]"#, + ); +} +fn run(env: &TestEnv, turns: Vec) -> serde_json::Value { + run_args(env, turns, &["work", "../tasks.json"], None) +} +fn run_args(env: &TestEnv, turns: Vec, args: &[&str], path: Option) -> serde_json::Value { + let server = FakeServer::start(turns, FakeOpts::default()).unwrap(); + let mut command = Command::new(env!("CARGO_BIN_EXE_oxa")); + command + .args(args) + .current_dir(env.work().join("project")) + .env_clear() + .envs(env.envs(&server.url())); + if let Some(path) = path { + command.env("PATH", path); + } + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + tx.send(command.output().unwrap()).unwrap(); + }); + let out = rx + .recv_timeout(std::time::Duration::from_secs(90)) + .expect("runner finished"); + serde_json::from_slice(&out.stdout).unwrap_or_else(|e| { + panic!( + "{e}: {} / {}", + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr) + ) + }) +} +#[test] +fn external_checks_run_without_edits_and_retain_worktree() { + let env = TestEnv::new(); + setup(&env, r#"["printf checked > receipt"]"#); + let record = run(&env, vec![ScriptTurn::text("finished")]); + assert_eq!(record["outcome"], "done", "{record}"); + let tree = Path::new(record["worktree"].as_str().unwrap()); + assert_eq!(std::fs::read_to_string(tree.join("receipt")).unwrap(), "checked"); + assert!(env.work().join("project/.git/oxa-work/test.json").exists()); +} +#[test] +fn clean_task_is_nothing_to_do() { + let env = TestEnv::new(); + setup(&env, "[]"); + assert_eq!( + run(&env, vec![ScriptTurn::text("nothing")])["outcome"], + "nothing_to_do" + ); +} +#[test] +fn failed_checks_get_exactly_one_retry() { + let env = TestEnv::new(); + setup( + &env, + r#"["printf attempt >> attempts; echo external-check; exit 1"]"#, + ); + let record = run( + &env, + vec![ScriptTurn::text("finished"), ScriptTurn::text("cannot repair")], + ); + assert_eq!(record["outcome"], "red", "{record}"); + assert!(record["detail"].as_str().unwrap().contains("external-check")); + let tree = Path::new(record["worktree"].as_str().unwrap()); + assert_eq!( + std::fs::read_to_string(tree.join("attempts")).unwrap(), + "attemptattempt" + ); +} +#[test] +fn retry_can_make_acceptance_green() { + let env = TestEnv::new(); + setup( + &env, + r#"["if test -f once; then true; else touch once; exit 1; fi"]"#, + ); + let record = run( + &env, + vec![ScriptTurn::text("finished"), ScriptTurn::text("retry")], + ); + assert_eq!(record["outcome"], "done", "{record}"); +} + +#[test] +fn agent_edits_stay_in_worktree() { + let env = TestEnv::new(); + setup(&env, "[]"); + env.write( + "home/.oxa/agent/settings.json", + r#"{"defaultProjectTrust":"always"}"#, + ); + let record = run( + &env, + vec![ + ScriptTurn::tool("edit", "write", r#"{"path":"answer.txt","content":"finished"}"#), + ScriptTurn::text("done"), + ], + ); + assert_eq!(record["outcome"], "done", "{record}"); + let tree = Path::new(record["worktree"].as_str().unwrap()); + assert_eq!( + std::fs::read_to_string(tree.join("answer.txt")).unwrap(), + "finished" + ); + assert!(!env.work().join("project/answer.txt").exists()); +} +#[test] +fn invalid_task_file_is_rejected_before_creating_worktree() { + let env = TestEnv::new(); + setup(&env, "[]"); + env.write( + "work/tasks.json", + r#"[{"id":"../escape","branch":"agent/test","model":"fake","prompt":"go"}]"#, + ); + let out = Command::new(env!("CARGO_BIN_EXE_oxa")) + .args(["work", "../tasks.json"]) + .current_dir(env.work().join("project")) + .env_clear() + .envs(env.envs("http://127.0.0.1:1")) + .output() + .unwrap(); + assert_eq!(out.status.code(), Some(2)); + assert!(!env.work().join("project/.git/oxa-work").exists()); +} + +#[test] +fn github_issue_input_uses_mock_gh() { + use std::os::unix::fs::PermissionsExt; + let env = TestEnv::new(); + setup(&env, "[]"); + let gh = env.write( + "tmp/gh", + r##"#!/bin/sh +[ "$*" = 'issue view 42 --json title,body' ] || exit 9 +printf '%s' '{"title":"Synthetic task","body":"Fix the test fixture"}' +"##, + ); + std::fs::set_permissions(&gh, std::fs::Permissions::from_mode(0o755)).unwrap(); + let path = format!("{}:{}", env.tmp().display(), std::env::var("PATH").unwrap()); + let record = run_args( + &env, + vec![ScriptTurn::text("done")], + &["work", "--issue", "42", "--model", "fake"], + Some(path), + ); + assert_eq!(record["id"], "issue-42"); + assert_eq!(record["branch"], "agent/42-work"); + assert_eq!(record["outcome"], "nothing_to_do", "{record}"); +} +#[test] +fn setup_failure_records_blocked_and_keeps_existing_branch() { + let env = TestEnv::new(); + setup(&env, "[]"); + git(&env, &env.work().join("project"), &["branch", "agent/test"]); + let record = run(&env, vec![]); + assert_eq!(record["outcome"], "blocked", "{record}"); + assert!(record["detail"].as_str().unwrap().contains("already exists")); +} diff --git a/oxa/oxa-work/src/lib.rs b/oxa/oxa-work/src/lib.rs index 90f7f11b9..5f1dbd487 100644 --- a/oxa/oxa-work/src/lib.rs +++ b/oxa/oxa-work/src/lib.rs @@ -1 +1,249 @@ -//! Unattended task runner. +//! Opt-in, sequential unattended task execution. Worktrees are retained on every outcome. +use serde::{Deserialize, Serialize}; +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::{Command, Output, Stdio}; + +pub type Result = std::result::Result; + +#[derive(Clone, Debug, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct Task { + pub id: String, + pub model: String, + pub branch: String, + #[serde(default = "default_base")] + pub base: String, + pub prompt: String, +} +fn default_base() -> String { + "main".into() +} + +#[derive(Clone, Copy, Debug, Serialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum Outcome { + Done, + NothingToDo, + Red, + Blocked, +} + +#[derive(Debug, Serialize)] +pub struct Record { + pub id: String, + pub branch: String, + pub worktree: PathBuf, + pub outcome: Outcome, + pub detail: String, +} + +fn output(mut command: Command) -> Result { + command.stdin(Stdio::null()).output().map_err(|e| e.to_string()) +} +fn checked(command: Command) -> Result { + let out = output(command)?; + if !out.status.success() { + return Err(String::from_utf8_lossy(&out.stderr).into_owned()); + } + Ok(String::from_utf8_lossy(&out.stdout).trim().into()) +} +fn git(repo: &Path, args: &[&str]) -> Command { + let mut c = Command::new("git"); + c.current_dir(repo).args(args); + c +} + +pub fn read_tasks(path: &Path) -> Result> { + let tasks: Vec = serde_json::from_slice(&fs::read(path).map_err(|e| e.to_string())?) + .map_err(|e| format!("task file: {e}"))?; + if tasks.is_empty() { + return Err("task file is empty".into()); + } + let mut ids = std::collections::HashSet::new(); + let mut branches = std::collections::HashSet::new(); + for task in &tasks { + validate(task)?; + if !ids.insert(&task.id) || !branches.insert(&task.branch) { + return Err("duplicate task id or branch".into()); + } + } + Ok(tasks) +} +fn validate(task: &Task) -> Result<()> { + if task.id.is_empty() + || !task + .id + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b"-_".contains(&b)) + { + return Err("task id must contain only letters, digits, - or _".into()); + } + if task.model.trim().is_empty() || task.prompt.trim().is_empty() { + return Err("model and prompt are required".into()); + } + for reference in [&task.branch, &task.base] { + if reference.is_empty() || reference.starts_with('-') { + return Err("invalid branch or base".into()); + } + } + Ok(()) +} + +/// Issue text is data, passed as one prompt argument; gh never invokes a shell. +pub fn issue_task(repo: &Path, number: u64, model: String) -> Result { + if number == 0 { + return Err("issue number must be positive".into()); + } + let mut c = Command::new("gh"); + c.current_dir(repo) + .args(["issue", "view", &number.to_string(), "--json", "title,body"]); + let text = checked(c)?; + let issue: serde_json::Value = serde_json::from_str(&text).map_err(|e| e.to_string())?; + let title = issue["title"].as_str().ok_or("issue title missing")?; + let body = issue["body"].as_str().ok_or("issue body missing")?; + Ok(Task { + id: format!("issue-{number}"), + model, + branch: format!("agent/{number}-work"), + base: default_base(), + prompt: format!("Implement issue #{number}: {title}\n\n{body}"), + }) +} + +/// Acceptance commands are frozen from the base before the agent can edit settings. +fn done_commands(root: &Path) -> Result> { + let path = root.join(".oxa/settings.json"); + let bytes = match fs::read(path) { + Ok(bytes) => bytes, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(vec![]), + Err(e) => return Err(e.to_string()), + }; + let value: serde_json::Value = serde_json::from_slice(&bytes).map_err(|e| e.to_string())?; + match value.get("done") { + None => Ok(vec![]), + Some(value) => serde_json::from_value(value.clone()).map_err(|e| format!("done commands: {e}")), + } +} +fn acceptance(root: &Path, commands: &[String]) -> Result { + let mut failures = String::new(); + for entry in commands { + let (dir, shell) = match entry.strip_prefix("in ").and_then(|s| s.split_once(':')) { + Some((dir, cmd)) => (root.join(dir.trim()), cmd.trim()), + None => (root.to_path_buf(), entry.as_str()), + }; + let dir = dir.canonicalize().map_err(|e| e.to_string())?; + if !dir.starts_with(root) { + return Err("done directory escapes worktree".into()); + } + let mut c = Command::new("sh"); + c.current_dir(dir).args(["-c", shell]); + let out = output(c)?; + if !out.status.success() { + failures.push_str(&format!( + "{entry}: {}\n{}\n{}\n", + out.status, + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr) + )); + } + } + Ok(failures) +} +fn agent(binary: &Path, root: &Path, task: &Task, prompt: &str) -> Result<()> { + let mut c = Command::new(binary); + c.current_dir(root) + .args(["-p", "--model", &task.model, "--no-session", "--", prompt]); + checked(c).map(|_| ()) +} + +struct TaskLock(PathBuf); +impl Drop for TaskLock { + fn drop(&mut self) { + let _ = fs::remove_file(&self.0); + } +} + +pub fn run_task(repo: &Path, binary: &Path, task: &Task) -> Result { + validate(task)?; + let root = checked(git(repo, &["rev-parse", "--show-toplevel"]))?; + let root = PathBuf::from(root); + checked(git(&root, &["check-ref-format", "--branch", &task.branch]))?; + let common = checked(git( + &root, + &["rev-parse", "--path-format=absolute", "--git-common-dir"], + ))?; + let storage = PathBuf::from(common).join("oxa-work"); + fs::create_dir_all(&storage).map_err(|e| e.to_string())?; + let lock_path = storage.join(format!("{}.lock", task.id)); + let _lock_file = fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(&lock_path) + .map_err(|e| format!("cannot lock task {}: {e}", task.id))?; + let _lock = TaskLock(lock_path); + let receipt = storage.join(format!("{}.json", task.id)); + if receipt.exists() { + return Err("task already has a receipt; retained for inspection".into()); + } + let tree = storage.join(&task.id); + let mut record = Record { + id: task.id.clone(), + branch: task.branch.clone(), + worktree: tree.clone(), + outcome: Outcome::Blocked, + detail: String::new(), + }; + let result = (|| -> Result { + if tree.exists() { + return Err("task worktree already exists; retained for inspection".into()); + } + let tree_arg = tree.to_str().ok_or("non-UTF8 worktree path")?; + checked(git( + &root, + &["worktree", "add", "-b", &task.branch, tree_arg, &task.base], + ))?; + let tree = tree.canonicalize().map_err(|e| e.to_string())?; + let initial = checked(git(&tree, &["rev-parse", "HEAD"]))?; + let commands = done_commands(&tree)?; + let first_agent = agent(binary, &tree, task, &task.prompt); + let failures = acceptance(&tree, &commands)?; + if !failures.is_empty() { + let repair_agent = agent( + binary, + &tree, + task, + &format!( + "{}\n\nExternal acceptance checks failed. Repair once:\n{failures}", + task.prompt + ), + ); + let failures = acceptance(&tree, &commands)?; + if !failures.is_empty() { + record.detail = failures; + return Ok(Outcome::Red); + } + repair_agent?; + } else { + first_agent?; + } + let head = checked(git(&tree, &["rev-parse", "HEAD"]))?; + let dirty = checked(git(&tree, &["status", "--porcelain"]))?; + Ok(if head == initial && dirty.is_empty() { + Outcome::NothingToDo + } else { + Outcome::Done + }) + })(); + match result { + Ok(outcome) => record.outcome = outcome, + Err(e) => record.detail = e, + } + // Separate receipts avoid overwriting another task's result. Never remove its worktree. + fs::write( + receipt, + serde_json::to_vec_pretty(&record).map_err(|e| e.to_string())?, + ) + .map_err(|e| e.to_string())?; + Ok(record) +} From cdfab279d60b4ae005dcc413507d9bac49a32948 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Oscar=20Nordstr=C3=B6m?= <13300531+n0rpan@users.noreply.github.com> Date: Sun, 15 Nov 2026 15:48:01 +0000 Subject: [PATCH 03/11] Fix sandbox commits and offline issue lookup in work runner --- oxa/docs/work.md | 9 ++-- oxa/oxa-cli/src/work_cmd.rs | 3 ++ oxa/oxa-cli/tests/work_cli.rs | 80 +++++++++++++++++++++++++++++++++++ oxa/oxa-work/src/lib.rs | 18 +++++++- 4 files changed, 105 insertions(+), 5 deletions(-) diff --git a/oxa/docs/work.md b/oxa/docs/work.md index 4bee57969..ed74c8ab8 100644 --- a/oxa/docs/work.md +++ b/oxa/docs/work.md @@ -10,7 +10,8 @@ Run it inside the project repository. The JSON file is an array: `base` defaults to `main`. IDs contain letters, digits, hyphens or underscores. IDs and branches must be unique; branches must be new. For a GitHub issue use `oxa work --issue 123 --model your-model`. This explicitly invokes your installed, -authenticated `gh` CLI to fetch the issue title and body. +authenticated `gh` CLI to fetch the issue title and body. Issue lookup is refused +when the environment or user settings enable offline mode. Each task runs a child `oxa -p` with its model. Normal agent permission, trust and sandbox rules apply. Configure project trust before unattended use. The runner @@ -26,8 +27,10 @@ commits or file changes), `red` (checks still fail), or `blocked` (setup or agen execution failed). Exit codes are 0 for success, 1 if any task is red or blocked, and 2 for invalid input or runner errors. -Worktrees and uncommitted changes remain under the common git directory's -`oxa-work/`. Result receipts are beside them at `.json`. No automatic +Worktrees and uncommitted changes remain in `.oxa-worktrees//` +beside the repository (or the separate git directory). Result receipts live inside +the common git directory at `oxa-work/.json`. Worktrees stay outside that git +directory so the normal sandbox can bind git objects and refs for commits. No automatic cleanup, commit, push, PR creation or continuation is implemented yet. Inspect retained work before removing it with `git worktree remove`. Review task prompts and bases before running them. diff --git a/oxa/oxa-cli/src/work_cmd.rs b/oxa/oxa-cli/src/work_cmd.rs index 3d8769c5e..af2d67257 100644 --- a/oxa/oxa-cli/src/work_cmd.rs +++ b/oxa/oxa-cli/src/work_cmd.rs @@ -6,6 +6,9 @@ pub(crate) fn run(args: &[String], cwd: &Path, out: &mut dyn Write, err: &mut dy let tasks = match args { [file] if !file.starts_with('-') => oxa_work::read_tasks(&cwd.join(file))?, [flag, number, model_flag, model] if flag == "--issue" && model_flag == "--model" => { + if oxa_proto::offline() { + return Err("GitHub issue lookup is unavailable in offline mode".into()); + } vec![oxa_work::issue_task( cwd, number.parse().map_err(|_| "invalid issue number")?, diff --git a/oxa/oxa-cli/tests/work_cli.rs b/oxa/oxa-cli/tests/work_cli.rs index fa28e7b54..ec6279eef 100644 --- a/oxa/oxa-cli/tests/work_cli.rs +++ b/oxa/oxa-cli/tests/work_cli.rs @@ -188,3 +188,83 @@ fn setup_failure_records_blocked_and_keeps_existing_branch() { assert_eq!(record["outcome"], "blocked", "{record}"); assert!(record["detail"].as_str().unwrap().contains("already exists")); } + +#[test] +fn child_can_create_a_commit_with_the_real_sandbox() { + let env = TestEnv::new(); + setup(&env, "[]"); + env.write( + "home/.oxa/agent/settings.json", + r#"{"defaultProjectTrust":"always"}"#, + ); + let record = run( + &env, + vec![ + ScriptTurn::tool("write", "write", r#"{"path":"answer.txt","content":"committed"}"#), + ScriptTurn::tool( + "commit", + "bash", + r#"{"command":"git add answer.txt && git -c user.name=Test -c user.email=test@example.invalid commit -m task"}"#, + ), + ScriptTurn::text("done"), + ], + ); + assert_eq!(record["outcome"], "done", "{record}"); + let tree = Path::new(record["worktree"].as_str().unwrap()); + let status = Command::new("git") + .args(["status", "--porcelain"]) + .current_dir(tree) + .env_clear() + .envs(env.envs("http://127.0.0.1:1")) + .output() + .unwrap(); + assert!(status.status.success()); + assert!( + status.stdout.is_empty(), + "commit must persist: {}", + String::from_utf8_lossy(&status.stdout) + ); + let subject = Command::new("git") + .args(["log", "-1", "--format=%s"]) + .current_dir(tree) + .env_clear() + .envs(env.envs("http://127.0.0.1:1")) + .output() + .unwrap(); + assert_eq!(String::from_utf8_lossy(&subject.stdout).trim(), "task"); +} +#[test] +fn offline_issue_input_never_spawns_gh() { + use std::os::unix::fs::PermissionsExt; + for setting in [false, true] { + let env = TestEnv::new(); + setup(&env, "[]"); + let gh = env.write( + "tmp/gh", + "#!/bin/sh\nprintf invoked > \"$HOME/gh-invoked\"\nexit 7\n", + ); + std::fs::set_permissions(&gh, std::fs::Permissions::from_mode(0o755)).unwrap(); + if setting { + env.write("home/.oxa/agent/settings.json", r#"{"oxa":{"offline":true}}"#); + } + let mut cmd = Command::new(env!("CARGO_BIN_EXE_oxa")); + cmd.args(["work", "--issue", "42", "--model", "fake"]) + .current_dir(env.work().join("project")) + .env_clear() + .envs(env.envs("http://127.0.0.1:1")) + .env( + "PATH", + format!("{}:{}", env.tmp().display(), std::env::var("PATH").unwrap()), + ); + if !setting { + cmd.env("OXA_OFFLINE", "1"); + } + let out = cmd.output().unwrap(); + assert_eq!(out.status.code(), Some(2)); + assert!( + !env.home().join("gh-invoked").exists(), + "offline lookup ran gh, setting={setting}" + ); + assert!(String::from_utf8_lossy(&out.stderr).contains("offline")); + } +} diff --git a/oxa/oxa-work/src/lib.rs b/oxa/oxa-work/src/lib.rs index 5f1dbd487..4ea8a1551 100644 --- a/oxa/oxa-work/src/lib.rs +++ b/oxa/oxa-work/src/lib.rs @@ -173,7 +173,8 @@ pub fn run_task(repo: &Path, binary: &Path, task: &Task) -> Result { &root, &["rev-parse", "--path-format=absolute", "--git-common-dir"], ))?; - let storage = PathBuf::from(common).join("oxa-work"); + let common = PathBuf::from(common); + let storage = common.join("oxa-work"); fs::create_dir_all(&storage).map_err(|e| e.to_string())?; let lock_path = storage.join(format!("{}.lock", task.id)); let _lock_file = fs::OpenOptions::new() @@ -186,7 +187,20 @@ pub fn run_task(repo: &Path, binary: &Path, task: &Task) -> Result { if receipt.exists() { return Err("task already has a receipt; retained for inspection".into()); } - let tree = storage.join(&task.id); + // The common git directory must not be an ancestor of the child cwd: the sandbox + // deliberately refuses writable git binds with that layout. + let repo_dir = if common.file_name().is_some_and(|name| name == ".git") { + common.parent().ok_or("git directory has no parent")? + } else { + &common + }; + let parent = repo_dir + .parent() + .ok_or("repository has no parent for worktrees")?; + let name = repo_dir.file_name().ok_or("repository has no directory name")?; + let trees = parent.join(".oxa-worktrees").join(name); + fs::create_dir_all(&trees).map_err(|e| e.to_string())?; + let tree = trees.join(&task.id); let mut record = Record { id: task.id.clone(), branch: task.branch.clone(), From 1e3917272e6b67660b34ae7f9795a55cad9b3c11 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Oscar=20Nordstr=C3=B6m?= <13300531+n0rpan@users.noreply.github.com> Date: Sun, 15 Nov 2026 16:39:53 +0000 Subject: [PATCH 04/11] Preserve offline policy and continue work batches after task failures --- oxa/docs/work.md | 9 +++- oxa/oxa-cli/src/args.rs | 21 +++++---- oxa/oxa-cli/src/work_cmd.rs | 3 +- oxa/oxa-cli/tests/work_cli.rs | 82 +++++++++++++++++++++++++++++++++++ oxa/oxa-work/src/lib.rs | 37 +++++++++++----- 5 files changed, 130 insertions(+), 22 deletions(-) diff --git a/oxa/docs/work.md b/oxa/docs/work.md index ed74c8ab8..a04b88a26 100644 --- a/oxa/docs/work.md +++ b/oxa/docs/work.md @@ -13,7 +13,8 @@ IDs and branches must be unique; branches must be new. For a GitHub issue use authenticated `gh` CLI to fetch the issue title and body. Issue lookup is refused when the environment or user settings enable offline mode. -Each task runs a child `oxa -p` with its model. Normal agent permission, trust and +Each task runs a child `oxa -p` with its model. The installed offline policy, +including a parent `--offline` flag, is passed to every child. Normal agent permission, trust and sandbox rules apply. Configure project trust before unattended use. The runner executes the base version of `.oxa/settings.json`'s `done` commands outside the agent after it exits, even without edits. These are trusted project shell commands: @@ -25,7 +26,11 @@ Failed acceptance output goes to one additional child run with the original prom then acceptance runs once more. JSON lines report `done`, `nothing_to_do` (no commits or file changes), `red` (checks still fail), or `blocked` (setup or agent execution failed). Exit codes are 0 for success, 1 if any task is red or blocked, -and 2 for invalid input or runner errors. +and 2 for invalid input or output errors. A task setup failure produces a blocked +JSON line and does not skip later tasks. If a task cannot be locked or already has +a receipt, its existing state is preserved; a pre-worktree failure has an empty +`worktree` in the result. Locks use kernel ownership, so an abandoned lock file +after process death does not permanently block a task. Worktrees and uncommitted changes remain in `.oxa-worktrees//` beside the repository (or the separate git directory). Result receipts live inside diff --git a/oxa/oxa-cli/src/args.rs b/oxa/oxa-cli/src/args.rs index ecf283560..b4a6942ed 100644 --- a/oxa/oxa-cli/src/args.rs +++ b/oxa/oxa-cli/src/args.rs @@ -458,19 +458,24 @@ fn positional(a: &mut Args, word: &str) { /// `unsupported_in_oxa`. pub fn parse_args(argv: &[String], ext_flags: &[FlagSpec]) -> Result { let mut a = Args::default(); - if let Some(first) = argv.first() { - if !first.starts_with('-') && !first.starts_with('@') { - if let Some(sub) = subcommand(first, &argv[1..])? { - a.subcommand = Some(sub); - return Ok(a); - } - } - } let mut i = 0; let mut stop = false; while i < argv.len() { let arg = argv[i].as_str(); i += 1; + if !stop + && !a.print + && a.mode.is_none() + && !arg.starts_with('-') + && !arg.starts_with('@') + && a.messages.is_empty() + && a.files.is_empty() + { + if let Some(sub) = subcommand(arg, &argv[i..])? { + a.subcommand = Some(sub); + break; + } + } if stop || !arg.starts_with('-') { positional(&mut a, arg); continue; diff --git a/oxa/oxa-cli/src/work_cmd.rs b/oxa/oxa-cli/src/work_cmd.rs index af2d67257..4afd4b9d1 100644 --- a/oxa/oxa-cli/src/work_cmd.rs +++ b/oxa/oxa-cli/src/work_cmd.rs @@ -20,7 +20,8 @@ pub(crate) fn run(args: &[String], cwd: &Path, out: &mut dyn Write, err: &mut dy let binary: PathBuf = std::env::current_exe().map_err(|e| e.to_string())?; let mut code = 0; for task in tasks { - let record = oxa_work::run_task(cwd, &binary, &task)?; + let record = oxa_work::run_task_with_policy(cwd, &binary, &task, oxa_proto::offline()) + .unwrap_or_else(|detail| oxa_work::blocked_record(&task, detail)); if matches!( record.outcome, oxa_work::Outcome::Red | oxa_work::Outcome::Blocked diff --git a/oxa/oxa-cli/tests/work_cli.rs b/oxa/oxa-cli/tests/work_cli.rs index ec6279eef..3cc488928 100644 --- a/oxa/oxa-cli/tests/work_cli.rs +++ b/oxa/oxa-cli/tests/work_cli.rs @@ -268,3 +268,85 @@ fn offline_issue_input_never_spawns_gh() { assert!(String::from_utf8_lossy(&out.stderr).contains("offline")); } } + +#[test] +fn command_line_offline_policy_reaches_child_agent() { + let env = TestEnv::new(); + setup(&env, "[]"); + env.write( + "work/tasks.json", + r#"[{"id":"test","branch":"agent/test","model":"cloud-model","prompt":"go"}]"#, + ); + let server = FakeServer::start( + vec![ScriptTurn::text("done")], + FakeOpts { + model: "cloud-model".into(), + remote: Some("openrouter"), + models: vec![oxa_fake::FakeModel { + alias: "cloud-model".into(), + cap: 64000, + max_output: Some(4096), + caps: None, + }], + ..FakeOpts::default() + }, + ) + .unwrap(); + let out = Command::new(env!("CARGO_BIN_EXE_oxa")) + .args(["--offline", "work", "../tasks.json"]) + .current_dir(env.work().join("project")) + .env_clear() + .envs(env.envs(&server.url())) + .output() + .unwrap(); + let record: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap(); + assert_eq!(record["outcome"], "blocked", "{record}"); + assert!( + record["detail"].as_str().unwrap().contains("offline mode is on"), + "{record}" + ); + assert!( + server.requests().is_empty(), + "no chat reached even the mock remote" + ); +} +#[test] +fn batch_reports_one_task_error_and_runs_later_tasks() { + let env = TestEnv::new(); + setup(&env, "[]"); + env.write("work/project/.git/oxa-work/test.json", "{}"); + env.write("work/tasks.json", r#"[{"id":"test","branch":"agent/test","model":"fake","prompt":"go"},{"id":"next","branch":"agent/next","model":"fake","prompt":"go"}]"#); + let server = FakeServer::start(vec![ScriptTurn::text("done")], FakeOpts::default()).unwrap(); + let out = Command::new(env!("CARGO_BIN_EXE_oxa")) + .args(["work", "../tasks.json"]) + .current_dir(env.work().join("project")) + .env_clear() + .envs(env.envs(&server.url())) + .output() + .unwrap(); + assert_eq!( + out.status.code(), + Some(1), + "{}", + String::from_utf8_lossy(&out.stderr) + ); + let rows: Vec = String::from_utf8_lossy(&out.stdout) + .lines() + .map(|line| serde_json::from_str(line).unwrap()) + .collect(); + assert_eq!(rows.len(), 2); + assert_eq!(rows[0]["outcome"], "blocked"); + assert_eq!(rows[1]["outcome"], "nothing_to_do"); + assert_eq!( + std::fs::read_to_string(env.work().join("project/.git/oxa-work/test.json")).unwrap(), + "{}" + ); +} +#[test] +fn abandoned_lock_file_does_not_block_a_task() { + let env = TestEnv::new(); + setup(&env, "[]"); + env.write("work/project/.git/oxa-work/test.lock", ""); + let record = run(&env, vec![ScriptTurn::text("done")]); + assert_eq!(record["outcome"], "nothing_to_do", "{record}"); +} diff --git a/oxa/oxa-work/src/lib.rs b/oxa/oxa-work/src/lib.rs index 4ea8a1551..2a862c1e6 100644 --- a/oxa/oxa-work/src/lib.rs +++ b/oxa/oxa-work/src/lib.rs @@ -150,21 +150,30 @@ fn acceptance(root: &Path, commands: &[String]) -> Result { } Ok(failures) } -fn agent(binary: &Path, root: &Path, task: &Task, prompt: &str) -> Result<()> { +fn agent(binary: &Path, root: &Path, task: &Task, prompt: &str, offline: bool) -> Result<()> { let mut c = Command::new(binary); c.current_dir(root) - .args(["-p", "--model", &task.model, "--no-session", "--", prompt]); + .args(["-p", "--model", &task.model, "--no-session"]); + if offline { + c.arg("--offline"); + } + c.args(["--", prompt]); checked(c).map(|_| ()) } -struct TaskLock(PathBuf); -impl Drop for TaskLock { - fn drop(&mut self) { - let _ = fs::remove_file(&self.0); +pub fn blocked_record(task: &Task, detail: String) -> Record { + Record { + id: task.id.clone(), + branch: task.branch.clone(), + worktree: PathBuf::new(), + outcome: Outcome::Blocked, + detail, } } - pub fn run_task(repo: &Path, binary: &Path, task: &Task) -> Result { + run_task_with_policy(repo, binary, task, false) +} +pub fn run_task_with_policy(repo: &Path, binary: &Path, task: &Task, offline: bool) -> Result { validate(task)?; let root = checked(git(repo, &["rev-parse", "--show-toplevel"]))?; let root = PathBuf::from(root); @@ -177,12 +186,17 @@ pub fn run_task(repo: &Path, binary: &Path, task: &Task) -> Result { let storage = common.join("oxa-work"); fs::create_dir_all(&storage).map_err(|e| e.to_string())?; let lock_path = storage.join(format!("{}.lock", task.id)); - let _lock_file = fs::OpenOptions::new() + let lock_file = fs::OpenOptions::new() .write(true) - .create_new(true) + .create(true) + .truncate(false) .open(&lock_path) .map_err(|e| format!("cannot lock task {}: {e}", task.id))?; - let _lock = TaskLock(lock_path); + lock_file + .try_lock() + .map_err(|e| format!("task {} is already running: {e}", task.id))?; + // Keep the inode so a crashed runner leaves no stale ownership and concurrent + // runners cannot acquire locks on two different files with the same name. let receipt = storage.join(format!("{}.json", task.id)); if receipt.exists() { return Err("task already has a receipt; retained for inspection".into()); @@ -220,7 +234,7 @@ pub fn run_task(repo: &Path, binary: &Path, task: &Task) -> Result { let tree = tree.canonicalize().map_err(|e| e.to_string())?; let initial = checked(git(&tree, &["rev-parse", "HEAD"]))?; let commands = done_commands(&tree)?; - let first_agent = agent(binary, &tree, task, &task.prompt); + let first_agent = agent(binary, &tree, task, &task.prompt, offline); let failures = acceptance(&tree, &commands)?; if !failures.is_empty() { let repair_agent = agent( @@ -231,6 +245,7 @@ pub fn run_task(repo: &Path, binary: &Path, task: &Task) -> Result { "{}\n\nExternal acceptance checks failed. Repair once:\n{failures}", task.prompt ), + offline, ); let failures = acceptance(&tree, &commands)?; if !failures.is_empty() { From d7ab5cfa31ae22b3ef4da2bc606e5cd2c151c74f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Oscar=20Nordstr=C3=B6m?= <13300531+n0rpan@users.noreply.github.com> Date: Sun, 15 Nov 2026 17:54:33 +0000 Subject: [PATCH 05/11] Keep prompt parsing stable and retain agent failure causes (#333) --- oxa/oxa-cli/src/args.rs | 9 +---- oxa/oxa-cli/tests/c12_argument_parsing.rs | 47 +++++++++++++++++++++++ oxa/oxa-cli/tests/work_cli.rs | 15 ++++++++ oxa/oxa-work/src/lib.rs | 3 ++ 4 files changed, 66 insertions(+), 8 deletions(-) diff --git a/oxa/oxa-cli/src/args.rs b/oxa/oxa-cli/src/args.rs index b4a6942ed..0ca62ae99 100644 --- a/oxa/oxa-cli/src/args.rs +++ b/oxa/oxa-cli/src/args.rs @@ -463,14 +463,7 @@ pub fn parse_args(argv: &[String], ext_flags: &[FlagSpec]) -> Result Date: Mon, 16 Nov 2026 06:33:25 +0000 Subject: [PATCH 06/11] Sandbox runner acceptance and consume the worker result contract (#333) --- oxa/docs/work.md | 23 ++- oxa/oxa-cli/src/dispatch.rs | 235 ++++++++++++++++------------- oxa/oxa-cli/src/lib.rs | 1 + oxa/oxa-cli/src/work_checks.rs | 96 ++++++++++++ oxa/oxa-cli/src/work_cmd.rs | 71 ++++++++- oxa/oxa-cli/tests/work_cli.rs | 262 +++++++++++++++++++++++++++++++-- oxa/oxa-work/src/lib.rs | 159 ++++++++++++-------- oxa/oxa-work/src/worker.rs | 185 +++++++++++++++++++++++ 8 files changed, 848 insertions(+), 184 deletions(-) create mode 100644 oxa/oxa-cli/src/work_checks.rs create mode 100644 oxa/oxa-work/src/worker.rs diff --git a/oxa/docs/work.md b/oxa/docs/work.md index a04b88a26..15b6bb390 100644 --- a/oxa/docs/work.md +++ b/oxa/docs/work.md @@ -13,17 +13,23 @@ IDs and branches must be unique; branches must be new. For a GitHub issue use authenticated `gh` CLI to fetch the issue title and body. Issue lookup is refused when the environment or user settings enable offline mode. -Each task runs a child `oxa -p` with its model. The installed offline policy, +Each task runs a child `oxa --mode=json` with its model and a saved session. The installed offline policy, including a parent `--offline` flag, is passed to every child. Normal agent permission, trust and sandbox rules apply. Configure project trust before unattended use. The runner executes the base version of `.oxa/settings.json`'s `done` commands outside the -agent after it exits, even without edits. These are trusted project shell commands: -invoking `work` authorizes their execution as your user. `in subdirectory: command` -runs in that worktree subdirectory; escaping it with the directory is rejected. +agent after it exits, even without edits. The source project must pass the existing +trust and executable-content approval before a task starts. Invoking `work` does +not approve an untrusted project. Acceptance runs in the normal bwrap sandbox; +missing or unusable bwrap blocks the task. Each check has the same ten-minute limit +as agent-internal done checks. `in subdirectory: command` selects a folder inside +that sandbox; escaping the worktree is rejected. Agent-internal done checks may also run when the project is trusted. -Failed acceptance output goes to one additional child run with the original prompt, -then acceptance runs once more. JSON lines report `done`, `nothing_to_do` (no +The runner reads the child's exit code, terminal `oxa_result` and session header, +without retaining its event stream. A blocked, failed or interrupted worker remains +blocked and does not consume a repair attempt. Failed acceptance after a successful +worker continues that same saved session once, then acceptance runs once more. +JSON lines include the worker result and session ID and report `done`, `nothing_to_do` (no commits or file changes), `red` (checks still fail), or `blocked` (setup or agent execution failed). Exit codes are 0 for success, 1 if any task is red or blocked, and 2 for invalid input or output errors. A task setup failure produces a blocked @@ -33,8 +39,9 @@ a receipt, its existing state is preserved; a pre-worktree failure has an empty after process death does not permanently block a task. Worktrees and uncommitted changes remain in `.oxa-worktrees//` -beside the repository (or the separate git directory). Result receipts live inside -the common git directory at `oxa-work/.json`. Worktrees stay outside that git +beside the repository (or the separate git directory). Private result receipts and +locks live under `~/.oxa/agent/work//` (or the configured agent +directory), outside the worker's writable Git bind. Worktrees stay outside that git directory so the normal sandbox can bind git objects and refs for commits. No automatic cleanup, commit, push, PR creation or continuation is implemented yet. Inspect retained work before removing it with `git worktree remove`. Review task prompts diff --git a/oxa/oxa-cli/src/dispatch.rs b/oxa/oxa-cli/src/dispatch.rs index f0473e717..ebf22b01f 100644 --- a/oxa/oxa-cli/src/dispatch.rs +++ b/oxa/oxa-cli/src/dispatch.rs @@ -170,7 +170,9 @@ pub fn run(argv: &[String], env: &Env, io: Stdio) -> i32 { Err(e) => return report(&mut *stderr, &e), }; let result = match sub { - Subcommand::Work(words) => return crate::work_cmd::run(&words, &cwd, &mut *stdout, &mut *stderr), + Subcommand::Work(words) => { + return crate::work_cmd::run(&words, &cwd, env, &dirs, &mut *stdout, &mut *stderr) + } Subcommand::Mcp(words) => run_mcp(&words, &dirs, &cwd, &mut *stdout, &mut *stderr), Subcommand::Pkg(verb, words) => run_pkg(&verb, &words, &dirs, &cwd, &mut *stdout, &mut *stderr), Subcommand::Config(words) => run_config(&words, &dirs, &cwd, &mut *stdout), @@ -473,112 +475,16 @@ fn prepare( let child = crate::child::ChildIdentity::from_env(env, &mut notices); notices.extend(crate::netguard::endpoint_notice(&endpoint.base_url)); - // Trust: the user's own settings decide the default; project settings load only when the - // project is trusted. - let user_settings = Settings::load(dirs, cwd, false); - let default = match user_settings.string("defaultProjectTrust").as_deref() { - Some("always") => DefaultTrust::Trust, - Some("never") => DefaultTrust::Untrusted, - _ => DefaultTrust::Ask, - }; let gated = gated_resources(cwd); - // `OXA_TRUST_PROJECT=1` is `--approve` for the trust decision, for unattended runs; - // an explicit `-na` still wins. - let approve = a - .approve - .or_else(|| matches!(env.get("OXA_TRUST_PROJECT"), Some("1" | "true")).then_some(true)); - let mut trust_store = TrustStore::load(&dirs.trust_file()); - // SEC-003 / EXT-008: the user-level and `-e` extensions answer `project_trust` before the - // saved decision and the default (pi's `resolveProjectTrusted`). - let extension = if approve.is_none() && !gated.is_empty() { - extension_trust(a, dirs, cwd, &user_settings, &mut trust_store, &mut notices) - } else { - None - }; - let interactive = mode == RunMode::Interactive && stdin_is_tty && stdout_is_tty; - let saved = trust_store.lookup(cwd); - let outcome = resolve_trust(&TrustInputs { - flag: approve, - extension, - saved, - default, - interactive, - has_gated: !gated.is_empty(), - }); - // B4: the user answered the trust question in this start (it approves the content too). - let mut asked_now = false; - let trusted = match outcome { - TrustOutcome::Trusted => true, - TrustOutcome::Untrusted => false, - TrustOutcome::AskUser => { - // The trust dialog (D10) on the terminal, before the session exists. A dismissed - // question leaves the project untrusted for this run and is asked again next time. - let (keymap, _) = Keymap::load(dirs); - let choice = ask_trust_interactive(env.pairs(), &keymap, &cwd.display().to_string(), &gated)?; - asked_now = true; - let file = dirs.trust_file(); - match choice { - Some(TrustChoice::Trust) => { - trust_store.save(&file, cwd, true)?; - true - } - Some(TrustChoice::TrustParent) => { - trust_store.save(&file, cwd.parent().unwrap_or(cwd), true)?; - true - } - Some(TrustChoice::NoTrust) => { - trust_store.save(&file, cwd, false)?; - false - } - Some(TrustChoice::Skip) | None => { - notices.push(( - Level::Warning, - "the project is not trusted for this run; /trust saves a decision".to_string(), - )); - false - } - } - } - }; - // B4: what runs outside the sandbox loads only as the user approved it (content hashes). - let trusted = if trusted && !gated.is_empty() { - crate::approval::check(crate::approval::Check { - env, - dirs, - cwd, - store: &mut trust_store, - via_flag: approve == Some(true), - via_default: extension.is_none() && saved.is_none() && default == DefaultTrust::Trust, - asked_now, - interactive, - notices: &mut notices, - })? - } else { - trusted - }; - // #201: a project trusted by a saved decision gets its approval baseline now (also with - // no project config yet), before any tool runs: `.oxa` / `.agents` content the session - // creates is then new at the next start and goes through the normal approval. - if trusted && saved == Some(true) { - trust_store.record_baseline(&dirs.trust_file(), cwd)?; - } - if !trusted && !gated.is_empty() { - notices.push(( - Level::Warning, - format!( - "project resources were skipped (not trusted): {}", - gated.join(", ") - ), - )); - } - // `done` is a project-only key in practice: an untrusted project's list is never merged, - // so say that its checks will not run. - if !trusted && Settings::project_declares_done(dirs, cwd) { - notices.push(( - Level::Warning, - "done checks in .oxa/settings.json were not run: project is not trusted".to_string(), - )); - } + let trusted = project_trusted( + a, + env, + dirs, + cwd, + &gated, + mode == RunMode::Interactive && stdin_is_tty && stdout_is_tty, + &mut notices, + )?; let mut settings = child.apply(Settings::load(dirs, cwd, trusted)); // CLI-045 (pi cli.md): `--verbose` overrides `quietStartup` for this run (in memory only). if a.verbose { @@ -829,6 +735,123 @@ fn prepare( } /// The resource discovery options of the flags. +/// The same project trust and executable-content approval for sessions and workers. +pub(crate) fn project_trusted( + a: &Args, + env: &Env, + dirs: &Dirs, + cwd: &Path, + gated: &[String], + interactive: bool, + notices: &mut Vec<(Level, String)>, +) -> Result { + // Trust: the user's own settings decide the default; project settings load only when the + // project is trusted. + let user_settings = Settings::load(dirs, cwd, false); + let default = match user_settings.string("defaultProjectTrust").as_deref() { + Some("always") => DefaultTrust::Trust, + Some("never") => DefaultTrust::Untrusted, + _ => DefaultTrust::Ask, + }; + // `OXA_TRUST_PROJECT=1` is `--approve` for the trust decision, for unattended runs; + // an explicit `-na` still wins. + let approve = a + .approve + .or_else(|| matches!(env.get("OXA_TRUST_PROJECT"), Some("1" | "true")).then_some(true)); + let mut trust_store = TrustStore::load(&dirs.trust_file()); + // SEC-003 / EXT-008: the user-level and `-e` extensions answer `project_trust` before the + // saved decision and the default (pi's `resolveProjectTrusted`). + let extension = if approve.is_none() && !gated.is_empty() { + extension_trust(a, dirs, cwd, &user_settings, &mut trust_store, notices) + } else { + None + }; + let saved = trust_store.lookup(cwd); + let outcome = resolve_trust(&TrustInputs { + flag: approve, + extension, + saved, + default, + interactive, + has_gated: !gated.is_empty(), + }); + // B4: the user answered the trust question in this start (it approves the content too). + let mut asked_now = false; + let trusted = match outcome { + TrustOutcome::Trusted => true, + TrustOutcome::Untrusted => false, + TrustOutcome::AskUser => { + // The trust dialog (D10) on the terminal, before the session exists. A dismissed + // question leaves the project untrusted for this run and is asked again next time. + let (keymap, _) = Keymap::load(dirs); + let choice = ask_trust_interactive(env.pairs(), &keymap, &cwd.display().to_string(), gated)?; + asked_now = true; + let file = dirs.trust_file(); + match choice { + Some(TrustChoice::Trust) => { + trust_store.save(&file, cwd, true)?; + true + } + Some(TrustChoice::TrustParent) => { + trust_store.save(&file, cwd.parent().unwrap_or(cwd), true)?; + true + } + Some(TrustChoice::NoTrust) => { + trust_store.save(&file, cwd, false)?; + false + } + Some(TrustChoice::Skip) | None => { + notices.push(( + Level::Warning, + "the project is not trusted for this run; /trust saves a decision".to_string(), + )); + false + } + } + } + }; + // B4: what runs outside the sandbox loads only as the user approved it (content hashes). + let trusted = if trusted && !gated.is_empty() { + crate::approval::check(crate::approval::Check { + env, + dirs, + cwd, + store: &mut trust_store, + via_flag: approve == Some(true), + via_default: extension.is_none() && saved.is_none() && default == DefaultTrust::Trust, + asked_now, + interactive, + notices, + })? + } else { + trusted + }; + // #201: a project trusted by a saved decision gets its approval baseline now (also with + // no project config yet), before any tool runs: `.oxa` / `.agents` content the session + // creates is then new at the next start and goes through the normal approval. + if trusted && saved == Some(true) { + trust_store.record_baseline(&dirs.trust_file(), cwd)?; + } + if !trusted && !gated.is_empty() { + notices.push(( + Level::Warning, + format!( + "project resources were skipped (not trusted): {}", + gated.join(", ") + ), + )); + } + // `done` is a project-only key in practice: an untrusted project's list is never merged, + // so say that its checks will not run. + if !trusted && Settings::project_declares_done(dirs, cwd) { + notices.push(( + Level::Warning, + "done checks in .oxa/settings.json were not run: project is not trusted".to_string(), + )); + } + Ok(trusted) +} + fn discover_opts(a: &Args, dirs: &Dirs, cwd: &Path, trusted: bool) -> Result { Ok(DiscoverOpts { trusted, diff --git a/oxa/oxa-cli/src/lib.rs b/oxa/oxa-cli/src/lib.rs index e632f42a9..c0a9fb5be 100644 --- a/oxa/oxa-cli/src/lib.rs +++ b/oxa/oxa-cli/src/lib.rs @@ -32,6 +32,7 @@ mod report_cmd; mod sandbox_layout; mod themes; mod wipe_cmd; +mod work_checks; mod work_cmd; pub use args::{parse_args, usage_text, ApiKey, Args, ModeArg, Subcommand}; diff --git a/oxa/oxa-cli/src/work_checks.rs b/oxa/oxa-cli/src/work_checks.rs new file mode 100644 index 000000000..f33721218 --- /dev/null +++ b/oxa/oxa-cli/src/work_checks.rs @@ -0,0 +1,96 @@ +//! Deterministic acceptance supervisor; no engine or model is constructed here. +use oxa_config::{Dirs, Env, Settings}; +use oxa_proto::{CancelToken, ExecSpec}; +use oxa_sandbox::Bwrap; +use oxa_work::AcceptanceRequest; +use std::io::Write; +use std::path::Path; +use std::sync::Arc; + +pub(crate) fn run( + request: &str, + cwd: &Path, + env: &Env, + dirs: &Dirs, + err: &mut dyn Write, +) -> Result { + let request: AcceptanceRequest = serde_json::from_str(request).map_err(|e| e.to_string())?; + let source = request.source.canonicalize().map_err(|e| e.to_string())?; + if !crate::work_cmd::trusted(&source, env, dirs)? { + return Err("acceptance source project is not trusted".into()); + } + let root = cwd.canonicalize().map_err(|e| e.to_string())?; + let settings = Settings::load(dirs, &source, true); + let shell = oxa_tools::ShellConfig { + shell_path: settings.shell_path(&dirs.home), + command_prefix: settings.shell_command_prefix(), + }; + let mut b = Bwrap::detect(env.get("PATH").unwrap_or(""), &dirs.home).map_err(|e| e.to_string())?; + b.layout = crate::sandbox_layout::layout(env, dirs, &root, false, &mut vec![]); + let sandbox = crate::netguard::with_net(Arc::new(b.with_git_dirs(&root)), &settings); + sandbox.check().map_err(|e| e.to_string())?; + let mut failed = false; + let mut diagnostics = Vec::new(); + for entry in request.commands { + let (directory, text) = match entry.strip_prefix("in ").and_then(|s| s.split_once(':')) { + Some((dir, command)) => (Some(dir.trim()), command.trim()), + None => (None, entry.as_str()), + }; + if text.is_empty() { + return Err("empty acceptance command".into()); + } + let command = shell.command(text)?; + // Bind the original workspace, then select a child inside that view. A + // symlink swap cannot turn an outside directory into the writable root. + let command = if let Some(directory) = directory { + let child = root.join(directory).canonicalize().map_err(|e| e.to_string())?; + let relative = child + .strip_prefix(&root) + .map_err(|_| "done directory escapes worktree")?; + let dir = if relative.as_os_str().is_empty() { + Path::new(".") + } else { + relative + }; + format!( + "cd -- '{}' || exit 111\n{command}", + dir.to_string_lossy().replace('\'', "'\\''") + ) + } else { + command + }; + let spec = ExecSpec { + command, + cwd: root.clone(), + writable: true, + net: sandbox.network(), + timeout_s: Some(600), + env: vec![("AI_AGENT".into(), "oxa".into())], + }; + let mut tail = Vec::new(); + let result = sandbox.run_streaming(&spec, &CancelToken::default(), &mut |bytes| { + keep_tail(&mut tail, bytes, 8192); + }); + if result.exit != Some(0) || result.timed_out { + failed = true; + let header = format!("{entry}: exit {:?}, timeout {}\n", result.exit, result.timed_out); + keep_tail(&mut diagnostics, header.as_bytes(), 16384); + keep_tail(&mut diagnostics, &tail, 16384); + } + } + if failed { + err.write_all(&diagnostics).map_err(|e| e.to_string())?; + } + Ok(i32::from(failed)) +} + +fn keep_tail(tail: &mut Vec, bytes: &[u8], cap: usize) { + if bytes.len() >= cap { + tail.clear(); + tail.extend_from_slice(&bytes[bytes.len() - cap..]); + } else { + let discard = (tail.len() + bytes.len()).saturating_sub(cap); + tail.drain(..discard); + tail.extend_from_slice(bytes); + } +} diff --git a/oxa/oxa-cli/src/work_cmd.rs b/oxa/oxa-cli/src/work_cmd.rs index 4afd4b9d1..8d3e76853 100644 --- a/oxa/oxa-cli/src/work_cmd.rs +++ b/oxa/oxa-cli/src/work_cmd.rs @@ -1,8 +1,35 @@ +use oxa_config::{Dirs, Env}; +use sha2::{Digest, Sha256}; use std::io::Write; use std::path::{Path, PathBuf}; -pub(crate) fn run(args: &[String], cwd: &Path, out: &mut dyn Write, err: &mut dyn Write) -> i32 { +pub(crate) fn trusted(cwd: &Path, env: &Env, dirs: &Dirs) -> Result { + crate::dispatch::project_trusted( + &crate::Args::default(), + env, + dirs, + cwd, + &oxa_perm::gated_resources(cwd), + false, + &mut vec![], + ) + .map_err(|e| e.to_string()) +} + +pub(crate) fn run( + args: &[String], + cwd: &Path, + env: &Env, + dirs: &Dirs, + out: &mut dyn Write, + err: &mut dyn Write, +) -> i32 { let result = (|| -> Result { + if let [flag, request] = args { + if flag == "--acceptance" { + return crate::work_checks::run(request, cwd, env, dirs, err); + } + } let tasks = match args { [file] if !file.starts_with('-') => oxa_work::read_tasks(&cwd.join(file))?, [flag, number, model_flag, model] if flag == "--issue" && model_flag == "--model" => { @@ -18,10 +45,48 @@ pub(crate) fn run(args: &[String], cwd: &Path, out: &mut dyn Write, err: &mut dy _ => return Err("usage: oxa work | --issue N --model MODEL".into()), }; let binary: PathBuf = std::env::current_exe().map_err(|e| e.to_string())?; + let output = std::process::Command::new("git") + .current_dir(cwd) + .args(["rev-parse", "--show-toplevel"]) + .output() + .map_err(|e| e.to_string())?; + if !output.status.success() { + return Err("oxa work requires a Git repository".into()); + } + let root = PathBuf::from(String::from_utf8_lossy(&output.stdout).trim()) + .canonicalize() + .map_err(|e| e.to_string())?; + let is_trusted = trusted(&root, env, dirs)?; + let common = std::process::Command::new("git") + .current_dir(&root) + .args(["rev-parse", "--path-format=absolute", "--git-common-dir"]) + .output() + .map_err(|e| e.to_string())?; + if !common.status.success() { + return Err("cannot resolve runner repository".into()); + } + let common = PathBuf::from(String::from_utf8_lossy(&common.stdout).trim()) + .canonicalize() + .map_err(|e| e.to_string())?; + let key = Sha256::digest(common.as_os_str().as_encoded_bytes()) + .iter() + .map(|b| format!("{b:02x}")) + .collect::(); + let policy = oxa_work::RunPolicy { + offline: oxa_proto::offline(), + storage: dirs.agent_dir.join("work").join(key), + }; let mut code = 0; for task in tasks { - let record = oxa_work::run_task_with_policy(cwd, &binary, &task, oxa_proto::offline()) - .unwrap_or_else(|detail| oxa_work::blocked_record(&task, detail)); + let record = if is_trusted { + oxa_work::run_task_with_policy(&root, &binary, &task, &policy) + .unwrap_or_else(|detail| oxa_work::blocked_record(&task, detail)) + } else { + oxa_work::blocked_record( + &task, + "source project is not trusted; approve it before unattended work".into(), + ) + }; if matches!( record.outcome, oxa_work::Outcome::Red | oxa_work::Outcome::Blocked diff --git a/oxa/oxa-cli/tests/work_cli.rs b/oxa/oxa-cli/tests/work_cli.rs index 70ee5b2ee..6314f6c9c 100644 --- a/oxa/oxa-cli/tests/work_cli.rs +++ b/oxa/oxa-cli/tests/work_cli.rs @@ -1,6 +1,19 @@ //! Real child oxa with fake engine and local bare git remote; no network. use oxa_fake::{FakeOpts, FakeServer, ScriptTurn, TestEnv}; -use std::{path::Path, process::Command}; +use std::{ + path::{Path, PathBuf}, + process::Command, +}; + +fn storage(env: &TestEnv) -> PathBuf { + use sha2::{Digest, Sha256}; + let common = env.work().join("project/.git").canonicalize().unwrap(); + let key: String = Sha256::digest(common.as_os_str().as_encoded_bytes()) + .iter() + .map(|b| format!("{b:02x}")) + .collect(); + env.agent_dir().join("work").join(key) +} fn git(env: &TestEnv, dir: &Path, args: &[&str]) { let out = Command::new("git") .args(args) @@ -27,6 +40,11 @@ fn setup(env: &TestEnv, done: &str) { git(env, &project, &["commit", "-m", "fixture"]); git(env, &project, &["remote", "add", "origin", "../remote.git"]); git(env, &project, &["push", "origin", "main"]); + // Approve the source repository only. The separate worker worktree still + // uses the normal project-resource decision of its own child session. + oxa_perm::TrustStore::default() + .save(&env.agent_dir().join("trust.json"), &project, true) + .unwrap(); env.write( "work/tasks.json", r#"[{"id":"test","branch":"agent/test","model":"fake","prompt":"Finish task"}]"#, @@ -69,7 +87,7 @@ fn external_checks_run_without_edits_and_retain_worktree() { assert_eq!(record["outcome"], "done", "{record}"); let tree = Path::new(record["worktree"].as_str().unwrap()); assert_eq!(std::fs::read_to_string(tree.join("receipt")).unwrap(), "checked"); - assert!(env.work().join("project/.git/oxa-work/test.json").exists()); + assert!(storage(&env).join("test.json").exists()); } #[test] fn clean_task_is_nothing_to_do() { @@ -121,11 +139,27 @@ fn retry_can_make_acceptance_green() { &env, r#"["if test -f once; then true; else touch once; exit 1; fi"]"#, ); - let record = run( - &env, + let server = FakeServer::start( vec![ScriptTurn::text("finished"), ScriptTurn::text("retry")], - ); + FakeOpts::default(), + ) + .unwrap(); + let out = Command::new(env!("CARGO_BIN_EXE_oxa")) + .args(["work", "../tasks.json"]) + .current_dir(env.work().join("project")) + .env_clear() + .envs(env.envs(&server.url())) + .output() + .unwrap(); + let record: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap(); assert_eq!(record["outcome"], "done", "{record}"); + let requests = server.requests(); + assert_eq!(requests.len(), 2); + assert_eq!( + requests[0].session, requests[1].session, + "repair lost the worker session" + ); + assert_eq!(record["session_id"], requests[0].session); } #[test] @@ -167,7 +201,7 @@ fn invalid_task_file_is_rejected_before_creating_worktree() { .output() .unwrap(); assert_eq!(out.status.code(), Some(2)); - assert!(!env.work().join("project/.git/oxa-work").exists()); + assert!(!env.agent_dir().join("work").exists()); } #[test] @@ -329,7 +363,8 @@ fn command_line_offline_policy_reaches_child_agent() { fn batch_reports_one_task_error_and_runs_later_tasks() { let env = TestEnv::new(); setup(&env, "[]"); - env.write("work/project/.git/oxa-work/test.json", "{}"); + std::fs::create_dir_all(storage(&env)).unwrap(); + std::fs::write(storage(&env).join("test.json"), "{}").unwrap(); env.write("work/tasks.json", r#"[{"id":"test","branch":"agent/test","model":"fake","prompt":"go"},{"id":"next","branch":"agent/next","model":"fake","prompt":"go"}]"#); let server = FakeServer::start(vec![ScriptTurn::text("done")], FakeOpts::default()).unwrap(); let out = Command::new(env!("CARGO_BIN_EXE_oxa")) @@ -353,7 +388,7 @@ fn batch_reports_one_task_error_and_runs_later_tasks() { assert_eq!(rows[0]["outcome"], "blocked"); assert_eq!(rows[1]["outcome"], "nothing_to_do"); assert_eq!( - std::fs::read_to_string(env.work().join("project/.git/oxa-work/test.json")).unwrap(), + std::fs::read_to_string(storage(&env).join("test.json")).unwrap(), "{}" ); } @@ -361,7 +396,216 @@ fn batch_reports_one_task_error_and_runs_later_tasks() { fn abandoned_lock_file_does_not_block_a_task() { let env = TestEnv::new(); setup(&env, "[]"); - env.write("work/project/.git/oxa-work/test.lock", ""); + std::fs::create_dir_all(storage(&env)).unwrap(); + std::fs::write(storage(&env).join("test.lock"), "").unwrap(); let record = run(&env, vec![ScriptTurn::text("done")]); assert_eq!(record["outcome"], "nothing_to_do", "{record}"); } + +#[test] +fn untrusted_project_never_executes_external_checks() { + let env = TestEnv::new(); + setup(&env, r#"["printf escaped > \"$HOME/untrusted-check\""]"#); + env.write( + "home/.oxa/agent/settings.json", + r#"{"defaultProjectTrust":"never"}"#, + ); + oxa_perm::TrustStore::default() + .save( + &env.agent_dir().join("trust.json"), + &env.work().join("project"), + false, + ) + .unwrap(); + let record = run(&env, vec![ScriptTurn::text("finished")]); + assert!(!env.home().join("untrusted-check").exists(), "untrusted code ran"); + assert_eq!(record["outcome"], "blocked", "{record}"); + assert!(record["detail"].as_str().unwrap().contains("trust"), "{record}"); +} + +#[test] +fn agent_written_acceptance_code_cannot_write_outside_the_sandbox() { + let env = TestEnv::new(); + setup(&env, r#"["sh check.sh"]"#); + env.write( + "home/.oxa/agent/settings.json", + r#"{"defaultProjectTrust":"always"}"#, + ); + env.write("work/project/check.sh", "exit 0\n"); + let project = env.work().join("project"); + git(&env, &project, &["add", "check.sh"]); + git(&env, &project, &["commit", "-m", "base check"]); + let script = "if printf escaped > \"$HOME/acceptance-escape\" 2>/dev/null; then true; fi\nprintf checked > acceptance-ran\n"; + let args = serde_json::json!({"path":"check.sh", "content":script}).to_string(); + let record = run( + &env, + vec![ + ScriptTurn::tool("change-check", "write", &args), + ScriptTurn::text("finished"), + ], + ); + assert!( + !env.home().join("acceptance-escape").exists(), + "agent-written code escaped acceptance" + ); + assert_eq!(record["outcome"], "done", "{record}"); + assert_eq!( + std::fs::read_to_string(Path::new(record["worktree"].as_str().unwrap()).join("acceptance-ran")) + .unwrap(), + "checked" + ); +} + +#[test] +fn worker_result_and_session_come_from_the_real_child_contract() { + let env = TestEnv::new(); + setup(&env, "[]"); + let record = run(&env, vec![ScriptTurn::text("finished")]); + assert_eq!(record["worker"]["outcome"], "done", "{record}"); + assert_eq!(record["worker"]["exit_code"], 0, "{record}"); + assert!(!record["session_id"].as_str().unwrap().is_empty()); +} + +#[test] +fn blocked_worker_keeps_its_result_and_does_not_start_a_repair() { + use oxa_fake::Fault; + let env = TestEnv::new(); + setup(&env, r#"["echo external-check-failed; exit 1"]"#); + env.write("home/.oxa/agent/settings.json", r#"{"retry":{"enabled":false}}"#); + let server = FakeServer::start( + vec![ScriptTurn::fault(Fault::Http { + status: 429, + body: serde_json::json!({"error":{"code":"budget_exceeded", "message":"Synthetic daily cap"}}) + .to_string(), + })], + FakeOpts::default(), + ) + .unwrap(); + let out = Command::new(env!("CARGO_BIN_EXE_oxa")) + .args(["work", "../tasks.json"]) + .current_dir(env.work().join("project")) + .env_clear() + .envs(env.envs(&server.url())) + .output() + .unwrap(); + let record: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap(); + assert_eq!(record["outcome"], "blocked", "{record}"); + assert_eq!(record["worker"]["outcome"], "blocked", "{record}"); + assert_eq!(record["worker"]["error_class"], "budget_exhausted", "{record}"); + assert_eq!(record["worker"]["exit_code"], oxa_proto::EXIT_BUDGET, "{record}"); + assert_eq!( + server.requests().len(), + 1, + "a budget refusal must not start a repair worker" + ); + assert!(record["detail"] + .as_str() + .unwrap() + .contains("external-check-failed")); +} + +#[test] +fn large_streamed_reply_does_not_enter_the_runner_receipt() { + let env = TestEnv::new(); + setup(&env, "[]"); + let mut turn = ScriptTurn::text(&"Synthetic response ".repeat(8192)); + turn.completion_tokens = Some(5); + turn.chunk = 8192; + let record = run(&env, vec![turn]); + assert_eq!(record["worker"]["outcome"], "done", "{record}"); + assert!( + record.to_string().len() < 2048, + "runner retained streamed model output" + ); +} + +#[test] +fn changed_project_commands_need_the_existing_content_approval() { + let env = TestEnv::new(); + setup(&env, "[]"); + let project = env.work().join("project"); + oxa_perm::TrustStore::load(&env.agent_dir().join("trust.json")) + .approve(&env.agent_dir().join("trust.json"), &project) + .unwrap(); + env.write( + "work/project/.oxa/settings.json", + r#"{"done":["printf escaped > \"$HOME/changed-check\""]}"#, + ); + git(&env, &project, &["add", ".oxa/settings.json"]); + git(&env, &project, &["commit", "-m", "changed commands"]); + let record = run(&env, vec![ScriptTurn::text("finished")]); + assert_eq!(record["outcome"], "blocked", "{record}"); + assert!(!env.home().join("changed-check").exists()); +} + +#[test] +fn acceptance_has_no_unsandboxed_fallback() { + use std::os::unix::fs::symlink; + let env = TestEnv::new(); + setup(&env, r#"["printf ran > acceptance-ran"]"#); + let tools = env.tmp().join("tools"); + std::fs::create_dir(&tools).unwrap(); + for name in ["git", "sh"] { + symlink(Path::new("/usr/bin").join(name), tools.join(name)).unwrap(); + } + let record = run_args( + &env, + vec![ScriptTurn::text("finished")], + &["work", "../tasks.json"], + Some(tools.to_string_lossy().into_owned()), + ); + assert_eq!(record["outcome"], "blocked", "{record}"); + assert!(record["detail"].as_str().unwrap().contains("bwrap"), "{record}"); + assert!(!Path::new(record["worktree"].as_str().unwrap()) + .join("acceptance-ran") + .exists()); +} + +#[test] +fn runner_state_is_private_and_outside_the_workers_git_bind() { + use std::os::unix::fs::PermissionsExt; + let env = TestEnv::new(); + setup(&env, "[]"); + let record = run(&env, vec![ScriptTurn::text("finished")]); + assert_eq!(record["outcome"], "nothing_to_do", "{record}"); + assert_eq!( + std::fs::metadata(storage(&env)).unwrap().permissions().mode() & 0o777, + 0o700 + ); + for file in ["test.json", "test.lock"] { + assert_eq!( + std::fs::metadata(storage(&env).join(file)) + .unwrap() + .permissions() + .mode() + & 0o777, + 0o600 + ); + } + assert!(!env.work().join("project/.git/oxa-work").exists()); +} + +#[test] +fn acceptance_preserves_the_normal_read_only_git_configuration() { + let env = TestEnv::new(); + setup(&env, r#"["sh check.sh"]"#); + env.write("work/project/check.sh", "git config core.fsmonitor 'printf escaped > \"$HOME/git-probe-escape\"; printf \"\\0\"' 2>/dev/null || true\nprintf checked > acceptance-ran\n"); + let project = env.work().join("project"); + git(&env, &project, &["add", "check.sh"]); + git(&env, &project, &["commit", "-m", "check fixture"]); + let record = run(&env, vec![ScriptTurn::text("finished")]); + assert_eq!(record["outcome"], "done", "{record}"); + assert!(!env.home().join("git-probe-escape").exists()); + let config = Command::new("git") + .args(["config", "--get", "core.fsmonitor"]) + .current_dir(project) + .env_clear() + .envs(env.envs("http://127.0.0.1:1")) + .output() + .unwrap(); + assert_eq!( + config.status.code(), + Some(1), + "acceptance rewrote executable Git configuration" + ); +} diff --git a/oxa/oxa-work/src/lib.rs b/oxa/oxa-work/src/lib.rs index 56ab914c9..bddce9e0f 100644 --- a/oxa/oxa-work/src/lib.rs +++ b/oxa/oxa-work/src/lib.rs @@ -1,9 +1,14 @@ //! Opt-in, sequential unattended task execution. Worktrees are retained on every outcome. use serde::{Deserialize, Serialize}; use std::fs; +use std::io::Write; +use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt}; use std::path::{Path, PathBuf}; use std::process::{Command, Output, Stdio}; +mod worker; +pub use worker::{WorkerOutcome, WorkerResult}; + pub type Result = std::result::Result; #[derive(Clone, Debug, Deserialize)] @@ -36,6 +41,8 @@ pub struct Record { pub worktree: PathBuf, pub outcome: Outcome, pub detail: String, + pub worker: Option, + pub session_id: Option, } fn output(mut command: Command) -> Result { @@ -125,40 +132,55 @@ fn done_commands(root: &Path) -> Result> { Some(value) => serde_json::from_value(value.clone()).map_err(|e| format!("done commands: {e}")), } } -fn acceptance(root: &Path, commands: &[String]) -> Result { - let mut failures = String::new(); - for entry in commands { - let (dir, shell) = match entry.strip_prefix("in ").and_then(|s| s.split_once(':')) { - Some((dir, cmd)) => (root.join(dir.trim()), cmd.trim()), - None => (root.to_path_buf(), entry.as_str()), - }; - let dir = dir.canonicalize().map_err(|e| e.to_string())?; - if !dir.starts_with(root) { - return Err("done directory escapes worktree".into()); - } - let mut c = Command::new("sh"); - c.current_dir(dir).args(["-c", shell]); - let out = output(c)?; - if !out.status.success() { - failures.push_str(&format!( - "{entry}: {}\n{}\n{}\n", - out.status, - String::from_utf8_lossy(&out.stdout), - String::from_utf8_lossy(&out.stderr) - )); - } - } - Ok(failures) +/// Private runner data stays outside every workspace and writable Git bind. +pub struct RunPolicy { + pub offline: bool, + pub storage: PathBuf, } -fn agent(binary: &Path, root: &Path, task: &Task, prompt: &str, offline: bool) -> Result<()> { - let mut c = Command::new(binary); - c.current_dir(root) - .args(["-p", "--model", &task.model, "--no-session"]); + +#[derive(Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct AcceptanceRequest { + pub source: PathBuf, + pub commands: Vec, +} + +fn acceptance( + binary: &Path, + root: &Path, + source: &Path, + commands: &[String], + offline: bool, + lock: &fs::File, +) -> Result { + if commands.is_empty() { + return Ok(String::new()); + } + let request = AcceptanceRequest { + source: source.to_path_buf(), + commands: commands.to_vec(), + }; + let mut command = Command::new(binary); if offline { - c.arg("--offline"); + command.arg("--offline"); + } + let out = command + .current_dir(root) + .args([ + "work", + "--acceptance", + &serde_json::to_string(&request).map_err(|e| e.to_string())?, + ]) + // The deterministic supervisor retains ownership if this runner dies. + .stdin(lock.try_clone().map_err(|e| e.to_string())?) + .output() + .map_err(|e| format!("acceptance supervisor: {e}"))?; + let diagnostic = String::from_utf8_lossy(&out.stderr).into_owned(); + match out.status.code() { + Some(0) => Ok(String::new()), + Some(1) => Ok(diagnostic), + _ => Err(format!("acceptance could not run: {diagnostic}")), } - c.args(["--", prompt]); - checked(c).map(|_| ()) } pub fn blocked_record(task: &Task, detail: String) -> Record { @@ -168,12 +190,11 @@ pub fn blocked_record(task: &Task, detail: String) -> Record { worktree: PathBuf::new(), outcome: Outcome::Blocked, detail, + worker: None, + session_id: None, } } -pub fn run_task(repo: &Path, binary: &Path, task: &Task) -> Result { - run_task_with_policy(repo, binary, task, false) -} -pub fn run_task_with_policy(repo: &Path, binary: &Path, task: &Task, offline: bool) -> Result { +pub fn run_task_with_policy(repo: &Path, binary: &Path, task: &Task, policy: &RunPolicy) -> Result { validate(task)?; let root = checked(git(repo, &["rev-parse", "--show-toplevel"]))?; let root = PathBuf::from(root); @@ -183,11 +204,17 @@ pub fn run_task_with_policy(repo: &Path, binary: &Path, task: &Task, offline: bo &["rev-parse", "--path-format=absolute", "--git-common-dir"], ))?; let common = PathBuf::from(common); - let storage = common.join("oxa-work"); - fs::create_dir_all(&storage).map_err(|e| e.to_string())?; + let storage = &policy.storage; + fs::DirBuilder::new() + .recursive(true) + .mode(0o700) + .create(storage) + .map_err(|e| e.to_string())?; let lock_path = storage.join(format!("{}.lock", task.id)); let lock_file = fs::OpenOptions::new() + .read(true) .write(true) + .mode(0o600) .create(true) .truncate(false) .open(&lock_path) @@ -221,6 +248,8 @@ pub fn run_task_with_policy(repo: &Path, binary: &Path, task: &Task, offline: bo worktree: tree.clone(), outcome: Outcome::Blocked, detail: String::new(), + worker: None, + session_id: None, }; let result = (|| -> Result { if tree.exists() { @@ -234,30 +263,41 @@ pub fn run_task_with_policy(repo: &Path, binary: &Path, task: &Task, offline: bo let tree = tree.canonicalize().map_err(|e| e.to_string())?; let initial = checked(git(&tree, &["rev-parse", "HEAD"]))?; let commands = done_commands(&tree)?; - let first_agent = agent(binary, &tree, task, &task.prompt, offline); - let failures = acceptance(&tree, &commands)?; + let first = worker::run( + binary, + &tree, + task, + &task.prompt, + policy.offline, + &lock_file, + None, + )?; + record.worker = Some(first.result.clone()); + record.session_id = first.session.clone(); + let failures = acceptance(binary, &tree, &root, &commands, policy.offline, &lock_file)?; + if let Some(error) = first.failure() { + return Err(format!("{error}\nAcceptance checks:\n{failures}")); + } if !failures.is_empty() { - let repair_agent = agent( + let repair = worker::run( binary, &tree, task, - &format!( - "{}\n\nExternal acceptance checks failed. Repair once:\n{failures}", - task.prompt - ), - offline, - ); - let failures = acceptance(&tree, &commands)?; + &format!("External acceptance checks failed. Repair once:\n{failures}"), + policy.offline, + &lock_file, + first.session.as_deref(), + )?; + record.worker = Some(repair.result.clone()); + record.session_id = repair.session.clone(); + let failures = acceptance(binary, &tree, &root, &commands, policy.offline, &lock_file)?; + if let Some(error) = repair.failure() { + return Err(format!("{error}\nAcceptance checks:\n{failures}")); + } if !failures.is_empty() { - if let Err(error) = repair_agent { - return Err(format!("{error}\nAcceptance checks:\n{failures}")); - } record.detail = failures; return Ok(Outcome::Red); } - repair_agent?; - } else { - first_agent?; } let head = checked(git(&tree, &["rev-parse", "HEAD"]))?; let dirty = checked(git(&tree, &["status", "--porcelain"]))?; @@ -272,10 +312,13 @@ pub fn run_task_with_policy(repo: &Path, binary: &Path, task: &Task, offline: bo Err(e) => record.detail = e, } // Separate receipts avoid overwriting another task's result. Never remove its worktree. - fs::write( - receipt, - serde_json::to_vec_pretty(&record).map_err(|e| e.to_string())?, - ) - .map_err(|e| e.to_string())?; + let mut file = fs::OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .open(receipt) + .map_err(|e| e.to_string())?; + file.write_all(&serde_json::to_vec_pretty(&record).map_err(|e| e.to_string())?) + .map_err(|e| e.to_string())?; Ok(record) } diff --git a/oxa/oxa-work/src/worker.rs b/oxa/oxa-work/src/worker.rs new file mode 100644 index 000000000..5187e9688 --- /dev/null +++ b/oxa/oxa-work/src/worker.rs @@ -0,0 +1,185 @@ +//! Consume the child's headless contract without retaining its event stream. +use crate::{Result, Task}; +use serde::{Deserialize, Serialize}; +use std::fs::File; +use std::io::{BufRead, BufReader, Read}; +use std::path::Path; +use std::process::{Command, Stdio}; + +const LINE_CAP: usize = 64 * 1024; +const DIAGNOSTIC_CAP: usize = 8192; + +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum WorkerOutcome { + Done, + NothingToDo, + Blocked, + Failed, + Interrupted, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct WorkerResult { + pub outcome: WorkerOutcome, + pub exit_code: i32, + pub error_class: Option, +} + +impl WorkerResult { + pub(crate) fn accepted(&self) -> bool { + matches!( + (&self.outcome, self.exit_code), + (WorkerOutcome::Done, 0) | (WorkerOutcome::NothingToDo, 4) + ) + } +} + +pub(crate) struct Worker { + pub result: WorkerResult, + pub session: Option, + pub diagnostic: String, +} + +impl Worker { + pub fn failure(&self) -> Option { + (!self.result.accepted()).then(|| { + format!( + "worker {:?} (exit {}, {}): {}", + self.result.outcome, + self.result.exit_code, + self.result.error_class.as_deref().unwrap_or("no error class"), + self.diagnostic.trim() + ) + }) + } +} + +pub(crate) fn run( + binary: &Path, + root: &Path, + task: &Task, + prompt: &str, + offline: bool, + lock: &File, + session: Option<&str>, +) -> Result { + let mut command = Command::new(binary); + command + .current_dir(root) + .args(["--mode=json", "--model", &task.model]); + if offline { + command.arg("--offline"); + } + if let Some(id) = session { + command.arg(format!("--continue={id}")); + } + let mut child = command + .args(["--", prompt]) + .stdin(lock.try_clone().map_err(|e| e.to_string())?) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .map_err(|e| format!("start worker: {e}"))?; + let stdout = child.stdout.take().ok_or("worker stdout missing")?; + let stderr = child.stderr.take().ok_or("worker stderr missing")?; + std::thread::scope(|scope| { + let header = scope.spawn(|| read_session(stdout)); + let terminal = scope.spawn(|| read_result(stderr)); + let status = child.wait().map_err(|e| format!("wait for worker: {e}"))?; + let session = header.join().map_err(|_| "worker header reader failed")??; + let (result, diagnostic) = terminal.join().map_err(|_| "worker result reader failed")??; + if status.code() != Some(result.exit_code) { + return Err("worker exit code disagrees with its oxa_result".into()); + } + if result.accepted() && session.is_none() { + return Err("successful worker did not report a session id".into()); + } + Ok(Worker { + result, + session, + diagnostic, + }) + }) +} + +fn read_session(pipe: impl Read) -> Result> { + let mut reader = BufReader::new(pipe); + let session = line(&mut reader)?.and_then(|line| { + let value: serde_json::Value = serde_json::from_slice(&line).ok()?; + (value["type"] == "session") + .then(|| value["id"].as_str().map(str::to_owned)) + .flatten() + .filter(|id| { + !id.is_empty() + && id.len() <= 128 + && id + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b"-_".contains(&b)) + }) + }); + std::io::copy(&mut reader, &mut std::io::sink()).map_err(|e| e.to_string())?; + Ok(session) +} + +fn read_result(pipe: impl Read) -> Result<(WorkerResult, String)> { + let mut reader = BufReader::new(pipe); + let mut result = None; + let mut duplicate = false; + let mut diagnostic = Vec::new(); + while let Some(bytes) = line(&mut reader)? { + let value = serde_json::from_slice::(&bytes).ok(); + if let Some(value) = value.filter(|v| v["type"] == "oxa_result") { + let parsed = serde_json::from_value(value).map_err(|e| format!("worker result: {e}"))?; + duplicate |= result.replace(parsed).is_some(); + } else { + keep_tail(&mut diagnostic, &bytes, DIAGNOSTIC_CAP); + } + } + if duplicate { + return Err("worker reported more than one oxa_result".into()); + } + let diagnostic = String::from_utf8_lossy(&diagnostic).into_owned(); + Ok(( + result.ok_or_else(|| format!("worker did not report oxa_result: {diagnostic}"))?, + diagnostic, + )) +} + +// Discard an oversized record while still draining the pipe. Event/progress size +// cannot increase the runner's memory use or block a child writing to either pipe. +fn line(reader: &mut impl BufRead) -> Result>> { + let mut line = Vec::new(); + let mut oversized = false; + let mut read = false; + loop { + let bytes = reader.fill_buf().map_err(|e| e.to_string())?; + if bytes.is_empty() { + return Ok(read.then_some(line)); + } + read = true; + let end = bytes.iter().position(|b| *b == b'\n'); + let count = end.map_or(bytes.len(), |i| i + 1); + if !oversized && line.len() + count <= LINE_CAP { + line.extend_from_slice(&bytes[..count]); + } else { + line.clear(); + oversized = true; + } + reader.consume(count); + if end.is_some() { + return Ok(Some(line)); + } + } +} + +pub(crate) fn keep_tail(tail: &mut Vec, bytes: &[u8], cap: usize) { + if bytes.len() >= cap { + tail.clear(); + tail.extend_from_slice(&bytes[bytes.len() - cap..]); + } else { + let discard = (tail.len() + bytes.len()).saturating_sub(cap); + tail.drain(..discard); + tail.extend_from_slice(bytes); + } +} From 12341d2092c970d51fffa632f1dd3baed6efd89c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Oscar=20Nordstr=C3=B6m?= <13300531+n0rpan@users.noreply.github.com> Date: Mon, 16 Nov 2026 07:00:48 +0000 Subject: [PATCH 07/11] Use trusted host tools for runner issue lookup and child startup (#333) --- oxa/docs/work.md | 4 ++ oxa/oxa-cli/src/netguard.rs | 83 +++++++++++++++++++++++++++++---- oxa/oxa-cli/src/work_cmd.rs | 68 +++++++++++++++++++++------ oxa/oxa-cli/tests/work_cli.rs | 88 +++++++++++++++++++++++++++++++++++ oxa/oxa-work/src/lib.rs | 66 +++++++++++++++----------- oxa/oxa-work/src/worker.rs | 7 +-- 6 files changed, 262 insertions(+), 54 deletions(-) diff --git a/oxa/docs/work.md b/oxa/docs/work.md index 15b6bb390..93551fef0 100644 --- a/oxa/docs/work.md +++ b/oxa/docs/work.md @@ -12,6 +12,10 @@ IDs and branches must be unique; branches must be new. For a GitHub issue use `oxa work --issue 123 --model your-model`. This explicitly invokes your installed, authenticated `gh` CLI to fetch the issue title and body. Issue lookup is refused when the environment or user settings enable offline mode. +Issue lookup also requires source-project trust. Git and GitHub CLI host calls use +validated executables outside the repository. Worker and check-supervisor PATHs +exclude project directories, relative entries and unsafe aliases; project tools +can still run by explicit path inside the sandbox. Each task runs a child `oxa --mode=json` with its model and a saved session. The installed offline policy, including a parent `--offline` flag, is passed to every child. Normal agent permission, trust and diff --git a/oxa/oxa-cli/src/netguard.rs b/oxa/oxa-cli/src/netguard.rs index b42d19148..ff4763846 100644 --- a/oxa/oxa-cli/src/netguard.rs +++ b/oxa/oxa-cli/src/netguard.rs @@ -57,13 +57,23 @@ fn trusted_gh_for( path: Option<&std::ffi::OsStr>, cwd: Option<&Path>, home: Option<&Path>, +) -> Option { + trusted_executable_for("gh", path, cwd, home) +} + +/// Host tools use the same project/PATH checks as the GitHub credential helper. +pub(crate) fn trusted_executable_for( + program: &str, + path: Option<&std::ffi::OsStr>, + cwd: Option<&Path>, + home: Option<&Path>, ) -> Option { let canon = |p: &Path| std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf()); let Some(h) = home.map(canon) else { - return trusted_gh(path, cwd); + return trusted_executable(program, path, cwd); }; if !cwd.is_some_and(|c| canon(c) == h) { - return trusted_gh(path, cwd); + return trusted_executable(program, path, cwd); } let allowed: Vec = USER_BIN.iter().map(|d| h.join(d)).collect(); // Allowed by where it resolves to, so a symlink from `~/.local/bin` into a project is refused. @@ -80,7 +90,7 @@ fn trusted_gh_for( }; std::env::split_paths(path?) .filter(|d| ok(d)) - .filter_map(|d| trusted_gh(Some(d.as_os_str()), None)) + .filter_map(|d| trusted_executable(program, Some(d.as_os_str()), None)) .find(|f| file_ok(f)) } @@ -134,10 +144,14 @@ fn gh_token_from(exe: &Path, deadline: std::time::Duration) -> Option { (!t.is_empty() && !t.chars().any(char::is_whitespace)).then(|| t.to_string()) } -/// The `gh` to run: the first executable file named `gh` in an absolute `PATH` entry that is +/// The host tool to run: the first executable with the requested name in an absolute `PATH` entry that is /// not inside the project (`cwd`) and not a group- or world-writable directory. Relative /// entries (`.`, `bin`, empty) are ignored, so a project shim never runs outside the sandbox. -fn trusted_gh(path: Option<&std::ffi::OsStr>, cwd: Option<&Path>) -> Option { +fn trusted_executable( + program: &str, + path: Option<&std::ffi::OsStr>, + cwd: Option<&Path>, +) -> Option { use std::os::unix::fs::PermissionsExt; let cwd_c = cwd.and_then(|c| std::fs::canonicalize(c).ok()); std::env::split_paths(path?) @@ -148,7 +162,7 @@ fn trusted_gh(path: Option<&std::ffi::OsStr>, cwd: Option<&Path>) -> Option, cwd: Option<&Path>) -> Option Option { + use std::os::unix::fs::PermissionsExt; + let home = home.canonicalize().unwrap_or_else(|_| home.to_path_buf()); + let project = project.canonicalize().ok()?; + let is_worker = |p: &Path| p.components().any(|part| part.as_os_str() == ".oxa-worktrees"); + let allowed: Vec<_> = USER_BIN.iter().map(|d| home.join(d)).collect(); + let entries = std::env::split_paths(path).filter(|dir| { + if !dir.is_absolute() || is_worker(dir) { + return false; + } + let Ok(real) = dir.canonicalize() else { + return false; + }; + if is_worker(&real) + || !std::fs::metadata(&real).is_ok_and(|m| m.is_dir() && m.permissions().mode() & 0o022 == 0) + { + return false; + } + if project == home { + if real.starts_with(&home) && !allowed.iter().any(|p| real.starts_with(p)) { + return false; + } + } else if dir.starts_with(&project) || real.starts_with(&project) { + return false; + } + ["git", "gh", "bwrap"].iter().all(|name| { + let exe = dir.join(name); + if std::fs::symlink_metadata(&exe).is_err() { + return true; + } + trusted_executable_for(name, Some(dir.as_os_str()), Some(&project), Some(&home)) + .is_some_and(|p| p.canonicalize().is_ok_and(|p| !is_worker(&p))) + }) + }); + std::env::join_paths(entries).ok() +} + /// The setting that allows an engine host that is not loopback (P3). Read from the user's /// settings only: a project file cannot send the prompts elsewhere. pub(crate) const SETTING_ALLOW_REMOTE: &str = "oxa.engine.allowRemote"; @@ -342,7 +399,7 @@ mod tests { script(&proj, "gh", "echo EVIL"); std::os::unix::fs::symlink(proj.join("gh"), good.join("gh")).unwrap(); let p = std::env::join_paths([good.to_str().unwrap()]).unwrap(); - assert_eq!(trusted_gh(Some(&p), Some(&proj)), None); + assert_eq!(trusted_executable("gh", Some(&p), Some(&proj)), None); } #[test] @@ -357,12 +414,18 @@ mod tests { let sep = |v: &[&str]| std::env::join_paths(v).unwrap(); // Relative entries are skipped. let rel = sep(&["bin", ".", "", good.to_str().unwrap()]); - assert_eq!(trusted_gh(Some(&rel), Some(&proj)), Some(good.join("gh"))); + assert_eq!( + trusted_executable("gh", Some(&rel), Some(&proj)), + Some(good.join("gh")) + ); // An absolute entry inside the project directory is skipped too. let p = sep(&[proj.to_str().unwrap(), good.to_str().unwrap()]); - assert_eq!(trusted_gh(Some(&p), Some(&proj)), Some(good.join("gh"))); + assert_eq!( + trusted_executable("gh", Some(&p), Some(&proj)), + Some(good.join("gh")) + ); // Only untrusted entries: nothing. let only = sep(&[proj.to_str().unwrap(), "rel"]); - assert_eq!(trusted_gh(Some(&only), Some(&proj)), None); + assert_eq!(trusted_executable("gh", Some(&only), Some(&proj)), None); } } diff --git a/oxa/oxa-cli/src/work_cmd.rs b/oxa/oxa-cli/src/work_cmd.rs index 8d3e76853..c34fe6f4a 100644 --- a/oxa/oxa-cli/src/work_cmd.rs +++ b/oxa/oxa-cli/src/work_cmd.rs @@ -30,34 +30,70 @@ pub(crate) fn run( return crate::work_checks::run(request, cwd, env, dirs, err); } } + let binary: PathBuf = std::env::current_exe().map_err(|e| e.to_string())?; + // Find the source boundary from files before executing any host tool. + let cwd_c = cwd.canonicalize().map_err(|e| e.to_string())?; + let project = cwd_c + .ancestors() + .find(|p| p.join(".git").exists()) + .ok_or("oxa work requires a Git repository")?; + let host_path = crate::netguard::trusted_work_path( + std::ffi::OsStr::new(env.get("PATH").unwrap_or("")), + project, + &dirs.home, + ) + .ok_or("cannot resolve trusted worker PATH")?; + let git_binary = crate::netguard::trusted_executable_for( + "git", + Some(host_path.as_os_str()), + Some(project), + Some(&dirs.home), + ) + .ok_or("no trusted Git executable outside the source project")?; + let output = std::process::Command::new(&git_binary) + .env("PATH", &host_path) + .current_dir(cwd) + .args(["rev-parse", "--show-toplevel"]) + .output() + .map_err(|e| e.to_string())?; + if !output.status.success() { + return Err("oxa work requires a Git repository".into()); + } + let root = PathBuf::from(String::from_utf8_lossy(&output.stdout).trim()) + .canonicalize() + .map_err(|e| e.to_string())?; + if root != project { + return Err("Git root differs from the source project boundary".into()); + } + let is_trusted = trusted(&root, env, dirs)?; let tasks = match args { [file] if !file.starts_with('-') => oxa_work::read_tasks(&cwd.join(file))?, [flag, number, model_flag, model] if flag == "--issue" && model_flag == "--model" => { if oxa_proto::offline() { return Err("GitHub issue lookup is unavailable in offline mode".into()); } + if !is_trusted { + return Err("source project is not trusted; approve it before issue lookup".into()); + } + let gh = crate::netguard::trusted_executable_for( + "gh", + Some(host_path.as_os_str()), + Some(&root), + Some(&dirs.home), + ) + .ok_or("no trusted gh executable outside the source project")?; vec![oxa_work::issue_task( - cwd, + &root, + &gh, + &host_path, number.parse().map_err(|_| "invalid issue number")?, model.clone(), )?] } _ => return Err("usage: oxa work | --issue N --model MODEL".into()), }; - let binary: PathBuf = std::env::current_exe().map_err(|e| e.to_string())?; - let output = std::process::Command::new("git") - .current_dir(cwd) - .args(["rev-parse", "--show-toplevel"]) - .output() - .map_err(|e| e.to_string())?; - if !output.status.success() { - return Err("oxa work requires a Git repository".into()); - } - let root = PathBuf::from(String::from_utf8_lossy(&output.stdout).trim()) - .canonicalize() - .map_err(|e| e.to_string())?; - let is_trusted = trusted(&root, env, dirs)?; - let common = std::process::Command::new("git") + let common = std::process::Command::new(&git_binary) + .env("PATH", &host_path) .current_dir(&root) .args(["rev-parse", "--path-format=absolute", "--git-common-dir"]) .output() @@ -73,6 +109,8 @@ pub(crate) fn run( .map(|b| format!("{b:02x}")) .collect::(); let policy = oxa_work::RunPolicy { + git_binary, + host_path, offline: oxa_proto::offline(), storage: dirs.agent_dir.join("work").join(key), }; diff --git a/oxa/oxa-cli/tests/work_cli.rs b/oxa/oxa-cli/tests/work_cli.rs index 6314f6c9c..5f8ed3d9b 100644 --- a/oxa/oxa-cli/tests/work_cli.rs +++ b/oxa/oxa-cli/tests/work_cli.rs @@ -609,3 +609,91 @@ fn acceptance_preserves_the_normal_read_only_git_configuration() { "acceptance rewrote executable Git configuration" ); } + +#[test] +fn github_lookup_ignores_project_local_executable() { + use std::os::unix::fs::PermissionsExt; + let env = TestEnv::new(); + setup(&env, "[]"); + let bad = env.write("work/project/bin/gh", "#!/bin/sh\nprintf invoked > \"$HOME/project-gh-ran\"\nprintf '%s' '{\"title\":\"Synthetic task\",\"body\":\"Fixture\"}'\n"); + let good = env.write("tmp/trusted/gh", "#!/bin/sh\nprintf invoked > \"$HOME/trusted-gh-ran\"\nprintf '%s' '{\"title\":\"Synthetic task\",\"body\":\"Fixture\"}'\n"); + for path in [&bad, &good] { + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).unwrap(); + } + let path = format!( + "{}:{}:{}", + bad.parent().unwrap().display(), + good.parent().unwrap().display(), + std::env::var("PATH").unwrap() + ); + let record = run_args( + &env, + vec![ScriptTurn::text("finished")], + &["work", "--issue", "42", "--model", "fake"], + Some(path), + ); + assert_eq!(record["outcome"], "nothing_to_do", "{record}"); + assert!( + !env.home().join("project-gh-ran").exists(), + "project executable ran on the host" + ); + assert!( + env.home().join("trusted-gh-ran").exists(), + "the trusted mock must handle issue lookup" + ); +} + +#[test] +fn runner_git_queries_ignore_project_local_executable() { + use std::os::unix::fs::PermissionsExt; + let env = TestEnv::new(); + setup(&env, "[]"); + let bad = env.write("work/project/bin/git", "#!/bin/sh\nprintf invoked > \"$HOME/project-git-ran\" 2>/dev/null || true\nexec /usr/bin/git \"$@\"\n"); + std::fs::set_permissions(&bad, std::fs::Permissions::from_mode(0o755)).unwrap(); + let path = format!( + "{}:{}", + bad.parent().unwrap().display(), + std::env::var("PATH").unwrap() + ); + let record = run_args( + &env, + vec![ScriptTurn::text("finished")], + &["work", "../tasks.json"], + Some(path), + ); + assert_eq!(record["outcome"], "nothing_to_do", "{record}"); + assert!( + !env.home().join("project-git-ran").exists(), + "project executable ran on the host" + ); +} + +#[test] +fn untrusted_issue_input_never_spawns_even_a_trusted_gh() { + use std::os::unix::fs::PermissionsExt; + let env = TestEnv::new(); + setup(&env, "[]"); + oxa_perm::TrustStore::default() + .save( + &env.agent_dir().join("trust.json"), + &env.work().join("project"), + false, + ) + .unwrap(); + let gh = env.write("tmp/gh", "#!/bin/sh\nprintf invoked > \"$HOME/issue-lookup-ran\"\nprintf '%s' '{\"title\":\"Synthetic task\",\"body\":\"Fixture\"}'\n"); + std::fs::set_permissions(&gh, std::fs::Permissions::from_mode(0o755)).unwrap(); + let out = Command::new(env!("CARGO_BIN_EXE_oxa")) + .args(["work", "--issue", "42", "--model", "fake"]) + .current_dir(env.work().join("project")) + .env_clear() + .envs(env.envs("http://127.0.0.1:1")) + .env( + "PATH", + format!("{}:{}", env.tmp().display(), std::env::var("PATH").unwrap()), + ) + .output() + .unwrap(); + assert_eq!(out.status.code(), Some(2)); + assert!(String::from_utf8_lossy(&out.stderr).contains("trust")); + assert!(!env.home().join("issue-lookup-ran").exists()); +} diff --git a/oxa/oxa-work/src/lib.rs b/oxa/oxa-work/src/lib.rs index bddce9e0f..53bfd7a74 100644 --- a/oxa/oxa-work/src/lib.rs +++ b/oxa/oxa-work/src/lib.rs @@ -55,9 +55,9 @@ fn checked(command: Command) -> Result { } Ok(String::from_utf8_lossy(&out.stdout).trim().into()) } -fn git(repo: &Path, args: &[&str]) -> Command { - let mut c = Command::new("git"); - c.current_dir(repo).args(args); +fn git(policy: &RunPolicy, repo: &Path, args: &[&str]) -> Command { + let mut c = Command::new(&policy.git_binary); + c.env("PATH", &policy.host_path).current_dir(repo).args(args); c } @@ -98,13 +98,24 @@ fn validate(task: &Task) -> Result<()> { } /// Issue text is data, passed as one prompt argument; gh never invokes a shell. -pub fn issue_task(repo: &Path, number: u64, model: String) -> Result { +pub fn issue_task( + repo: &Path, + gh: &Path, + host_path: &std::ffi::OsStr, + number: u64, + model: String, +) -> Result { if number == 0 { return Err("issue number must be positive".into()); } - let mut c = Command::new("gh"); - c.current_dir(repo) - .args(["issue", "view", &number.to_string(), "--json", "title,body"]); + let mut c = Command::new(gh); + c.env("PATH", host_path).current_dir(repo).args([ + "issue", + "view", + &number.to_string(), + "--json", + "title,body", + ]); let text = checked(c)?; let issue: serde_json::Value = serde_json::from_str(&text).map_err(|e| e.to_string())?; let title = issue["title"].as_str().ok_or("issue title missing")?; @@ -134,6 +145,10 @@ fn done_commands(root: &Path) -> Result> { } /// Private runner data stays outside every workspace and writable Git bind. pub struct RunPolicy { + /// Absolute tool path approved by the front end's trusted-executable checks. + pub git_binary: PathBuf, + /// Installed tools only; repository code is invoked inside the sandbox. + pub host_path: std::ffi::OsString, pub offline: bool, pub storage: PathBuf, } @@ -150,7 +165,7 @@ fn acceptance( root: &Path, source: &Path, commands: &[String], - offline: bool, + policy: &RunPolicy, lock: &fs::File, ) -> Result { if commands.is_empty() { @@ -161,10 +176,11 @@ fn acceptance( commands: commands.to_vec(), }; let mut command = Command::new(binary); - if offline { + if policy.offline { command.arg("--offline"); } let out = command + .env("PATH", &policy.host_path) .current_dir(root) .args([ "work", @@ -196,10 +212,15 @@ pub fn blocked_record(task: &Task, detail: String) -> Record { } pub fn run_task_with_policy(repo: &Path, binary: &Path, task: &Task, policy: &RunPolicy) -> Result { validate(task)?; - let root = checked(git(repo, &["rev-parse", "--show-toplevel"]))?; + let root = checked(git(policy, repo, &["rev-parse", "--show-toplevel"]))?; let root = PathBuf::from(root); - checked(git(&root, &["check-ref-format", "--branch", &task.branch]))?; + checked(git( + policy, + &root, + &["check-ref-format", "--branch", &task.branch], + ))?; let common = checked(git( + policy, &root, &["rev-parse", "--path-format=absolute", "--git-common-dir"], ))?; @@ -257,24 +278,17 @@ pub fn run_task_with_policy(repo: &Path, binary: &Path, task: &Task, policy: &Ru } let tree_arg = tree.to_str().ok_or("non-UTF8 worktree path")?; checked(git( + policy, &root, &["worktree", "add", "-b", &task.branch, tree_arg, &task.base], ))?; let tree = tree.canonicalize().map_err(|e| e.to_string())?; - let initial = checked(git(&tree, &["rev-parse", "HEAD"]))?; + let initial = checked(git(policy, &tree, &["rev-parse", "HEAD"]))?; let commands = done_commands(&tree)?; - let first = worker::run( - binary, - &tree, - task, - &task.prompt, - policy.offline, - &lock_file, - None, - )?; + let first = worker::run(binary, &tree, task, &task.prompt, policy, &lock_file, None)?; record.worker = Some(first.result.clone()); record.session_id = first.session.clone(); - let failures = acceptance(binary, &tree, &root, &commands, policy.offline, &lock_file)?; + let failures = acceptance(binary, &tree, &root, &commands, policy, &lock_file)?; if let Some(error) = first.failure() { return Err(format!("{error}\nAcceptance checks:\n{failures}")); } @@ -284,13 +298,13 @@ pub fn run_task_with_policy(repo: &Path, binary: &Path, task: &Task, policy: &Ru &tree, task, &format!("External acceptance checks failed. Repair once:\n{failures}"), - policy.offline, + policy, &lock_file, first.session.as_deref(), )?; record.worker = Some(repair.result.clone()); record.session_id = repair.session.clone(); - let failures = acceptance(binary, &tree, &root, &commands, policy.offline, &lock_file)?; + let failures = acceptance(binary, &tree, &root, &commands, policy, &lock_file)?; if let Some(error) = repair.failure() { return Err(format!("{error}\nAcceptance checks:\n{failures}")); } @@ -299,8 +313,8 @@ pub fn run_task_with_policy(repo: &Path, binary: &Path, task: &Task, policy: &Ru return Ok(Outcome::Red); } } - let head = checked(git(&tree, &["rev-parse", "HEAD"]))?; - let dirty = checked(git(&tree, &["status", "--porcelain"]))?; + let head = checked(git(policy, &tree, &["rev-parse", "HEAD"]))?; + let dirty = checked(git(policy, &tree, &["status", "--porcelain"]))?; Ok(if head == initial && dirty.is_empty() { Outcome::NothingToDo } else { diff --git a/oxa/oxa-work/src/worker.rs b/oxa/oxa-work/src/worker.rs index 5187e9688..52df82697 100644 --- a/oxa/oxa-work/src/worker.rs +++ b/oxa/oxa-work/src/worker.rs @@ -1,5 +1,5 @@ //! Consume the child's headless contract without retaining its event stream. -use crate::{Result, Task}; +use crate::{Result, RunPolicy, Task}; use serde::{Deserialize, Serialize}; use std::fs::File; use std::io::{BufRead, BufReader, Read}; @@ -60,15 +60,16 @@ pub(crate) fn run( root: &Path, task: &Task, prompt: &str, - offline: bool, + policy: &RunPolicy, lock: &File, session: Option<&str>, ) -> Result { let mut command = Command::new(binary); command + .env("PATH", &policy.host_path) .current_dir(root) .args(["--mode=json", "--model", &task.model]); - if offline { + if policy.offline { command.arg("--offline"); } if let Some(id) = session { From 098a257867e92593e6c7bef7921bde38bc1d74c6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Oscar=20Nordstr=C3=B6m?= <13300531+n0rpan@users.noreply.github.com> Date: Mon, 16 Nov 2026 07:17:14 +0000 Subject: [PATCH 08/11] Exclude outer project tools across nested Git boundaries (#333) --- oxa/oxa-cli/src/work_cmd.rs | 8 +++++++- oxa/oxa-cli/tests/work_cli.rs | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/oxa/oxa-cli/src/work_cmd.rs b/oxa/oxa-cli/src/work_cmd.rs index c34fe6f4a..43362a107 100644 --- a/oxa/oxa-cli/src/work_cmd.rs +++ b/oxa/oxa-cli/src/work_cmd.rs @@ -37,9 +37,15 @@ pub(crate) fn run( .ancestors() .find(|p| p.join(".git").exists()) .ok_or("oxa work requires a Git repository")?; + // Nested repository metadata cannot bless code from an outer project. + let host_project = project + .ancestors() + .filter(|p| p.join(".git").exists()) + .last() + .unwrap_or(project); let host_path = crate::netguard::trusted_work_path( std::ffi::OsStr::new(env.get("PATH").unwrap_or("")), - project, + host_project, &dirs.home, ) .ok_or("cannot resolve trusted worker PATH")?; diff --git a/oxa/oxa-cli/tests/work_cli.rs b/oxa/oxa-cli/tests/work_cli.rs index 5f8ed3d9b..dc7b46f16 100644 --- a/oxa/oxa-cli/tests/work_cli.rs +++ b/oxa/oxa-cli/tests/work_cli.rs @@ -697,3 +697,36 @@ fn untrusted_issue_input_never_spawns_even_a_trusted_gh() { assert!(String::from_utf8_lossy(&out.stderr).contains("trust")); assert!(!env.home().join("issue-lookup-ran").exists()); } + +#[test] +fn invalid_nested_git_metadata_cannot_hide_an_outer_project_executable() { + use std::os::unix::fs::PermissionsExt; + let env = TestEnv::new(); + setup(&env, "[]"); + let bad = env.write( + "work/project/bin/git", + "#!/bin/sh\nprintf invoked > \"$HOME/nested-project-git-ran\"\nexec /usr/bin/git \"$@\"\n", + ); + std::fs::set_permissions(&bad, std::fs::Permissions::from_mode(0o755)).unwrap(); + env.write("work/project/nested/.git", "invalid git metadata\n"); + let out = Command::new(env!("CARGO_BIN_EXE_oxa")) + .args(["work", "../../tasks.json"]) + .current_dir(env.work().join("project/nested")) + .env_clear() + .envs(env.envs("http://127.0.0.1:1")) + .env( + "PATH", + format!( + "{}:{}", + bad.parent().unwrap().display(), + std::env::var("PATH").unwrap() + ), + ) + .output() + .unwrap(); + assert_eq!(out.status.code(), Some(2)); + assert!( + !env.home().join("nested-project-git-ran").exists(), + "nested metadata bypassed the source boundary" + ); +} From 224b4fef12bc456ac312805be890a2570b2e6df7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Oscar=20Nordstr=C3=B6m?= <13300531+n0rpan@users.noreply.github.com> Date: Mon, 16 Nov 2026 07:34:50 +0000 Subject: [PATCH 09/11] Keep final Git inspection inside the runner sandbox (#333) --- oxa/docs/work.md | 3 + oxa/oxa-cli/src/work_checks.rs | 58 +++++++++++++++---- oxa/oxa-cli/src/work_cmd.rs | 2 +- oxa/oxa-cli/tests/work_cli.rs | 102 +++++++++++++++++++++++++++++++++ oxa/oxa-work/src/lib.rs | 87 ++++++++++++++++++++++------ 5 files changed, 223 insertions(+), 29 deletions(-) diff --git a/oxa/docs/work.md b/oxa/docs/work.md index 93551fef0..b94b8c9a5 100644 --- a/oxa/docs/work.md +++ b/oxa/docs/work.md @@ -27,6 +27,9 @@ not approve an untrusted project. Acceptance runs in the normal bwrap sandbox; missing or unusable bwrap blocks the task. Each check has the same ten-minute limit as agent-internal done checks. `in subdirectory: command` selects a folder inside that sandbox; escaping the worktree is rejected. +The final Git inspection is also sandboxed, with a read-only workspace, no network +and fsmonitor disabled. Clean filters stay inside that sandbox; an inspection +error blocks the task rather than producing a clean verdict. Agent-internal done checks may also run when the project is trusted. The runner reads the child's exit code, terminal `oxa_result` and session header, diff --git a/oxa/oxa-cli/src/work_checks.rs b/oxa/oxa-cli/src/work_checks.rs index f33721218..5ee566c24 100644 --- a/oxa/oxa-cli/src/work_checks.rs +++ b/oxa/oxa-cli/src/work_checks.rs @@ -1,8 +1,8 @@ -//! Deterministic acceptance supervisor; no engine or model is constructed here. +//! Deterministic check/inspection supervisor; no engine or model is constructed here. use oxa_config::{Dirs, Env, Settings}; -use oxa_proto::{CancelToken, ExecSpec}; +use oxa_proto::{CancelToken, ExecSpec, Sandbox}; use oxa_sandbox::Bwrap; -use oxa_work::AcceptanceRequest; +use oxa_work::{SupervisorOperation, SupervisorRequest}; use std::io::Write; use std::path::Path; use std::sync::Arc; @@ -14,24 +14,29 @@ pub(crate) fn run( dirs: &Dirs, err: &mut dyn Write, ) -> Result { - let request: AcceptanceRequest = serde_json::from_str(request).map_err(|e| e.to_string())?; + let request: SupervisorRequest = serde_json::from_str(request).map_err(|e| e.to_string())?; let source = request.source.canonicalize().map_err(|e| e.to_string())?; if !crate::work_cmd::trusted(&source, env, dirs)? { - return Err("acceptance source project is not trusted".into()); + return Err("supervisor source project is not trusted".into()); } let root = cwd.canonicalize().map_err(|e| e.to_string())?; + let mut b = Bwrap::detect(env.get("PATH").unwrap_or(""), &dirs.home).map_err(|e| e.to_string())?; + b.layout = crate::sandbox_layout::layout(env, dirs, &root, false, &mut vec![]); + let b = b.with_git_dirs(&root); + b.check().map_err(|e| e.to_string())?; + let commands = match request.operation { + SupervisorOperation::Inspect => return inspect(&b, &root), + SupervisorOperation::Checks { commands } => commands, + }; let settings = Settings::load(dirs, &source, true); let shell = oxa_tools::ShellConfig { shell_path: settings.shell_path(&dirs.home), command_prefix: settings.shell_command_prefix(), }; - let mut b = Bwrap::detect(env.get("PATH").unwrap_or(""), &dirs.home).map_err(|e| e.to_string())?; - b.layout = crate::sandbox_layout::layout(env, dirs, &root, false, &mut vec![]); - let sandbox = crate::netguard::with_net(Arc::new(b.with_git_dirs(&root)), &settings); - sandbox.check().map_err(|e| e.to_string())?; + let sandbox = crate::netguard::with_net(Arc::new(b), &settings); let mut failed = false; let mut diagnostics = Vec::new(); - for entry in request.commands { + for entry in commands { let (directory, text) = match entry.strip_prefix("in ").and_then(|s| s.split_once(':')) { Some((dir, command)) => (Some(dir.trim()), command.trim()), None => (None, entry.as_str()), @@ -84,6 +89,39 @@ pub(crate) fn run( Ok(i32::from(failed)) } +// Exit codes are the only result: repository callbacks cannot forge a clean +// verdict by printing JSON or diagnostics. Git failures remain distinct from dirty. +fn inspect(sandbox: &Bwrap, root: &Path) -> Result { + let spec = ExecSpec { + command: r#"git --no-optional-locks -c core.fsmonitor=false status --porcelain=v1 -z | { + work_dirty=0 + while IFS= read -r -d '' work_entry; do work_dirty=1; done + exit "$work_dirty" +} +work_probe_status=("${PIPESTATUS[@]}") +if test "${work_probe_status[0]}" -ne 0; then exit 2; fi +exit "${work_probe_status[1]}" +"# + .into(), + cwd: root.to_path_buf(), + writable: false, + net: false, + timeout_s: Some(600), + env: Vec::new(), + }; + let mut tail = Vec::new(); + let result = sandbox.run_streaming(&spec, &CancelToken::default(), &mut |bytes| { + keep_tail(&mut tail, bytes, 8192); + }); + match (result.exit, result.timed_out) { + (Some(code @ (0 | 1)), false) => Ok(code), + _ => Err(format!( + "sandboxed Git inspection failed: {}", + String::from_utf8_lossy(&tail) + )), + } +} + fn keep_tail(tail: &mut Vec, bytes: &[u8], cap: usize) { if bytes.len() >= cap { tail.clear(); diff --git a/oxa/oxa-cli/src/work_cmd.rs b/oxa/oxa-cli/src/work_cmd.rs index 43362a107..be48c3e83 100644 --- a/oxa/oxa-cli/src/work_cmd.rs +++ b/oxa/oxa-cli/src/work_cmd.rs @@ -26,7 +26,7 @@ pub(crate) fn run( ) -> i32 { let result = (|| -> Result { if let [flag, request] = args { - if flag == "--acceptance" { + if flag == "--supervise" { return crate::work_checks::run(request, cwd, env, dirs, err); } } diff --git a/oxa/oxa-cli/tests/work_cli.rs b/oxa/oxa-cli/tests/work_cli.rs index dc7b46f16..6eb1e7e79 100644 --- a/oxa/oxa-cli/tests/work_cli.rs +++ b/oxa/oxa-cli/tests/work_cli.rs @@ -730,3 +730,105 @@ fn invalid_nested_git_metadata_cannot_hide_an_outer_project_executable() { "nested metadata bypassed the source boundary" ); } + +#[test] +fn final_inspection_never_executes_a_worker_edited_fsmonitor_on_the_host() { + let env = TestEnv::new(); + setup(&env, "[]"); + let project = env.work().join("project"); + env.write("work/project/monitor.sh", "printf '\\0'\n"); + git(&env, &project, &["add", "monitor.sh"]); + git(&env, &project, &["commit", "-m", "monitor fixture"]); + git(&env, &project, &["config", "core.fsmonitor", "sh monitor.sh"]); + let args = serde_json::json!({"path":"monitor.sh","content":"printf escaped > \"$HOME/fsmonitor-inspection-escape\"\nprintf '\\0'\n"}).to_string(); + let record = run( + &env, + vec![ + ScriptTurn::tool("change-monitor", "write", &args), + ScriptTurn::text("finished"), + ], + ); + assert_eq!(record["outcome"], "done", "{record}"); + assert!( + !env.home().join("fsmonitor-inspection-escape").exists(), + "final inspection ran a host callback" + ); +} + +#[test] +fn final_inspection_keeps_worker_edited_clean_filters_in_the_sandbox() { + let env = TestEnv::new(); + setup(&env, "[]"); + let project = env.work().join("project"); + env.write("work/project/.gitattributes", "tracked.txt filter=probe\n"); + env.write("work/project/filter.sh", "cat\n"); + env.write("work/project/tracked.txt", "alpha\n"); + git(&env, &project, &["config", "filter.probe.clean", "sh filter.sh"]); + git(&env, &project, &["config", "filter.probe.smudge", "cat"]); + git(&env, &project, &["config", "filter.probe.required", "true"]); + git( + &env, + &project, + &["add", ".gitattributes", "filter.sh", "tracked.txt"], + ); + git(&env, &project, &["commit", "-m", "filter fixture"]); + let args = serde_json::json!({"path":"filter.sh","content":"printf escaped > \"$HOME/filter-inspection-escape\" 2>/dev/null || true\ncat\n"}).to_string(); + let record = run( + &env, + vec![ + ScriptTurn::tool("change-filter", "write", &args), + ScriptTurn::tool( + "change-file", + "write", + r#"{"path":"tracked.txt","content":"bravo\n"}"#, + ), + ScriptTurn::text("finished"), + ], + ); + assert_eq!(record["outcome"], "done", "{record}"); + assert!( + !env.home().join("filter-inspection-escape").exists(), + "final inspection ran a host filter" + ); +} + +#[test] +fn failed_git_inspection_is_blocked_instead_of_clean_or_dirty() { + let env = TestEnv::new(); + setup(&env, "[]"); + let project = env.work().join("project"); + env.write("work/project/.gitattributes", "tracked.txt filter=probe\n"); + env.write("work/project/filter.sh", "cat\n"); + env.write("work/project/tracked.txt", "alpha\n"); + git(&env, &project, &["config", "filter.probe.clean", "sh filter.sh"]); + git(&env, &project, &["config", "filter.probe.smudge", "cat"]); + git(&env, &project, &["config", "filter.probe.required", "true"]); + git( + &env, + &project, + &["add", ".gitattributes", "filter.sh", "tracked.txt"], + ); + git(&env, &project, &["commit", "-m", "filter fixture"]); + let record = run( + &env, + vec![ + ScriptTurn::tool( + "break-filter", + "write", + r#"{"path":"filter.sh","content":"echo synthetic-filter-failure >&2\nexit 1\n"}"#, + ), + ScriptTurn::tool( + "change-file", + "write", + r#"{"path":"tracked.txt","content":"bravo\n"}"#, + ), + ScriptTurn::text("finished"), + ], + ); + assert_eq!(record["outcome"], "blocked", "{record}"); + assert_eq!(record["worker"]["outcome"], "done", "{record}"); + assert!(record["detail"] + .as_str() + .unwrap() + .contains("synthetic-filter-failure")); +} diff --git a/oxa/oxa-work/src/lib.rs b/oxa/oxa-work/src/lib.rs index 53bfd7a74..4e29b1000 100644 --- a/oxa/oxa-work/src/lib.rs +++ b/oxa/oxa-work/src/lib.rs @@ -155,42 +155,66 @@ pub struct RunPolicy { #[derive(Deserialize, Serialize)] #[serde(deny_unknown_fields)] -pub struct AcceptanceRequest { +pub struct SupervisorRequest { pub source: PathBuf, - pub commands: Vec, + pub operation: SupervisorOperation, } -fn acceptance( +#[derive(Deserialize, Serialize)] +#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] +pub enum SupervisorOperation { + Checks { commands: Vec }, + Inspect, +} + +fn supervise( binary: &Path, root: &Path, - source: &Path, - commands: &[String], + request: SupervisorRequest, policy: &RunPolicy, lock: &fs::File, -) -> Result { - if commands.is_empty() { - return Ok(String::new()); - } - let request = AcceptanceRequest { - source: source.to_path_buf(), - commands: commands.to_vec(), - }; +) -> Result { let mut command = Command::new(binary); if policy.offline { command.arg("--offline"); } - let out = command + command .env("PATH", &policy.host_path) .current_dir(root) .args([ "work", - "--acceptance", + "--supervise", &serde_json::to_string(&request).map_err(|e| e.to_string())?, ]) // The deterministic supervisor retains ownership if this runner dies. .stdin(lock.try_clone().map_err(|e| e.to_string())?) .output() - .map_err(|e| format!("acceptance supervisor: {e}"))?; + .map_err(|e| format!("work supervisor: {e}")) +} + +fn acceptance( + binary: &Path, + root: &Path, + source: &Path, + commands: &[String], + policy: &RunPolicy, + lock: &fs::File, +) -> Result { + if commands.is_empty() { + return Ok(String::new()); + } + let out = supervise( + binary, + root, + SupervisorRequest { + source: source.to_path_buf(), + operation: SupervisorOperation::Checks { + commands: commands.to_vec(), + }, + }, + policy, + lock, + )?; let diagnostic = String::from_utf8_lossy(&out.stderr).into_owned(); match out.status.code() { Some(0) => Ok(String::new()), @@ -199,6 +223,33 @@ fn acceptance( } } +fn dirty_worktree( + binary: &Path, + root: &Path, + source: &Path, + policy: &RunPolicy, + lock: &fs::File, +) -> Result { + let out = supervise( + binary, + root, + SupervisorRequest { + source: source.to_path_buf(), + operation: SupervisorOperation::Inspect, + }, + policy, + lock, + )?; + match out.status.code() { + Some(0) => Ok(false), + Some(1) => Ok(true), + _ => Err(format!( + "worktree inspection could not run: {}", + String::from_utf8_lossy(&out.stderr) + )), + } +} + pub fn blocked_record(task: &Task, detail: String) -> Record { Record { id: task.id.clone(), @@ -314,8 +365,8 @@ pub fn run_task_with_policy(repo: &Path, binary: &Path, task: &Task, policy: &Ru } } let head = checked(git(policy, &tree, &["rev-parse", "HEAD"]))?; - let dirty = checked(git(policy, &tree, &["status", "--porcelain"]))?; - Ok(if head == initial && dirty.is_empty() { + let dirty = dirty_worktree(binary, &tree, &root, policy, &lock_file)?; + Ok(if head == initial && !dirty { Outcome::NothingToDo } else { Outcome::Done From dd80623ae9cfb0fa1dea30b870c2f1803301cf56 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Oscar=20Nordstr=C3=B6m?= <13300531+n0rpan@users.noreply.github.com> Date: Mon, 16 Nov 2026 07:57:31 +0000 Subject: [PATCH 10/11] Bootstrap task branches without host Git callbacks (#333) --- oxa/docs/work.md | 12 ++- oxa/oxa-cli/src/work_checks.rs | 29 ++++- oxa/oxa-cli/tests/work_cli.rs | 191 +++++++++++++++++++++++++++++++++ oxa/oxa-work/src/lib.rs | 64 +++++++++-- 4 files changed, 282 insertions(+), 14 deletions(-) diff --git a/oxa/docs/work.md b/oxa/docs/work.md index b94b8c9a5..ca2f3e4b2 100644 --- a/oxa/docs/work.md +++ b/oxa/docs/work.md @@ -20,11 +20,19 @@ can still run by explicit path inside the sandbox. Each task runs a child `oxa --mode=json` with its model and a saved session. The installed offline policy, including a parent `--offline` flag, is passed to every child. Normal agent permission, trust and sandbox rules apply. Configure project trust before unattended use. The runner -executes the base version of `.oxa/settings.json`'s `done` commands outside the +creates detached Git metadata with callbacks suppressed on the host, then creates +the task branch and populates the fresh worktree inside the normal sandbox. +Reference hooks, checkout hooks and smudge filters stay inside it; a reference hook +that rejects the task branch still blocks the task. +missing bwrap blocks before checkout or a worker starts. Configured hook directories +keep their normal read-only protection: a checkout that needs to populate a tracked +protected hook directory blocks with the worktree retained. +Acceptance commands are frozen from the captured base commit before checkout +callbacks can change settings. The runner executes those `done` commands outside the agent after it exits, even without edits. The source project must pass the existing trust and executable-content approval before a task starts. Invoking `work` does not approve an untrusted project. Acceptance runs in the normal bwrap sandbox; -missing or unusable bwrap blocks the task. Each check has the same ten-minute limit +missing or unusable bwrap blocks the task. Checkout and each check have the same ten-minute limit as agent-internal done checks. `in subdirectory: command` selects a folder inside that sandbox; escaping the worktree is rejected. The final Git inspection is also sandboxed, with a read-only workspace, no network diff --git a/oxa/oxa-cli/src/work_checks.rs b/oxa/oxa-cli/src/work_checks.rs index 5ee566c24..75339a521 100644 --- a/oxa/oxa-cli/src/work_checks.rs +++ b/oxa/oxa-cli/src/work_checks.rs @@ -24,11 +24,38 @@ pub(crate) fn run( b.layout = crate::sandbox_layout::layout(env, dirs, &root, false, &mut vec![]); let b = b.with_git_dirs(&root); b.check().map_err(|e| e.to_string())?; + let settings = Settings::load(dirs, &source, true); let commands = match request.operation { SupervisorOperation::Inspect => return inspect(&b, &root), + SupervisorOperation::Checkout { branch } => { + let sandbox = crate::netguard::with_net(Arc::new(b), &settings); + let spec = ExecSpec { + command: format!( + "git checkout HEAD -- . && git checkout -b '{}' HEAD", + branch.replace('\'', "'\\''") + ), + cwd: root, + writable: true, + net: sandbox.network(), + timeout_s: Some(600), + env: vec![("AI_AGENT".into(), "oxa".into())], + }; + let mut tail = Vec::new(); + let result = sandbox.run_streaming(&spec, &CancelToken::default(), &mut |bytes| { + keep_tail(&mut tail, bytes, 8192); + }); + if result.exit != Some(0) || result.timed_out { + return Err(format!( + "checkout exit {:?}, timeout {}: {}", + result.exit, + result.timed_out, + String::from_utf8_lossy(&tail) + )); + } + return Ok(0); + } SupervisorOperation::Checks { commands } => commands, }; - let settings = Settings::load(dirs, &source, true); let shell = oxa_tools::ShellConfig { shell_path: settings.shell_path(&dirs.home), command_prefix: settings.shell_command_prefix(), diff --git a/oxa/oxa-cli/tests/work_cli.rs b/oxa/oxa-cli/tests/work_cli.rs index 6eb1e7e79..65a9e0784 100644 --- a/oxa/oxa-cli/tests/work_cli.rs +++ b/oxa/oxa-cli/tests/work_cli.rs @@ -832,3 +832,194 @@ fn failed_git_inspection_is_blocked_instead_of_clean_or_dirty() { .unwrap() .contains("synthetic-filter-failure")); } + +fn checkout_hook_fixture(env: &TestEnv) { + use std::os::unix::fs::PermissionsExt; + setup(env, "[]"); + let hook = env.write( + "work/project/.githooks/post-checkout", + "#!/bin/sh\nprintf escaped > \"$HOME/worktree-checkout-escape\"\n", + ); + std::fs::set_permissions(hook, std::fs::Permissions::from_mode(0o755)).unwrap(); + let project = env.work().join("project"); + git(env, &project, &["add", ".githooks"]); + git(env, &project, &["commit", "-m", "checkout hook fixture"]); + git(env, &project, &["config", "core.hooksPath", ".githooks"]); +} + +#[test] +fn worktree_checkout_never_runs_tracked_hooks_on_the_host() { + let env = TestEnv::new(); + checkout_hook_fixture(&env); + let record = run(&env, vec![ScriptTurn::text("finished")]); + assert!( + !env.home().join("worktree-checkout-escape").exists(), + "worktree creation ran a host hook: {record}" + ); + // The normal sandbox pins configured hook directories read-only, including + // this missing directory. Checkout must block rather than unmask it. + assert_eq!(record["outcome"], "blocked", "{record}"); + assert!(record["worker"].is_null(), "{record}"); +} + +#[test] +fn checkout_keeps_git_hooks_active_inside_the_sandbox() { + use std::os::unix::fs::PermissionsExt; + let env = TestEnv::new(); + setup(&env, "[]"); + let hook = env.write( + "work/project/.git/hooks/post-checkout", + "#!/bin/sh\nprintf escaped > \"$HOME/worktree-checkout-escape\" 2>/dev/null || true\nprintf ran > checkout-hook-ran\n", + ); + std::fs::set_permissions(hook, std::fs::Permissions::from_mode(0o755)).unwrap(); + let record = run(&env, vec![ScriptTurn::text("finished")]); + assert!( + !env.home().join("worktree-checkout-escape").exists(), + "checkout hook escaped: {record}" + ); + assert_eq!(record["outcome"], "done", "{record}"); + assert_eq!( + std::fs::read_to_string(Path::new(record["worktree"].as_str().unwrap()).join("checkout-hook-ran")) + .unwrap(), + "ran" + ); + assert!(!env.work().join("project/checkout-hook-ran").exists()); +} + +#[test] +fn unavailable_sandbox_blocks_checkout_before_any_hook() { + use std::os::unix::fs::symlink; + let env = TestEnv::new(); + checkout_hook_fixture(&env); + let tools = env.tmp().join("tools"); + std::fs::create_dir(&tools).unwrap(); + for name in ["git", "sh"] { + symlink(Path::new("/usr/bin").join(name), tools.join(name)).unwrap(); + } + let record = run_args( + &env, + vec![ScriptTurn::text("finished")], + &["work", "../tasks.json"], + Some(tools.to_string_lossy().into_owned()), + ); + assert!( + !env.home().join("worktree-checkout-escape").exists(), + "checkout ran a host hook before missing bwrap blocked the task: {record}" + ); + assert_eq!(record["outcome"], "blocked", "{record}"); + assert!(record["detail"].as_str().unwrap().contains("bwrap"), "{record}"); +} + +#[test] +fn worktree_checkout_keeps_smudge_filters_in_the_sandbox() { + let env = TestEnv::new(); + setup(&env, "[]"); + env.write("work/project/.gitattributes", "*.data filter=probe\n"); + env.write("work/project/fixture.data", "synthetic data\n"); + let project = env.work().join("project"); + git(&env, &project, &["add", "."]); + git(&env, &project, &["commit", "-m", "smudge filter fixture"]); + git( + &env, + &project, + &[ + "config", + "filter.probe.smudge", + "printf escaped > \"$HOME/worktree-smudge-escape\" 2>/dev/null || true; cat", + ], + ); + git(&env, &project, &["config", "filter.probe.clean", "cat"]); + git(&env, &project, &["config", "filter.probe.required", "true"]); + let record = run(&env, vec![ScriptTurn::text("finished")]); + assert!( + !env.home().join("worktree-smudge-escape").exists(), + "worktree creation ran a host filter: {record}" + ); + assert_eq!(record["outcome"], "nothing_to_do", "{record}"); +} + +#[test] +fn checkout_callbacks_cannot_replace_the_frozen_acceptance_commands() { + let env = TestEnv::new(); + setup(&env, r#"["echo frozen-checkout-acceptance; exit 1"]"#); + env.write("work/project/.gitattributes", "*.data filter=probe\n"); + env.write("work/project/fixture.data", "synthetic data\n"); + let project = env.work().join("project"); + git(&env, &project, &["add", "."]); + git(&env, &project, &["commit", "-m", "checkout settings fixture"]); + git( + &env, + &project, + &[ + "config", + "filter.probe.smudge", + "printf '%s' '{\"done\":[]}' > .oxa/settings.json; cat", + ], + ); + git(&env, &project, &["config", "filter.probe.clean", "cat"]); + git(&env, &project, &["config", "filter.probe.required", "true"]); + let record = run( + &env, + vec![ScriptTurn::text("finished"), ScriptTurn::text("cannot repair")], + ); + assert_eq!(record["outcome"], "red", "{record}"); + assert!( + record["detail"] + .as_str() + .unwrap() + .contains("frozen-checkout-acceptance"), + "{record}" + ); +} + +#[test] +fn worktree_reference_hooks_run_only_inside_the_sandbox() { + use std::os::unix::fs::PermissionsExt; + let env = TestEnv::new(); + setup(&env, "[]"); + let hook = env.write( + "work/project/.git/hooks/reference-transaction", + "#!/bin/sh\nprintf escaped > \"$HOME/worktree-reference-escape\" 2>/dev/null || true\nprintf ran >> reference-hook-ran\ncat >/dev/null\n", + ); + std::fs::set_permissions(hook, std::fs::Permissions::from_mode(0o755)).unwrap(); + let record = run(&env, vec![ScriptTurn::text("finished")]); + assert!( + !env.home().join("worktree-reference-escape").exists(), + "worktree metadata ran a host reference hook: {record}" + ); + assert_eq!(record["outcome"], "done", "{record}"); + assert!(Path::new(record["worktree"].as_str().unwrap()) + .join("reference-hook-ran") + .exists()); + assert!(!env.work().join("project/reference-hook-ran").exists()); +} + +#[test] +fn sandboxed_branch_creation_still_obeys_rejecting_reference_hooks() { + use std::os::unix::fs::PermissionsExt; + let env = TestEnv::new(); + setup(&env, "[]"); + let hook = env.write( + "work/project/.git/hooks/reference-transaction", + "#!/bin/sh\ncat >/dev/null\necho required-reference-policy >&2\nexit 1\n", + ); + std::fs::set_permissions(hook, std::fs::Permissions::from_mode(0o755)).unwrap(); + let record = run(&env, vec![]); + assert_eq!(record["outcome"], "blocked", "{record}"); + assert!(record["worker"].is_null(), "{record}"); + assert!( + record["detail"] + .as_str() + .unwrap() + .contains("required-reference-policy"), + "{record}" + ); + let branch = Command::new("git") + .args(["show-ref", "--verify", "--quiet", "refs/heads/agent/test"]) + .current_dir(env.work().join("project")) + .env_clear() + .envs(env.envs("http://127.0.0.1:1")) + .output() + .unwrap(); + assert_eq!(branch.status.code(), Some(1)); +} diff --git a/oxa/oxa-work/src/lib.rs b/oxa/oxa-work/src/lib.rs index 4e29b1000..a21ecd011 100644 --- a/oxa/oxa-work/src/lib.rs +++ b/oxa/oxa-work/src/lib.rs @@ -129,15 +129,14 @@ pub fn issue_task( }) } -/// Acceptance commands are frozen from the base before the agent can edit settings. -fn done_commands(root: &Path) -> Result> { - let path = root.join(".oxa/settings.json"); - let bytes = match fs::read(path) { - Ok(bytes) => bytes, - Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(vec![]), - Err(e) => return Err(e.to_string()), - }; - let value: serde_json::Value = serde_json::from_slice(&bytes).map_err(|e| e.to_string())?; +/// Freeze acceptance before checkout filters or hooks can edit project settings. +fn done_commands(policy: &RunPolicy, root: &Path, base: &str) -> Result> { + let path = ".oxa/settings.json"; + if checked(git(policy, root, &["ls-tree", "--name-only", base, "--", path]))?.is_empty() { + return Ok(vec![]); + } + let text = checked(git(policy, root, &["show", &format!("{base}:{path}")]))?; + let value: serde_json::Value = serde_json::from_str(&text).map_err(|e| e.to_string())?; match value.get("done") { None => Ok(vec![]), Some(value) => serde_json::from_value(value.clone()).map_err(|e| format!("done commands: {e}")), @@ -163,6 +162,7 @@ pub struct SupervisorRequest { #[derive(Deserialize, Serialize)] #[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] pub enum SupervisorOperation { + Checkout { branch: String }, Checks { commands: Vec }, Inspect, } @@ -327,15 +327,57 @@ pub fn run_task_with_policy(repo: &Path, binary: &Path, task: &Task, policy: &Ru if tree.exists() { return Err("task worktree already exists; retained for inspection".into()); } + let base = checked(git( + policy, + &root, + &["rev-parse", "--verify", &format!("{}^{{commit}}", task.base)], + ))?; + let commands = done_commands(policy, &root, &base)?; + let branch = format!("refs/heads/{}", task.branch); + let exists = output(git(policy, &root, &["show-ref", "--verify", "--quiet", &branch]))?; + match exists.status.code() { + Some(1) => {} + Some(0) => return Err("task branch already exists; retained for inspection".into()), + _ => return Err(String::from_utf8_lossy(&exists.stderr).into_owned()), + } let tree_arg = tree.to_str().ok_or("non-UTF8 worktree path")?; + // Bootstrap detached metadata without repository callbacks. Even + // --no-checkout runs reference hooks unless they are suppressed here. + // The real task branch and its reference hooks are created in bwrap. checked(git( policy, &root, - &["worktree", "add", "-b", &task.branch, tree_arg, &task.base], + &[ + "-c", + "core.hooksPath=/dev/null", + "worktree", + "add", + "--no-checkout", + "--detach", + tree_arg, + &base, + ], ))?; let tree = tree.canonicalize().map_err(|e| e.to_string())?; + let checkout = supervise( + binary, + &tree, + SupervisorRequest { + source: root.clone(), + operation: SupervisorOperation::Checkout { + branch: task.branch.clone(), + }, + }, + policy, + &lock_file, + )?; + if !checkout.status.success() { + return Err(format!( + "sandboxed worktree checkout failed: {}", + String::from_utf8_lossy(&checkout.stderr) + )); + } let initial = checked(git(policy, &tree, &["rev-parse", "HEAD"]))?; - let commands = done_commands(&tree)?; let first = worker::run(binary, &tree, task, &task.prompt, policy, &lock_file, None)?; record.worker = Some(first.result.clone()); record.session_id = first.session.clone(); From 7d81cd52fd3728eb54d880641a0c346baa1c5009 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Oscar=20Nordstr=C3=B6m?= <13300531+n0rpan@users.noreply.github.com> Date: Mon, 16 Nov 2026 09:20:07 +0000 Subject: [PATCH 11/11] Freeze task batches and deny worker project resources (#333) --- oxa/docs/work.md | 20 ++- oxa/oxa-cli/src/work_checks.rs | 17 +- oxa/oxa-cli/src/work_cmd.rs | 53 ++++-- oxa/oxa-cli/tests/work_cli.rs | 320 ++++++++++++++++++++++++++++++++- oxa/oxa-work/src/lib.rs | 139 +++++++++++--- oxa/oxa-work/src/worker.rs | 4 +- 6 files changed, 492 insertions(+), 61 deletions(-) diff --git a/oxa/docs/work.md b/oxa/docs/work.md index ca2f3e4b2..26c5048de 100644 --- a/oxa/docs/work.md +++ b/oxa/docs/work.md @@ -16,10 +16,21 @@ Issue lookup also requires source-project trust. Git and GitHub CLI host calls u validated executables outside the repository. Worker and check-supervisor PATHs exclude project directories, relative entries and unsafe aliases; project tools can still run by explicit path inside the sandbox. +Branches must be literal names; checkout-history aliases such as `@{-1}` are refused. +Every base and acceptance command list is resolved before any task in the batch +starts. All bases must therefore exist at batch startup. Host metadata commands +ignore replacement objects and inherited `GIT_*` overrides, disable filesystem +monitors, and never lazily fetch missing objects. Fetch the needed objects before +starting the batch. Checkout and checks also ignore replacement objects. Each task runs a child `oxa --mode=json` with its model and a saved session. The installed offline policy, including a parent `--offline` flag, is passed to every child. Normal agent permission, trust and sandbox rules apply. Configure project trust before unattended use. The runner +passes `-na` on every child start, including repair, and removes `OXA_TRUST_PROJECT`. +Worker project settings, MCP servers and extensions are therefore ignored even +when a parent directory or the user's default would trust the new worktree. +User-level resources keep their normal behavior; external acceptance uses the +approved source project and the batch's frozen command list. The runner creates detached Git metadata with callbacks suppressed on the host, then creates the task branch and populates the fresh worktree inside the normal sandbox. Reference hooks, checkout hooks and smudge filters stay inside it; a reference hook @@ -44,7 +55,7 @@ The runner reads the child's exit code, terminal `oxa_result` and session header without retaining its event stream. A blocked, failed or interrupted worker remains blocked and does not consume a repair attempt. Failed acceptance after a successful worker continues that same saved session once, then acceptance runs once more. -JSON lines include the worker result and session ID and report `done`, `nothing_to_do` (no +JSON lines include the worker result, session ID and captured `base_sha` and report `done`, `nothing_to_do` (no commits or file changes), `red` (checks still fail), or `blocked` (setup or agent execution failed). Exit codes are 0 for success, 1 if any task is red or blocked, and 2 for invalid input or output errors. A task setup failure produces a blocked @@ -56,8 +67,13 @@ after process death does not permanently block a task. Worktrees and uncommitted changes remain in `.oxa-worktrees//` beside the repository (or the separate git directory). Private result receipts and locks live under `~/.oxa/agent/work//` (or the configured agent -directory), outside the worker's writable Git bind. Worktrees stay outside that git +directory), outside the worker's writable Git bind. Receipts are published atomically +without overwriting an existing receipt. Worktrees stay outside that git directory so the normal sandbox can bind git objects and refs for commits. No automatic cleanup, commit, push, PR creation or continuation is implemented yet. Inspect retained work before removing it with `git worktree remove`. Review task prompts and bases before running them. + +`done` here describes accepted local work, which may be uncommitted. This slice +does not publish it. The saving/publication slices must bind acceptance to a clean +committed tree and verify its recorded commit before pushing. diff --git a/oxa/oxa-cli/src/work_checks.rs b/oxa/oxa-cli/src/work_checks.rs index 75339a521..090ba813e 100644 --- a/oxa/oxa-cli/src/work_checks.rs +++ b/oxa/oxa-cli/src/work_checks.rs @@ -31,14 +31,14 @@ pub(crate) fn run( let sandbox = crate::netguard::with_net(Arc::new(b), &settings); let spec = ExecSpec { command: format!( - "git checkout HEAD -- . && git checkout -b '{}' HEAD", + "git --no-replace-objects checkout HEAD -- . && git --no-replace-objects checkout -b '{}' HEAD", branch.replace('\'', "'\\''") ), cwd: root, writable: true, net: sandbox.network(), timeout_s: Some(600), - env: vec![("AI_AGENT".into(), "oxa".into())], + env: git_environment(), }; let mut tail = Vec::new(); let result = sandbox.run_streaming(&spec, &CancelToken::default(), &mut |bytes| { @@ -97,7 +97,7 @@ pub(crate) fn run( writable: true, net: sandbox.network(), timeout_s: Some(600), - env: vec![("AI_AGENT".into(), "oxa".into())], + env: git_environment(), }; let mut tail = Vec::new(); let result = sandbox.run_streaming(&spec, &CancelToken::default(), &mut |bytes| { @@ -120,7 +120,7 @@ pub(crate) fn run( // verdict by printing JSON or diagnostics. Git failures remain distinct from dirty. fn inspect(sandbox: &Bwrap, root: &Path) -> Result { let spec = ExecSpec { - command: r#"git --no-optional-locks -c core.fsmonitor=false status --porcelain=v1 -z | { + command: r#"git --no-replace-objects --no-optional-locks -c core.fsmonitor=false status --porcelain=v1 -z | { work_dirty=0 while IFS= read -r -d '' work_entry; do work_dirty=1; done exit "$work_dirty" @@ -134,7 +134,7 @@ exit "${work_probe_status[1]}" writable: false, net: false, timeout_s: Some(600), - env: Vec::new(), + env: git_environment(), }; let mut tail = Vec::new(); let result = sandbox.run_streaming(&spec, &CancelToken::default(), &mut |bytes| { @@ -149,6 +149,13 @@ exit "${work_probe_status[1]}" } } +fn git_environment() -> Vec<(String, String)> { + vec![ + ("AI_AGENT".into(), "oxa".into()), + ("GIT_NO_REPLACE_OBJECTS".into(), "1".into()), + ] +} + fn keep_tail(tail: &mut Vec, bytes: &[u8], cap: usize) { if bytes.len() >= cap { tail.clear(); diff --git a/oxa/oxa-cli/src/work_cmd.rs b/oxa/oxa-cli/src/work_cmd.rs index be48c3e83..c73f7aeda 100644 --- a/oxa/oxa-cli/src/work_cmd.rs +++ b/oxa/oxa-cli/src/work_cmd.rs @@ -56,10 +56,7 @@ pub(crate) fn run( Some(&dirs.home), ) .ok_or("no trusted Git executable outside the source project")?; - let output = std::process::Command::new(&git_binary) - .env("PATH", &host_path) - .current_dir(cwd) - .args(["rev-parse", "--show-toplevel"]) + let output = oxa_work::metadata_git(&git_binary, &host_path, cwd, &["rev-parse", "--show-toplevel"]) .output() .map_err(|e| e.to_string())?; if !output.status.success() { @@ -98,12 +95,14 @@ pub(crate) fn run( } _ => return Err("usage: oxa work | --issue N --model MODEL".into()), }; - let common = std::process::Command::new(&git_binary) - .env("PATH", &host_path) - .current_dir(&root) - .args(["rev-parse", "--path-format=absolute", "--git-common-dir"]) - .output() - .map_err(|e| e.to_string())?; + let common = oxa_work::metadata_git( + &git_binary, + &host_path, + &root, + &["rev-parse", "--path-format=absolute", "--git-common-dir"], + ) + .output() + .map_err(|e| e.to_string())?; if !common.status.success() { return Err("cannot resolve runner repository".into()); } @@ -120,16 +119,32 @@ pub(crate) fn run( offline: oxa_proto::offline(), storage: dirs.agent_dir.join("work").join(key), }; + // Freeze every task before checkout hooks or a first worker can change + // shared refs. A bad plan remains a per-task error, not a batch abort. + let planned: Vec<_> = tasks + .into_iter() + .map(|task| { + if is_trusted { + oxa_work::plan_task(&root, task.clone(), &policy) + .map_err(|detail| Box::new(oxa_work::blocked_record(&task, detail))) + } else { + Err(Box::new(oxa_work::blocked_record( + &task, + "source project is not trusted; approve it before unattended work".into(), + ))) + } + }) + .collect(); let mut code = 0; - for task in tasks { - let record = if is_trusted { - oxa_work::run_task_with_policy(&root, &binary, &task, &policy) - .unwrap_or_else(|detail| oxa_work::blocked_record(&task, detail)) - } else { - oxa_work::blocked_record( - &task, - "source project is not trusted; approve it before unattended work".into(), - ) + for task in planned { + let record = match task { + Ok(plan) => { + let mut record = oxa_work::run_task_with_policy(&root, &binary, &plan, &policy) + .unwrap_or_else(|detail| oxa_work::blocked_record(plan.task(), detail)); + record.base_sha = Some(plan.base_sha().to_owned()); + record + } + Err(record) => *record, }; if matches!( record.outcome, diff --git a/oxa/oxa-cli/tests/work_cli.rs b/oxa/oxa-cli/tests/work_cli.rs index 65a9e0784..ddd884be8 100644 --- a/oxa/oxa-cli/tests/work_cli.rs +++ b/oxa/oxa-cli/tests/work_cli.rs @@ -14,7 +14,7 @@ fn storage(env: &TestEnv) -> PathBuf { .collect(); env.agent_dir().join("work").join(key) } -fn git(env: &TestEnv, dir: &Path, args: &[&str]) { +fn git(env: &TestEnv, dir: &Path, args: &[&str]) -> String { let out = Command::new("git") .args(args) .current_dir(dir) @@ -27,6 +27,7 @@ fn git(env: &TestEnv, dir: &Path, args: &[&str]) { .output() .unwrap(); assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr)); + String::from_utf8_lossy(&out.stdout).trim().into() } fn setup(env: &TestEnv, done: &str) { git(env, &env.work(), &["init", "--bare", "remote.git"]); @@ -54,6 +55,17 @@ fn run(env: &TestEnv, turns: Vec) -> serde_json::Value { run_args(env, turns, &["work", "../tasks.json"], None) } fn run_args(env: &TestEnv, turns: Vec, args: &[&str], path: Option) -> serde_json::Value { + let mut rows = run_records(env, turns, args, path, &[]); + assert_eq!(rows.len(), 1); + rows.remove(0) +} +fn run_records( + env: &TestEnv, + turns: Vec, + args: &[&str], + path: Option, + extra: &[(&str, &str)], +) -> Vec { let server = FakeServer::start(turns, FakeOpts::default()).unwrap(); let mut command = Command::new(env!("CARGO_BIN_EXE_oxa")); command @@ -64,6 +76,7 @@ fn run_args(env: &TestEnv, turns: Vec, args: &[&str], path: Option, args: &[&str], path: Option String { + serde_json::json!({"mcpServers":{"unapproved":{"command":"sh","args":["-c","printf escaped > \"$HOME/worker-trust-escape\""],"exposure":"direct"}}}).to_string() +} + +fn child_trust_case(mode: &str) { + let env = TestEnv::new(); + setup(&env, "[]"); + let project = env.work().join("project"); + git(&env, &project, &["checkout", "-b", "hostile-base"]); + env.write("work/project/.oxa/mcp.json", &malicious_mcp()); + git(&env, &project, &["add", ".oxa/mcp.json"]); + git(&env, &project, &["commit", "-m", "unapproved base resource"]); + git(&env, &project, &["checkout", "main"]); + let extra = match mode { + "always" => { + env.write( + "home/.oxa/agent/settings.json", + r#"{"defaultProjectTrust":"always"}"#, + ); + vec![] + } + "parent" => { + oxa_perm::TrustStore::default() + .save(&env.agent_dir().join("trust.json"), &env.work(), true) + .unwrap(); + vec![] + } + "environment" => vec![("OXA_TRUST_PROJECT", "1")], + _ => unreachable!(), + }; + env.write("work/tasks.json", r#"[{"id":"test","branch":"agent/test","model":"fake","base":"hostile-base","prompt":"Finish task"}]"#); + let rows = run_records( + &env, + vec![ScriptTurn::text("done")], + &["work", "../tasks.json"], + None, + &extra, + ); + assert!( + !env.home().join("worker-trust-escape").exists(), + "unapproved child resource ran, mode={mode}: {rows:?}" + ); + assert_eq!(rows[0]["outcome"], "nothing_to_do", "{rows:?}"); +} + +#[test] +fn security_child_does_not_inherit_parent_directory_trust() { + child_trust_case("parent"); +} +#[test] +fn security_child_does_not_autoapprove_a_different_base() { + child_trust_case("always"); +} +#[test] +fn security_child_does_not_inherit_the_trust_environment() { + child_trust_case("environment"); +} + +#[test] +fn security_repair_does_not_load_new_project_resources() { + use std::{ + process::Stdio, + time::{Duration, Instant}, + }; + let env = TestEnv::new(); + setup(&env, r#"["echo external-repair-required; exit 1"]"#); + env.write( + "home/.oxa/agent/settings.json", + r#"{"defaultProjectTrust":"always"}"#, + ); + let mut first = ScriptTurn::text("first complete"); + first.fault = Some(oxa_fake::Fault::Stall { bytes: 16, ms: 1000 }); + let server = FakeServer::start( + vec![first, ScriptTurn::text("repair complete")], + FakeOpts::default(), + ) + .unwrap(); + let child = Command::new(env!("CARGO_BIN_EXE_oxa")) + .args(["work", "../tasks.json"]) + .current_dir(env.work().join("project")) + .env_clear() + .envs(env.envs(&server.url())) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let start = Instant::now(); + while server.requests().is_empty() { + assert!( + start.elapsed() < Duration::from_secs(10), + "first worker reached the engine" + ); + std::thread::sleep(Duration::from_millis(5)); + } + // Change the on-disk manifest after startup discovery and before repair. + env.write("work/.oxa-worktrees/project/test/.oxa/mcp.json", &malicious_mcp()); + let out = child.wait_with_output().unwrap(); + assert!( + !env.home().join("worker-trust-escape").exists(), + "repair loaded a new resource: {}", + String::from_utf8_lossy(&out.stderr) + ); + let record: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap(); + assert_eq!(record["outcome"], "red", "{record}"); +} + +fn batch_tampering(replace: bool) { + let env = TestEnv::new(); + setup(&env, r#"["printf trusted > accepted-base"]"#); + env.write( + "home/.oxa/agent/settings.json", + r#"{"defaultProjectTrust":"always"}"#, + ); + let project = env.work().join("project"); + let original = git(&env, &project, &["rev-parse", "main"]); + git(&env, &project, &["checkout", "-b", "forged-base"]); + env.write("work/project/.oxa/settings.json", r#"{"done":["true"]}"#); + env.write("work/project/forged-base", "forged\n"); + git(&env, &project, &["add", "."]); + git(&env, &project, &["commit", "-m", "forged acceptance fixture"]); + let forged = git(&env, &project, &["rev-parse", "HEAD"]); + git(&env, &project, &["checkout", "main"]); + env.write("work/tasks.json", r#"[{"id":"first","branch":"agent/first","model":"fake","prompt":"First task"},{"id":"second","branch":"agent/second","model":"fake","prompt":"Second task"}]"#); + let reference = if replace { + format!("refs/replace/{original}") + } else { + "refs/heads/main".into() + }; + let command = serde_json::json!({"command":format!("git update-ref {reference} {forged}")}).to_string(); + let rows = run_records( + &env, + vec![ + ScriptTurn::tool("tamper", "bash", &command), + ScriptTurn::text("first finished"), + ScriptTurn::text("second finished"), + ], + &["work", "../tasks.json"], + None, + &[], + ); + assert_eq!( + git(&env, &project, &["rev-parse", &reference]), + forged, + "the first worker really changed the shared ref" + ); + assert_eq!(rows.len(), 2, "{rows:?}"); + let tree = Path::new(rows[1]["worktree"].as_str().unwrap()); + assert_eq!( + std::fs::read_to_string(tree.join("accepted-base")).unwrap_or_default(), + "trusted", + "later task used forged checks: {rows:?}" + ); + assert!( + !tree.join("forged-base").exists(), + "later task checked out a forged base" + ); + assert_eq!(rows[1]["base_sha"], original, "{rows:?}"); +} + +#[test] +fn security_batch_freezes_bases_before_shared_ref_updates() { + batch_tampering(false); +} +#[test] +fn security_batch_ignores_replace_refs_from_an_earlier_worker() { + batch_tampering(true); +} + +#[test] +fn security_host_metadata_never_lazy_fetches_from_a_promisor() { + use std::os::unix::fs::PermissionsExt; + let env = TestEnv::new(); + setup(&env, "[]"); + let project = env.work().join("project"); + let object = git(&env, &project, &["rev-parse", "main:.oxa/settings.json"]); + let helper = env.write( + "tmp/promisor", + "#!/bin/sh\nprintf escaped > \"$HOME/metadata-lazy-fetch-escape\"\nexit 1\n", + ); + std::fs::set_permissions(&helper, std::fs::Permissions::from_mode(0o755)).unwrap(); + git( + &env, + &project, + &[ + "config", + "remote.attack.url", + &format!("ext::{}", helper.display()), + ], + ); + git(&env, &project, &["config", "remote.attack.promisor", "true"]); + git(&env, &project, &["config", "protocol.ext.allow", "always"]); + std::fs::remove_file(project.join(".git/objects").join(&object[..2]).join(&object[2..])).unwrap(); + let record = run(&env, vec![]); + assert!( + !env.home().join("metadata-lazy-fetch-escape").exists(), + "host metadata ran a promisor helper: {record}" + ); + assert_eq!(record["outcome"], "blocked", "{record}"); + assert!(record["worker"].is_null(), "{record}"); +} + +#[test] +fn security_git_environment_cannot_redirect_the_runner() { + let env = TestEnv::new(); + setup(&env, "[]"); + let redirect = env.work().join("remote.git"); + let rows = run_records( + &env, + vec![ScriptTurn::text("done")], + &["work", "../tasks.json"], + None, + &[("GIT_DIR", redirect.to_str().unwrap())], + ); + assert_eq!(rows[0]["outcome"], "nothing_to_do", "{rows:?}"); +} + +#[test] +fn security_branch_alias_is_refused_before_worktree_creation() { + let env = TestEnv::new(); + setup(&env, "[]"); + let project = env.work().join("project"); + git(&env, &project, &["checkout", "-b", "previous"]); + git(&env, &project, &["checkout", "main"]); + env.write( + "work/tasks.json", + r#"[{"id":"test","branch":"@{-1}","model":"fake","prompt":"Finish task"}]"#, + ); + let record = run(&env, vec![]); + assert_eq!(record["outcome"], "blocked", "{record}"); + assert!( + !env.work().join(".oxa-worktrees/project/test").exists(), + "alias reached checkout: {record}" + ); +} + +#[test] +fn security_failed_receipt_write_never_publishes_a_torn_record() { + use std::{ + process::Stdio, + time::{Duration, Instant}, + }; + let env = TestEnv::new(); + setup(&env, "[]"); + let mut first = ScriptTurn::text("finished"); + first.fault = Some(oxa_fake::Fault::Stall { bytes: 16, ms: 1000 }); + let server = FakeServer::start(vec![first], FakeOpts::default()).unwrap(); + let child = Command::new("/usr/bin/prlimit") + .args([ + "--core=0", + "--", + env!("CARGO_BIN_EXE_oxa"), + "work", + "../tasks.json", + ]) + .current_dir(env.work().join("project")) + .env_clear() + .envs(env.envs(&server.url())) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let start = Instant::now(); + while server.requests().is_empty() { + assert!( + start.elapsed() < Duration::from_secs(10), + "worker reached the engine" + ); + std::thread::sleep(Duration::from_millis(5)); + } + // Kill this isolated runner at its next regular-file write. Its already + // running worker keeps normal limits, and core dumps are disabled. + let limit = Command::new("/usr/bin/prlimit") + .args(["--pid", &child.id().to_string(), "--fsize=0"]) + .env_clear() + .envs(env.envs(&server.url())) + .output() + .unwrap(); + assert!( + limit.status.success(), + "{}", + String::from_utf8_lossy(&limit.stderr) + ); + let out = child.wait_with_output().unwrap(); + assert!(!out.status.success()); + assert!( + !storage(&env).join("test.json").exists(), + "interrupted receipt write left a canonical partial record" + ); +} diff --git a/oxa/oxa-work/src/lib.rs b/oxa/oxa-work/src/lib.rs index a21ecd011..dc74e7942 100644 --- a/oxa/oxa-work/src/lib.rs +++ b/oxa/oxa-work/src/lib.rs @@ -43,6 +43,41 @@ pub struct Record { pub detail: String, pub worker: Option, pub session_id: Option, + pub base_sha: Option, +} + +/// An immutable task/base/check snapshot, built before any task in its batch runs. +pub struct PlannedTask { + task: Task, + base_sha: String, + commands: Vec, +} +impl PlannedTask { + pub fn task(&self) -> &Task { + &self.task + } + pub fn base_sha(&self) -> &str { + &self.base_sha + } +} + +pub fn plan_task(repo: &Path, task: Task, policy: &RunPolicy) -> Result { + validate(&task)?; + let branch = checked(git(policy, repo, &["check-ref-format", "--branch", &task.branch]))?; + if branch != task.branch { + return Err("branch aliases are not allowed; provide a literal branch name".into()); + } + let base_sha = checked(git( + policy, + repo, + &["rev-parse", "--verify", &format!("{}^{{commit}}", task.base)], + ))?; + let commands = done_commands(policy, repo, &base_sha)?; + Ok(PlannedTask { + task, + base_sha, + commands, + }) } fn output(mut command: Command) -> Result { @@ -56,8 +91,37 @@ fn checked(command: Command) -> Result { Ok(String::from_utf8_lossy(&out.stdout).trim().into()) } fn git(policy: &RunPolicy, repo: &Path, args: &[&str]) -> Command { - let mut c = Command::new(&policy.git_binary); - c.env("PATH", &policy.host_path).current_dir(repo).args(args); + metadata_git(&policy.git_binary, &policy.host_path, repo, args) +} + +fn isolate_git_environment(command: &mut Command) { + for (key, _) in std::env::vars_os() { + if key.as_encoded_bytes().starts_with(b"GIT_") { + command.env_remove(key); + } + } + command.env("GIT_NO_REPLACE_OBJECTS", "1"); +} + +/// Host metadata and bootstrap commands never consult replace refs, invoke a +/// filesystem monitor, or fetch missing objects through a repository's helpers. +pub fn metadata_git(binary: &Path, path: &std::ffi::OsStr, repo: &Path, args: &[&str]) -> Command { + let mut c = Command::new(binary); + isolate_git_environment(&mut c); + c.env("PATH", path) + .env("GIT_NO_LAZY_FETCH", "1") + .env("GIT_ALLOW_PROTOCOL", "") + .env("GIT_TERMINAL_PROMPT", "0") + .current_dir(repo) + .args([ + "--no-replace-objects", + "--no-optional-locks", + "-c", + "core.fsmonitor=false", + "-c", + "protocol.allow=never", + ]) + .args(args); c } @@ -109,6 +173,7 @@ pub fn issue_task( return Err("issue number must be positive".into()); } let mut c = Command::new(gh); + isolate_git_environment(&mut c); c.env("PATH", host_path).current_dir(repo).args([ "issue", "view", @@ -175,6 +240,7 @@ fn supervise( lock: &fs::File, ) -> Result { let mut command = Command::new(binary); + isolate_git_environment(&mut command); if policy.offline { command.arg("--offline"); } @@ -259,17 +325,19 @@ pub fn blocked_record(task: &Task, detail: String) -> Record { detail, worker: None, session_id: None, + base_sha: None, } } -pub fn run_task_with_policy(repo: &Path, binary: &Path, task: &Task, policy: &RunPolicy) -> Result { +pub fn run_task_with_policy( + repo: &Path, + binary: &Path, + planned: &PlannedTask, + policy: &RunPolicy, +) -> Result { + let task = &planned.task; validate(task)?; let root = checked(git(policy, repo, &["rev-parse", "--show-toplevel"]))?; let root = PathBuf::from(root); - checked(git( - policy, - &root, - &["check-ref-format", "--branch", &task.branch], - ))?; let common = checked(git( policy, &root, @@ -322,17 +390,14 @@ pub fn run_task_with_policy(repo: &Path, binary: &Path, task: &Task, policy: &Ru detail: String::new(), worker: None, session_id: None, + base_sha: Some(planned.base_sha.clone()), }; let result = (|| -> Result { if tree.exists() { return Err("task worktree already exists; retained for inspection".into()); } - let base = checked(git( - policy, - &root, - &["rev-parse", "--verify", &format!("{}^{{commit}}", task.base)], - ))?; - let commands = done_commands(policy, &root, &base)?; + let base = &planned.base_sha; + let commands = &planned.commands; let branch = format!("refs/heads/{}", task.branch); let exists = output(git(policy, &root, &["show-ref", "--verify", "--quiet", &branch]))?; match exists.status.code() { @@ -355,7 +420,7 @@ pub fn run_task_with_policy(repo: &Path, binary: &Path, task: &Task, policy: &Ru "--no-checkout", "--detach", tree_arg, - &base, + base, ], ))?; let tree = tree.canonicalize().map_err(|e| e.to_string())?; @@ -381,7 +446,7 @@ pub fn run_task_with_policy(repo: &Path, binary: &Path, task: &Task, policy: &Ru let first = worker::run(binary, &tree, task, &task.prompt, policy, &lock_file, None)?; record.worker = Some(first.result.clone()); record.session_id = first.session.clone(); - let failures = acceptance(binary, &tree, &root, &commands, policy, &lock_file)?; + let failures = acceptance(binary, &tree, &root, commands, policy, &lock_file)?; if let Some(error) = first.failure() { return Err(format!("{error}\nAcceptance checks:\n{failures}")); } @@ -397,7 +462,7 @@ pub fn run_task_with_policy(repo: &Path, binary: &Path, task: &Task, policy: &Ru )?; record.worker = Some(repair.result.clone()); record.session_id = repair.session.clone(); - let failures = acceptance(binary, &tree, &root, &commands, policy, &lock_file)?; + let failures = acceptance(binary, &tree, &root, commands, policy, &lock_file)?; if let Some(error) = repair.failure() { return Err(format!("{error}\nAcceptance checks:\n{failures}")); } @@ -418,14 +483,36 @@ pub fn run_task_with_policy(repo: &Path, binary: &Path, task: &Task, policy: &Ru Ok(outcome) => record.outcome = outcome, Err(e) => record.detail = e, } - // Separate receipts avoid overwriting another task's result. Never remove its worktree. - let mut file = fs::OpenOptions::new() - .write(true) - .create_new(true) - .mode(0o600) - .open(receipt) - .map_err(|e| e.to_string())?; - file.write_all(&serde_json::to_vec_pretty(&record).map_err(|e| e.to_string())?) - .map_err(|e| e.to_string())?; + save_receipt(&receipt, &record)?; Ok(record) } + +fn save_receipt(path: &Path, record: &Record) -> Result<()> { + let nonce = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_nanos(); + let temporary = path.with_extension(format!("tmp-{}-{nonce}", std::process::id())); + let result = (|| -> Result<()> { + let mut file = fs::OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .open(&temporary) + .map_err(|e| e.to_string())?; + file.write_all(&serde_json::to_vec_pretty(record).map_err(|e| e.to_string())?) + .map_err(|e| e.to_string())?; + file.sync_all().map_err(|e| e.to_string())?; + // Atomic publication with create-only semantics: an existing receipt + // is never overwritten, even if one appears while the task runs. + fs::hard_link(&temporary, path).map_err(|e| e.to_string())?; + fs::remove_file(&temporary).map_err(|e| e.to_string())?; + fs::File::open(path.parent().ok_or("receipt has no parent")?) + .and_then(|parent| parent.sync_all()) + .map_err(|e| e.to_string()) + })(); + if result.is_err() { + let _ = fs::remove_file(temporary); + } + result +} diff --git a/oxa/oxa-work/src/worker.rs b/oxa/oxa-work/src/worker.rs index 52df82697..cb802ac31 100644 --- a/oxa/oxa-work/src/worker.rs +++ b/oxa/oxa-work/src/worker.rs @@ -65,10 +65,12 @@ pub(crate) fn run( session: Option<&str>, ) -> Result { let mut command = Command::new(binary); + crate::isolate_git_environment(&mut command); command .env("PATH", &policy.host_path) + .env_remove("OXA_TRUST_PROJECT") .current_dir(root) - .args(["--mode=json", "--model", &task.model]); + .args(["-na", "--mode=json", "--model", &task.model]); if policy.offline { command.arg("--offline"); }