diff --git a/oxa/Cargo.lock b/oxa/Cargo.lock index 087554903..cf87fcf2c 100644 --- a/oxa/Cargo.lock +++ b/oxa/Cargo.lock @@ -432,6 +432,7 @@ dependencies = [ "oxa-tools", "oxa-tui", "oxa-web", + "oxa-work", "regex", "serde_json", "sha2", @@ -707,6 +708,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 2e1ac6101..9bdff2d0b 100644 --- a/oxa/Cargo.toml +++ b/oxa/Cargo.toml @@ -13,7 +13,7 @@ members = [ "oxa-core", "oxa-tui", "oxa-interactive", "oxa-rpc", "oxa-export", - "oxa-cli", + "oxa-cli", "oxa-work", "oxa-fake", "oxa-parity", ] @@ -46,6 +46,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/docs/work.md b/oxa/docs/work.md new file mode 100644 index 000000000..7983dd97d --- /dev/null +++ b/oxa/docs/work.md @@ -0,0 +1,53 @@ +# 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 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. + +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: +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 +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 +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 +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 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/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-cli/src/args.rs b/oxa/oxa-cli/src/args.rs index d62d19272..0ca62ae99 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" => { @@ -451,19 +458,17 @@ 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 && (i == 1 || (arg == "work" && argv[..i - 1].iter().all(|word| word == "--offline"))) { + 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/dispatch.rs b/oxa/oxa-cli/src/dispatch.rs index 41bbac144..4ef83d386 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..4afd4b9d1 --- /dev/null +++ b/oxa/oxa-cli/src/work_cmd.rs @@ -0,0 +1,43 @@ +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" => { + 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")?, + 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_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 + ) { + 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/c12_argument_parsing.rs b/oxa/oxa-cli/tests/c12_argument_parsing.rs index 3899ce88d..c51fe7c6f 100644 --- a/oxa/oxa-cli/tests/c12_argument_parsing.rs +++ b/oxa/oxa-cli/tests/c12_argument_parsing.rs @@ -389,6 +389,53 @@ fn subcommands_split() { assert_eq!(a.messages, ["summarise", "install"]); } +#[test] +fn agent_options_keep_command_words_as_prompts() { + for word in [ + "mcp", + "install", + "remove", + "update", + "list", + "config", + "identity", + "report-issue", + "wipe", + "work", + "auth", + "login", + "logout", + ] { + for flags in [&["--model", "m"][..], &["-c"][..]] { + let mut words = flags.to_vec(); + words.extend([word, "example"]); + let a = parse(&words); + assert_eq!(a.subcommand, None, "{words:?}"); + assert_eq!(a.messages, [word, "example"]); + } + if word != "work" { + let a = parse(&["--offline", word, "example"]); + assert_eq!(a.subcommand, None, "{word}"); + assert_eq!(a.messages, [word, "example"]); + } + } +} + +#[test] +fn only_the_offline_work_prefix_dispatches_after_options() { + let a = parse(&["--offline", "work", "tasks.json"]); + assert!(a.offline); + assert_eq!(a.subcommand, Some(Subcommand::Work(argv(&["tasks.json"])))); + for flags in [&["-p"][..], &["--model", "m"][..], &["--"][..]] { + let mut words = vec!["--offline"]; + words.extend(flags); + words.extend(["work", "tasks.json"]); + let a = parse(&words); + assert_eq!(a.subcommand, None, "{words:?}"); + assert_eq!(a.messages, ["work", "tasks.json"]); + } +} + /// Extra: help lists the flags and the extension flags. #[test] fn usage_text_lists_flags_and_extension_flags() { 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 new file mode 100644 index 000000000..069245b37 --- /dev/null +++ b/oxa/oxa-cli/tests/work_cli.rs @@ -0,0 +1,314 @@ +//! Real child oxa with fake engine and local bare git remote; no network. +#[path = "common/work.rs"] +mod work; +use oxa_fake::{FakeOpts, FakeServer, ScriptTurn, TestEnv}; +use std::{path::Path, process::Command}; +use work::{git, run, run_args, setup}; +#[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 failed_agent_with_failed_checks_is_blocked_and_keeps_both_causes() { + let env = TestEnv::new(); + setup(&env, r#"["echo external-check-failed; exit 1"]"#); + env.write( + "work/tasks.json", + r#"[{"id":"test","branch":"agent/test","model":"missing-model","prompt":"Finish task"}]"#, + ); + let record = run(&env, vec![]); + assert_eq!(record["outcome"], "blocked", "{record}"); + let detail = record["detail"].as_str().unwrap(); + assert!(detail.contains("missing-model"), "{detail}"); + assert!(detail.contains("external-check-failed"), "{detail}"); +} +#[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 branch_checked_out_elsewhere_is_blocked() { + let env = TestEnv::new(); + setup(&env, "[]"); + 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("other")); +} + +#[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")); + } +} + +#[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-cli/tests/work_continue.rs b/oxa/oxa-cli/tests/work_continue.rs new file mode 100644 index 000000000..bc0c252d4 --- /dev/null +++ b/oxa/oxa-cli/tests/work_continue.rs @@ -0,0 +1,254 @@ +//! 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")); +} + +#[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/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..96e6f760d --- /dev/null +++ b/oxa/oxa-work/src/lib.rs @@ -0,0 +1,260 @@ +//! 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}; +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, Deserialize, Serialize, PartialEq, Eq)] +#[serde(rename_all = "snake_case")] +pub enum Outcome { + Done, + NothingToDo, + Red, + Blocked, +} + +#[derive(Debug, Deserialize, 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}"), + }) +} + +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, offline: bool) -> Result<()> { + let mut c = Command::new(binary); + c.current_dir(root) + .args(["-p", "--model", &task.model, "--no-session"]); + if offline { + c.arg("--offline"); + } + c.args(["--", prompt]); + checked(c).map(|_| ()) +} + +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); + checked(git(&root, &["check-ref-format", "--branch", &task.branch]))?; + let common = checked(git( + &root, + &["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 lock_path = storage.join(format!("{}.lock", task.id)); + let lock_file = fs::OpenOptions::new() + .write(true) + .create(true) + .truncate(false) + .open(&lock_path) + .map_err(|e| format!("cannot lock task {}: {e}", task.id))?; + 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)); + // 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); + tree::check_receipt(&receipt, &tree, task)?; + let mut record = Record { + id: task.id.clone(), + branch: task.branch.clone(), + worktree: tree.clone(), + outcome: Outcome::Blocked, + detail: String::new(), + }; + let result = (|| -> Result { + let prepared = tree::prepare(&root, &tree, task)?; + let tree = tree.canonicalize().map_err(|e| e.to_string())?; + let commands = tree::done_from_base(&tree, &prepared.base)?; + let first_agent = agent(binary, &tree, task, &prepared.prompt, offline); + tree::ensure_merged(&tree, &prepared.base, &task.branch)?; + 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}", + prepared.prompt + ), + offline, + ); + tree::ensure_merged(&tree, &prepared.base, &task.branch)?; + let failures = acceptance(&tree, &commands)?; + 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"]))?; + Ok(if head == prepared.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) +} diff --git a/oxa/oxa-work/src/tree.rs b/oxa/oxa-work/src/tree.rs new file mode 100644 index 000000000..122fe61a7 --- /dev/null +++ b/oxa/oxa-work/src/tree.rs @@ -0,0 +1,149 @@ +//! 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, base: &str, output: &str) -> Result { + let paths = checked(git(tree, &["diff", "--name-only", "--diff-filter=U"]))?; + 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( + 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: base.clone(), + prompt: merge_prompt(tree, task, &base, "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: base.clone(), + prompt: merge_prompt( + tree, + task, + &base, + &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(()) +}