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 1/7] 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 2/7] 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 3/7] 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 c86fa8b9bf3df4ae49612e9458f2fa51aad354bd 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:50:25 +0000 Subject: [PATCH 4/7] Continue work branches with ordinary base merges (#333) --- oxa/docs/work.md | 16 ++- oxa/oxa-cli/tests/common/work.rs | 79 +++++++++++ oxa/oxa-cli/tests/work_cli.rs | 75 ++-------- oxa/oxa-cli/tests/work_continue.rs | 215 +++++++++++++++++++++++++++++ oxa/oxa-work/src/lib.rs | 43 ++---- oxa/oxa-work/src/tree.rs | 147 ++++++++++++++++++++ 6 files changed, 477 insertions(+), 98 deletions(-) create mode 100644 oxa/oxa-cli/tests/common/work.rs create mode 100644 oxa/oxa-cli/tests/work_continue.rs create mode 100644 oxa/oxa-work/src/tree.rs diff --git a/oxa/docs/work.md b/oxa/docs/work.md index ed74c8ab8..0772b2b76 100644 --- a/oxa/docs/work.md +++ b/oxa/docs/work.md @@ -8,7 +8,9 @@ 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 +IDs and branches must be unique within one file. A new branch starts from `base`; +an existing branch is continued with a normal merge of that base before the agent +starts. No remote fetch happens automatically. 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. @@ -20,6 +22,8 @@ agent after it exits, even without edits. These are trusted project shell comman 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. +On continued branches, acceptance commands are read from the captured base commit, +even when the task branch has changed its own settings. 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 @@ -31,6 +35,14 @@ 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 +cleanup, commit, push or PR creation is implemented yet. + +To continue a task, run the same file again. The retained receipt must match its +ID, branch and worktree. A clean worktree is reused; a branch checked out elsewhere +is blocked. Uncommitted changes are retained and blocked until you commit them. +Merge conflicts are passed to the agent with the merge still in progress, the +conflicted file list and merge output. An unfinished merge can be continued on a +later run. The agent must finish the merge commit and keep the task branch selected; +unresolved or aborted base merges remain blocked even when checks would pass. Inspect retained work before removing it with `git worktree remove`. Review task prompts and bases before running them. diff --git a/oxa/oxa-cli/tests/common/work.rs b/oxa/oxa-cli/tests/common/work.rs new file mode 100644 index 000000000..44062a99f --- /dev/null +++ b/oxa/oxa-cli/tests/common/work.rs @@ -0,0 +1,79 @@ +use oxa_fake::{FakeOpts, FakeServer, ScriptTurn, TestEnv}; +use std::{path::Path, process::Command}; +pub fn git(env: &TestEnv, dir: &Path, args: &[&str]) -> String { + 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)); + String::from_utf8_lossy(&out.stdout).trim().into() +} +pub 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"); + git(env, &project, &["config", "user.name", "Test"]); + git(env, &project, &["config", "user.email", "test@example.invalid"]); + 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"}]"#, + ); +} +pub fn run(env: &TestEnv, turns: Vec) -> serde_json::Value { + run_args(env, turns, &["work", "../tasks.json"], None) +} +pub fn run_args( + env: &TestEnv, + turns: Vec, + args: &[&str], + path: Option, +) -> serde_json::Value { + run_observed(env, turns, args, path).0 +} +pub fn run_observed( + env: &TestEnv, + turns: Vec, + args: &[&str], + path: Option, +) -> (serde_json::Value, Vec) { + 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"); + let record = serde_json::from_slice(&out.stdout).unwrap_or_else(|e| { + panic!( + "{e}: {} / {}", + String::from_utf8_lossy(&out.stdout), + String::from_utf8_lossy(&out.stderr) + ) + }); + (record, server.requests()) +} diff --git a/oxa/oxa-cli/tests/work_cli.rs b/oxa/oxa-cli/tests/work_cli.rs index ec6279eef..52dc5f2ee 100644 --- a/oxa/oxa-cli/tests/work_cli.rs +++ b/oxa/oxa-cli/tests/work_cli.rs @@ -1,66 +1,9 @@ //! Real child oxa with fake engine and local bare git remote; no network. -use oxa_fake::{FakeOpts, FakeServer, ScriptTurn, TestEnv}; +#[path = "common/work.rs"] +mod work; +use oxa_fake::{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) - ) - }) -} +use work::{git, run, run_args, setup}; #[test] fn external_checks_run_without_edits_and_retain_worktree() { let env = TestEnv::new(); @@ -180,13 +123,17 @@ printf '%s' '{"title":"Synthetic task","body":"Fix the test fixture"}' assert_eq!(record["outcome"], "nothing_to_do", "{record}"); } #[test] -fn setup_failure_records_blocked_and_keeps_existing_branch() { +fn branch_checked_out_elsewhere_is_blocked() { let env = TestEnv::new(); setup(&env, "[]"); - git(&env, &env.work().join("project"), &["branch", "agent/test"]); + git( + &env, + &env.work().join("project"), + &["worktree", "add", "-b", "agent/test", "../other"], + ); let record = run(&env, vec![]); assert_eq!(record["outcome"], "blocked", "{record}"); - assert!(record["detail"].as_str().unwrap().contains("already exists")); + assert!(record["detail"].as_str().unwrap().contains("other")); } #[test] diff --git a/oxa/oxa-cli/tests/work_continue.rs b/oxa/oxa-cli/tests/work_continue.rs new file mode 100644 index 000000000..5c0c244a2 --- /dev/null +++ b/oxa/oxa-cli/tests/work_continue.rs @@ -0,0 +1,215 @@ +//! Continued branches merge the base before the real child agent starts. +#[path = "common/work.rs"] +mod work; +use oxa_fake::{ScriptTurn, TestEnv}; +use std::path::{Path, PathBuf}; +use work::{git, run, run_observed, setup}; + +fn project(env: &TestEnv) -> PathBuf { + env.work().join("project") +} +fn commit_file(env: &TestEnv, file: &str, content: &str) { + env.write(&format!("work/project/{file}"), content); + git(env, &project(env), &["add", file]); + git(env, &project(env), &["commit", "-m", "fixture update"]); +} +fn diverge(env: &TestEnv, conflict: bool) { + setup(env, "[]"); + commit_file(env, "shared.txt", "original\n"); + git(env, &project(env), &["checkout", "-b", "agent/test"]); + commit_file(env, "shared.txt", "task version\n"); + git(env, &project(env), &["checkout", "main"]); + commit_file( + env, + if conflict { "shared.txt" } else { "base.txt" }, + "base version\n", + ); +} +fn tree(record: &serde_json::Value) -> &Path { + Path::new(record["worktree"].as_str().unwrap()) +} +fn merge_head(env: &TestEnv, root: &Path) -> PathBuf { + PathBuf::from(git( + env, + root, + &["rev-parse", "--path-format=absolute", "--git-path", "MERGE_HEAD"], + )) +} +fn resolve_turns() -> Vec { + vec![ + ScriptTurn::tool( + "resolve", + "write", + r#"{"path":"shared.txt","content":"resolved\n"}"#, + ), + ScriptTurn::tool( + "commit", + "bash", + r#"{"command":"git add shared.txt && git commit --no-edit"}"#, + ), + ScriptTurn::text("merge finished"), + ] +} +fn trust(env: &TestEnv) { + env.write( + "home/.oxa/agent/settings.json", + r#"{"defaultProjectTrust":"always"}"#, + ); +} +#[test] +fn existing_branch_fast_forwards_to_base_before_agent() { + let env = TestEnv::new(); + setup(&env, "[]"); + git(&env, &project(&env), &["branch", "agent/test"]); + commit_file(&env, "base.txt", "from main\n"); + let record = run(&env, vec![ScriptTurn::text("nothing")]); + assert_eq!(record["outcome"], "nothing_to_do", "{record}"); + assert_eq!( + std::fs::read_to_string(tree(&record).join("base.txt")).unwrap(), + "from main\n" + ); + git( + &env, + &project(&env), + &["merge-base", "--is-ancestor", "main", "agent/test"], + ); +} +#[test] +fn divergent_branch_gets_normal_merge_without_losing_task_commit() { + let env = TestEnv::new(); + diverge(&env, false); + let record = run(&env, vec![ScriptTurn::text("nothing")]); + assert_eq!(record["outcome"], "nothing_to_do", "{record}"); + assert_eq!( + git(&env, tree(&record), &["rev-list", "--parents", "-n", "1", "HEAD"]) + .split_whitespace() + .count(), + 3 + ); + assert_eq!( + std::fs::read_to_string(tree(&record).join("shared.txt")).unwrap(), + "task version\n" + ); + assert!(tree(&record).join("base.txt").exists()); +} +#[test] +fn conflicts_reach_agent_with_merge_in_progress_and_stay_blocked_if_unresolved() { + let env = TestEnv::new(); + diverge(&env, true); + let (record, requests) = run_observed( + &env, + vec![ScriptTurn::text("cannot resolve")], + &["work", "../tasks.json"], + None, + ); + assert_eq!(record["outcome"], "blocked", "{record}"); + assert!(record["detail"].as_str().unwrap().contains("merge")); + assert!(merge_head(&env, tree(&record)).exists()); + assert!(std::fs::read_to_string(tree(&record).join("shared.txt")) + .unwrap() + .contains("<<<<<<<")); + let user = requests + .iter() + .flat_map(|r| &r.messages) + .filter_map(|m| m.content.as_deref()) + .collect::>() + .join("\n"); + assert!( + user.contains("Finish task") && user.contains("merge in progress") && user.contains("shared.txt"), + "{user}" + ); +} +#[test] +fn agent_can_resolve_and_commit_merge_inside_real_sandbox() { + let env = TestEnv::new(); + diverge(&env, true); + trust(&env); + let record = run(&env, resolve_turns()); + assert_eq!(record["outcome"], "done", "{record}"); + assert!(!merge_head(&env, tree(&record)).exists()); + assert_eq!( + std::fs::read_to_string(tree(&record).join("shared.txt")).unwrap(), + "resolved\n" + ); + assert_eq!( + std::fs::read_to_string(project(&env).join("shared.txt")).unwrap(), + "base version\n" + ); +} +#[test] +fn unresolved_merge_can_be_continued_without_resetting_it() { + let env = TestEnv::new(); + diverge(&env, true); + trust(&env); + let first = run(&env, vec![ScriptTurn::text("blocked")]); + assert_eq!(first["outcome"], "blocked", "{first}"); + let second = run(&env, resolve_turns()); + assert_eq!(second["outcome"], "done", "{second}"); + assert!(!merge_head(&env, tree(&second)).exists()); +} +#[test] +fn dirty_retained_worktree_is_blocked_without_dropping_edits() { + let env = TestEnv::new(); + setup(&env, "[]"); + trust(&env); + let first = run( + &env, + vec![ + ScriptTurn::tool("write", "write", r#"{"path":"notes.txt","content":"keep me"}"#), + ScriptTurn::text("done"), + ], + ); + assert_eq!(first["outcome"], "done", "{first}"); + let (record, requests) = run_observed(&env, vec![], &["work", "../tasks.json"], None); + assert_eq!(record["outcome"], "blocked", "{record}"); + assert!(requests.is_empty()); + assert_eq!( + std::fs::read_to_string(tree(&record).join("notes.txt")).unwrap(), + "keep me" + ); +} +#[test] +fn continued_branch_cannot_replace_base_acceptance_commands() { + let env = TestEnv::new(); + setup(&env, r#"["echo base-acceptance; exit 1"]"#); + git(&env, &project(&env), &["checkout", "-b", "agent/test"]); + commit_file(&env, ".oxa/settings.json", r#"{"done":[]}"#); + git(&env, &project(&env), &["checkout", "main"]); + let record = run( + &env, + vec![ScriptTurn::text("done"), ScriptTurn::text("still done")], + ); + assert_eq!(record["outcome"], "red", "{record}"); + assert!(record["detail"].as_str().unwrap().contains("base-acceptance")); +} + +#[test] +fn aborting_merge_cannot_report_green() { + let env = TestEnv::new(); + diverge(&env, true); + trust(&env); + let record = run( + &env, + vec![ + ScriptTurn::tool("abort", "bash", r#"{"command":"git merge --abort"}"#), + ScriptTurn::text("done"), + ], + ); + assert_eq!(record["outcome"], "blocked", "{record}"); + assert!(record["detail"].as_str().unwrap().contains("base is not merged")); +} +#[test] +fn changing_branch_cannot_report_green_for_task_branch() { + let env = TestEnv::new(); + setup(&env, "[]"); + trust(&env); + let record = run( + &env, + vec![ + ScriptTurn::tool("switch", "bash", r#"{"command":"git checkout -b alternate"}"#), + ScriptTurn::text("done"), + ], + ); + assert_eq!(record["outcome"], "blocked", "{record}"); + assert!(record["detail"].as_str().unwrap().contains("different branch")); +} diff --git a/oxa/oxa-work/src/lib.rs b/oxa/oxa-work/src/lib.rs index 4ea8a1551..02e9d52e9 100644 --- a/oxa/oxa-work/src/lib.rs +++ b/oxa/oxa-work/src/lib.rs @@ -1,4 +1,5 @@ //! Opt-in, sequential unattended task execution. Worktrees are retained on every outcome. +mod tree; use serde::{Deserialize, Serialize}; use std::fs; use std::path::{Path, PathBuf}; @@ -20,7 +21,7 @@ fn default_base() -> String { "main".into() } -#[derive(Clone, Copy, Debug, Serialize, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)] #[serde(rename_all = "snake_case")] pub enum Outcome { Done, @@ -29,7 +30,7 @@ pub enum Outcome { Blocked, } -#[derive(Debug, Serialize)] +#[derive(Debug, Deserialize, Serialize)] pub struct Record { pub id: String, pub branch: String, @@ -111,20 +112,6 @@ pub fn issue_task(repo: &Path, number: u64, model: String) -> Result { }) } -/// 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 { @@ -184,9 +171,6 @@ pub fn run_task(repo: &Path, binary: &Path, task: &Task) -> Result { .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()); - } // 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") { @@ -201,6 +185,7 @@ pub fn run_task(repo: &Path, binary: &Path, task: &Task) -> Result { 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); + tree::check_receipt(&receipt, &tree, task)?; let mut record = Record { id: task.id.clone(), branch: task.branch.clone(), @@ -209,18 +194,11 @@ pub fn run_task(repo: &Path, binary: &Path, task: &Task) -> Result { 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 prepared = tree::prepare(&root, &tree, task)?; 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 commands = tree::done_from_base(&tree, &prepared.base)?; + let first_agent = agent(binary, &tree, task, &prepared.prompt); + tree::ensure_merged(&tree, &prepared.base, &task.branch)?; let failures = acceptance(&tree, &commands)?; if !failures.is_empty() { let repair_agent = agent( @@ -229,9 +207,10 @@ pub fn run_task(repo: &Path, binary: &Path, task: &Task) -> Result { task, &format!( "{}\n\nExternal acceptance checks failed. Repair once:\n{failures}", - task.prompt + prepared.prompt ), ); + tree::ensure_merged(&tree, &prepared.base, &task.branch)?; let failures = acceptance(&tree, &commands)?; if !failures.is_empty() { record.detail = failures; @@ -243,7 +222,7 @@ pub fn run_task(repo: &Path, binary: &Path, task: &Task) -> Result { } let head = checked(git(&tree, &["rev-parse", "HEAD"]))?; let dirty = checked(git(&tree, &["status", "--porcelain"]))?; - Ok(if head == initial && dirty.is_empty() { + Ok(if head == prepared.initial && dirty.is_empty() { Outcome::NothingToDo } else { Outcome::Done diff --git a/oxa/oxa-work/src/tree.rs b/oxa/oxa-work/src/tree.rs new file mode 100644 index 000000000..48c8e5561 --- /dev/null +++ b/oxa/oxa-work/src/tree.rs @@ -0,0 +1,147 @@ +//! Worktree continuation uses ordinary merges; no reset, stash or force checkout. +use super::{checked, git, output, Result, Task}; +use std::fs; +use std::path::{Path, PathBuf}; + +pub(crate) struct Prepared { + pub initial: String, + pub base: String, + pub prompt: String, +} +fn git_path(tree: &Path, name: &str) -> Result { + checked(git( + tree, + &["rev-parse", "--path-format=absolute", "--git-path", name], + )) + .map(PathBuf::from) +} +fn merging(tree: &Path) -> Result { + Ok(git_path(tree, "MERGE_HEAD")?.exists()) +} +fn merge_prompt(tree: &Path, task: &Task, output: &str) -> Result { + let paths = checked(git(tree, &["diff", "--name-only", "--diff-filter=U"]))?; + Ok(format!("{}\n\nThere is a merge in progress from base {}. Resolve the conflicts, stage the resolutions, and finish the merge commit before completing the task. Preserve the task's existing work.\nConflicted paths:\n{paths}\nMerge output:\n{output}", task.prompt, task.base)) +} +pub(crate) fn prepare(repo: &Path, tree: &Path, task: &Task) -> Result { + let base = checked(git( + repo, + &["rev-parse", "--verify", &format!("{}^{{commit}}", task.base)], + ))?; + if !tree.exists() { + let branch = format!("refs/heads/{}", task.branch); + let exists = output(git(repo, &["show-ref", "--verify", "--quiet", &branch]))?; + let tree_arg = tree.to_str().ok_or("non-UTF8 worktree path")?; + match exists.status.code() { + Some(0) => { + checked(git(repo, &["worktree", "add", tree_arg, &task.branch]))?; + } + Some(1) => { + checked(git( + repo, + &["worktree", "add", "-b", &task.branch, tree_arg, &base], + ))?; + } + _ => return Err(String::from_utf8_lossy(&exists.stderr).into()), + } + } + let canonical = tree.canonicalize().map_err(|e| e.to_string())?; + let actual = PathBuf::from(checked(git(tree, &["rev-parse", "--show-toplevel"]))?); + let common = |p: &Path| -> Result { + PathBuf::from(checked(git( + p, + &["rev-parse", "--path-format=absolute", "--git-common-dir"], + ))?) + .canonicalize() + .map_err(|e| e.to_string()) + }; + if actual.canonicalize().map_err(|e| e.to_string())? != canonical || common(tree)? != common(repo)? { + return Err("retained directory is not this repository's task worktree".into()); + } + let branch = checked(git(tree, &["symbolic-ref", "--quiet", "HEAD"]))?; + if branch != format!("refs/heads/{}", task.branch) { + return Err("retained worktree is on a different branch".into()); + } + for operation in ["rebase-merge", "rebase-apply", "CHERRY_PICK_HEAD", "REVERT_HEAD"] { + if git_path(tree, operation)?.exists() { + return Err(format!("retained worktree has {operation} in progress")); + } + } + let initial = checked(git(tree, &["rev-parse", "HEAD"]))?; + if merging(tree)? { + return Ok(Prepared { + initial, + base, + prompt: merge_prompt(tree, task, "Resuming the retained merge.")?, + }); + } + if !checked(git(tree, &["status", "--porcelain"]))?.is_empty() { + return Err("retained worktree has uncommitted changes; commit them before continuing".into()); + } + let merged = output(git(tree, &["merge", "--no-edit", &base]))?; + if !merged.status.success() { + if !merging(tree)? { + return Err(format!( + "base merge failed: {}\n{}", + String::from_utf8_lossy(&merged.stdout), + String::from_utf8_lossy(&merged.stderr) + )); + } + return Ok(Prepared { + initial, + base, + prompt: merge_prompt( + tree, + task, + &format!( + "{}\n{}", + String::from_utf8_lossy(&merged.stdout), + String::from_utf8_lossy(&merged.stderr) + ), + )?, + }); + } + // A clean base-only merge is preparation, not new task work. + Ok(Prepared { + initial: checked(git(tree, &["rev-parse", "HEAD"]))?, + base, + prompt: task.prompt.clone(), + }) +} +pub(crate) fn ensure_merged(tree: &Path, base: &str, branch: &str) -> Result<()> { + if checked(git(tree, &["symbolic-ref", "--quiet", "HEAD"]))? != format!("refs/heads/{branch}") { + return Err("agent left the worktree on a different branch".into()); + } + if merging(tree)? || !checked(git(tree, &["diff", "--name-only", "--diff-filter=U"]))?.is_empty() { + return Err("merge remains in progress; retained for resolution".into()); + } + if !output(git(tree, &["merge-base", "--is-ancestor", base, "HEAD"]))? + .status + .success() + { + return Err("base is not merged into the task branch; retained for continuation".into()); + } + Ok(()) +} +/// Read acceptance settings from the captured base commit, even on an older task branch. +pub(crate) fn done_from_base(repo: &Path, base: &str) -> Result> { + let path = ".oxa/settings.json"; + if checked(git(repo, &["ls-tree", "--name-only", base, "--", path]))?.is_empty() { + return Ok(vec![]); + } + let text = checked(git(repo, &["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}")), + } +} +pub(crate) fn check_receipt(receipt: &Path, tree: &Path, task: &Task) -> Result<()> { + if receipt.exists() { + let record: super::Record = serde_json::from_slice(&fs::read(receipt).map_err(|e| e.to_string())?) + .map_err(|e| format!("retained receipt: {e}"))?; + if record.id != task.id || record.branch != task.branch || record.worktree != tree { + return Err("retained receipt belongs to a different task branch or worktree".into()); + } + } + Ok(()) +} From d05391082f1edb8a76d76664f90912743853b2e9 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:56:43 +0000 Subject: [PATCH 5/7] Include the current base when resuming an older merge --- oxa/oxa-cli/tests/work_continue.rs | 39 ++++++++++++++++++++++++++++++ oxa/oxa-work/src/tree.rs | 12 +++++---- 2 files changed, 46 insertions(+), 5 deletions(-) diff --git a/oxa/oxa-cli/tests/work_continue.rs b/oxa/oxa-cli/tests/work_continue.rs index 5c0c244a2..bc0c252d4 100644 --- a/oxa/oxa-cli/tests/work_continue.rs +++ b/oxa/oxa-cli/tests/work_continue.rs @@ -213,3 +213,42 @@ fn changing_branch_cannot_report_green_for_task_branch() { assert_eq!(record["outcome"], "blocked", "{record}"); assert!(record["detail"].as_str().unwrap().contains("different branch")); } + +#[test] +fn resumed_old_merge_is_told_to_integrate_the_newly_captured_base() { + let env = TestEnv::new(); + diverge(&env, true); + trust(&env); + let first = run(&env, vec![ScriptTurn::text("blocked")]); + assert_eq!(first["outcome"], "blocked", "{first}"); + let old_base = git(&env, &project(&env), &["rev-parse", "main"]); + commit_file(&env, "new-base.txt", "new base commit\n"); + let new_base = git(&env, &project(&env), &["rev-parse", "main"]); + let mut turns = resolve_turns(); + turns.insert( + 2, + ScriptTurn::tool( + "latest", + "bash", + &serde_json::json!({"command": format!("git merge --no-edit {new_base}")}).to_string(), + ), + ); + let (record, requests) = run_observed(&env, turns, &["work", "../tasks.json"], None); + assert_eq!(record["outcome"], "done", "{record}"); + let messages = requests + .iter() + .flat_map(|r| &r.messages) + .filter_map(|m| m.content.as_deref()) + .collect::>() + .join("\n"); + assert!( + messages.contains(&old_base) && messages.contains(&format!("git merge --no-edit {new_base}")), + "{messages}" + ); + assert!(tree(&record).join("new-base.txt").exists()); + git( + &env, + &project(&env), + &["merge-base", "--is-ancestor", &new_base, "agent/test"], + ); +} diff --git a/oxa/oxa-work/src/tree.rs b/oxa/oxa-work/src/tree.rs index 48c8e5561..122fe61a7 100644 --- a/oxa/oxa-work/src/tree.rs +++ b/oxa/oxa-work/src/tree.rs @@ -18,9 +18,10 @@ fn git_path(tree: &Path, name: &str) -> Result { fn merging(tree: &Path) -> Result { Ok(git_path(tree, "MERGE_HEAD")?.exists()) } -fn merge_prompt(tree: &Path, task: &Task, output: &str) -> Result { +fn merge_prompt(tree: &Path, task: &Task, base: &str, output: &str) -> Result { let paths = checked(git(tree, &["diff", "--name-only", "--diff-filter=U"]))?; - Ok(format!("{}\n\nThere is a merge in progress from base {}. Resolve the conflicts, stage the resolutions, and finish the merge commit before completing the task. Preserve the task's existing work.\nConflicted paths:\n{paths}\nMerge output:\n{output}", task.prompt, task.base)) + let pending = checked(git(tree, &["rev-parse", "MERGE_HEAD"]))?; + Ok(format!("{}\n\nThere is a merge in progress from base {} at commit {pending}. The current base for this run is {base}. Resolve the conflicts, stage the resolutions, and finish the merge commit before completing the task. Then run `git merge --no-edit {base}` to integrate the captured current base as well, resolving and committing any further conflicts. Preserve the task's existing work.\nConflicted paths:\n{paths}\nMerge output:\n{output}", task.prompt, task.base)) } pub(crate) fn prepare(repo: &Path, tree: &Path, task: &Task) -> Result { let base = checked(git( @@ -70,8 +71,8 @@ pub(crate) fn prepare(repo: &Path, tree: &Path, task: &Task) -> Result if merging(tree)? { return Ok(Prepared { initial, - base, - prompt: merge_prompt(tree, task, "Resuming the retained merge.")?, + base: base.clone(), + prompt: merge_prompt(tree, task, &base, "Resuming the retained merge.")?, }); } if !checked(git(tree, &["status", "--porcelain"]))?.is_empty() { @@ -88,10 +89,11 @@ pub(crate) fn prepare(repo: &Path, tree: &Path, task: &Task) -> Result } return Ok(Prepared { initial, - base, + base: base.clone(), prompt: merge_prompt( tree, task, + &base, &format!( "{}\n{}", String::from_utf8_lossy(&merged.stdout), 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 6/7] 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 7/7] 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