diff --git a/oxa/Cargo.lock b/oxa/Cargo.lock index 0230d3d92..394325c54 100644 --- a/oxa/Cargo.lock +++ b/oxa/Cargo.lock @@ -918,6 +918,7 @@ dependencies = [ "oxa-tools", "oxa-tui", "oxa-web", + "oxa-work", "regex", "serde_json", "sha2", @@ -1194,6 +1195,14 @@ dependencies = [ "ureq", ] +[[package]] +name = "oxa-work" +version = "0.2.0" +dependencies = [ + "serde", + "serde_json", +] + [[package]] name = "oxc-gateway" version = "0.2.0" diff --git a/oxa/Cargo.toml b/oxa/Cargo.toml index 79ba2bf3c..1e1a92112 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", "oxc-gateway", ] @@ -47,6 +47,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" } # Shared oxa dependencies; the optional cloud transport is owned by the gateway. serde = { version = "1", features = ["derive"] } diff --git a/oxa/docs/work.md b/oxa/docs/work.md new file mode 100644 index 000000000..26c5048de --- /dev/null +++ b/oxa/docs/work.md @@ -0,0 +1,79 @@ +# 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. Issue lookup is refused +when the environment or user settings enable offline mode. +Issue lookup also requires source-project trust. Git and GitHub CLI host calls use +validated executables outside the repository. Worker and check-supervisor PATHs +exclude project directories, relative entries and unsafe aliases; project tools +can still run by explicit path inside the sandbox. +Branches must be literal names; checkout-history aliases such as `@{-1}` are refused. +Every base and acceptance command list is resolved before any task in the batch +starts. All bases must therefore exist at batch startup. Host metadata commands +ignore replacement objects and inherited `GIT_*` overrides, disable filesystem +monitors, and never lazily fetch missing objects. Fetch the needed objects before +starting the batch. Checkout and checks also ignore replacement objects. + +Each task runs a child `oxa --mode=json` with its model and a saved session. The installed offline policy, +including a parent `--offline` flag, is passed to every child. Normal agent permission, trust and +sandbox rules apply. Configure project trust before unattended use. The runner +passes `-na` on every child start, including repair, and removes `OXA_TRUST_PROJECT`. +Worker project settings, MCP servers and extensions are therefore ignored even +when a parent directory or the user's default would trust the new worktree. +User-level resources keep their normal behavior; external acceptance uses the +approved source project and the batch's frozen command list. The runner +creates detached Git metadata with callbacks suppressed on the host, then creates +the task branch and populates the fresh worktree inside the normal sandbox. +Reference hooks, checkout hooks and smudge filters stay inside it; a reference hook +that rejects the task branch still blocks the task. +missing bwrap blocks before checkout or a worker starts. Configured hook directories +keep their normal read-only protection: a checkout that needs to populate a tracked +protected hook directory blocks with the worktree retained. +Acceptance commands are frozen from the captured base commit before checkout +callbacks can change settings. The runner executes those `done` commands outside the +agent after it exits, even without edits. The source project must pass the existing +trust and executable-content approval before a task starts. Invoking `work` does +not approve an untrusted project. Acceptance runs in the normal bwrap sandbox; +missing or unusable bwrap blocks the task. Checkout and each check have the same ten-minute limit +as agent-internal done checks. `in subdirectory: command` selects a folder inside +that sandbox; escaping the worktree is rejected. +The final Git inspection is also sandboxed, with a read-only workspace, no network +and fsmonitor disabled. Clean filters stay inside that sandbox; an inspection +error blocks the task rather than producing a clean verdict. +Agent-internal done checks may also run when the project is trusted. + +The runner reads the child's exit code, terminal `oxa_result` and session header, +without retaining its event stream. A blocked, failed or interrupted worker remains +blocked and does not consume a repair attempt. Failed acceptance after a successful +worker continues that same saved session once, then acceptance runs once more. +JSON lines include the worker result, session ID and captured `base_sha` and report `done`, `nothing_to_do` (no +commits or file changes), `red` (checks still fail), or `blocked` (setup or agent +execution failed). Exit codes are 0 for success, 1 if any task is red or blocked, +and 2 for invalid input or output errors. A task setup failure produces a blocked +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). Private result receipts and +locks live under `~/.oxa/agent/work//` (or the configured agent +directory), outside the worker's writable Git bind. Receipts are published atomically +without overwriting an existing receipt. Worktrees stay outside that git +directory so the normal sandbox can bind git objects and refs for commits. No automatic +cleanup, commit, push, PR creation or continuation is implemented yet. Inspect +retained work before removing it with `git worktree remove`. Review task prompts +and bases before running them. + +`done` here describes accepted local work, which may be uncommitted. This slice +does not publish it. The saving/publication slices must bind acceptance to a clean +committed tree and verify its recorded commit before pushing. diff --git a/oxa/oxa-cli/Cargo.toml b/oxa/oxa-cli/Cargo.toml index 2c41240c0..bb7651101 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 8fc150267..12045a66a 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. @@ -182,6 +184,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", @@ -352,6 +358,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" => { @@ -463,19 +470,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 04571d8f0..ebf22b01f 100644 --- a/oxa/oxa-cli/src/dispatch.rs +++ b/oxa/oxa-cli/src/dispatch.rs @@ -170,6 +170,9 @@ pub fn run(argv: &[String], env: &Env, io: Stdio) -> i32 { Err(e) => return report(&mut *stderr, &e), }; let result = match sub { + Subcommand::Work(words) => { + return crate::work_cmd::run(&words, &cwd, env, &dirs, &mut *stdout, &mut *stderr) + } Subcommand::Mcp(words) => run_mcp(&words, &dirs, &cwd, &mut *stdout, &mut *stderr), Subcommand::Pkg(verb, words) => run_pkg(&verb, &words, &dirs, &cwd, &mut *stdout, &mut *stderr), Subcommand::Config(words) => run_config(&words, &dirs, &cwd, &mut *stdout), @@ -472,112 +475,16 @@ fn prepare( let child = crate::child::ChildIdentity::from_env(env, &mut notices); notices.extend(crate::netguard::endpoint_notice(&endpoint.base_url)); - // Trust: the user's own settings decide the default; project settings load only when the - // project is trusted. - let user_settings = Settings::load(dirs, cwd, false); - let default = match user_settings.string("defaultProjectTrust").as_deref() { - Some("always") => DefaultTrust::Trust, - Some("never") => DefaultTrust::Untrusted, - _ => DefaultTrust::Ask, - }; let gated = gated_resources(cwd); - // `OXA_TRUST_PROJECT=1` is `--approve` for the trust decision, for unattended runs; - // an explicit `-na` still wins. - let approve = a - .approve - .or_else(|| matches!(env.get("OXA_TRUST_PROJECT"), Some("1" | "true")).then_some(true)); - let mut trust_store = TrustStore::load(&dirs.trust_file()); - // SEC-003 / EXT-008: the user-level and `-e` extensions answer `project_trust` before the - // saved decision and the default (pi's `resolveProjectTrusted`). - let extension = if approve.is_none() && !gated.is_empty() { - extension_trust(a, dirs, cwd, &user_settings, &mut trust_store, &mut notices) - } else { - None - }; - let interactive = mode == RunMode::Interactive && stdin_is_tty && stdout_is_tty; - let saved = trust_store.lookup(cwd); - let outcome = resolve_trust(&TrustInputs { - flag: approve, - extension, - saved, - default, - interactive, - has_gated: !gated.is_empty(), - }); - // B4: the user answered the trust question in this start (it approves the content too). - let mut asked_now = false; - let trusted = match outcome { - TrustOutcome::Trusted => true, - TrustOutcome::Untrusted => false, - TrustOutcome::AskUser => { - // The trust dialog (D10) on the terminal, before the session exists. A dismissed - // question leaves the project untrusted for this run and is asked again next time. - let (keymap, _) = Keymap::load(dirs); - let choice = ask_trust_interactive(env.pairs(), &keymap, &cwd.display().to_string(), &gated)?; - asked_now = true; - let file = dirs.trust_file(); - match choice { - Some(TrustChoice::Trust) => { - trust_store.save(&file, cwd, true)?; - true - } - Some(TrustChoice::TrustParent) => { - trust_store.save(&file, cwd.parent().unwrap_or(cwd), true)?; - true - } - Some(TrustChoice::NoTrust) => { - trust_store.save(&file, cwd, false)?; - false - } - Some(TrustChoice::Skip) | None => { - notices.push(( - Level::Warning, - "the project is not trusted for this run; /trust saves a decision".to_string(), - )); - false - } - } - } - }; - // B4: what runs outside the sandbox loads only as the user approved it (content hashes). - let trusted = if trusted && !gated.is_empty() { - crate::approval::check(crate::approval::Check { - env, - dirs, - cwd, - store: &mut trust_store, - via_flag: approve == Some(true), - via_default: extension.is_none() && saved.is_none() && default == DefaultTrust::Trust, - asked_now, - interactive, - notices: &mut notices, - })? - } else { - trusted - }; - // #201: a project trusted by a saved decision gets its approval baseline now (also with - // no project config yet), before any tool runs: `.oxa` / `.agents` content the session - // creates is then new at the next start and goes through the normal approval. - if trusted && saved == Some(true) { - trust_store.record_baseline(&dirs.trust_file(), cwd)?; - } - if !trusted && !gated.is_empty() { - notices.push(( - Level::Warning, - format!( - "project resources were skipped (not trusted): {}", - gated.join(", ") - ), - )); - } - // `done` is a project-only key in practice: an untrusted project's list is never merged, - // so say that its checks will not run. - if !trusted && Settings::project_declares_done(dirs, cwd) { - notices.push(( - Level::Warning, - "done checks in .oxa/settings.json were not run: project is not trusted".to_string(), - )); - } + let trusted = project_trusted( + a, + env, + dirs, + cwd, + &gated, + mode == RunMode::Interactive && stdin_is_tty && stdout_is_tty, + &mut notices, + )?; let mut settings = child.apply(Settings::load(dirs, cwd, trusted)); // CLI-045 (pi cli.md): `--verbose` overrides `quietStartup` for this run (in memory only). if a.verbose { @@ -828,6 +735,123 @@ fn prepare( } /// The resource discovery options of the flags. +/// The same project trust and executable-content approval for sessions and workers. +pub(crate) fn project_trusted( + a: &Args, + env: &Env, + dirs: &Dirs, + cwd: &Path, + gated: &[String], + interactive: bool, + notices: &mut Vec<(Level, String)>, +) -> Result { + // Trust: the user's own settings decide the default; project settings load only when the + // project is trusted. + let user_settings = Settings::load(dirs, cwd, false); + let default = match user_settings.string("defaultProjectTrust").as_deref() { + Some("always") => DefaultTrust::Trust, + Some("never") => DefaultTrust::Untrusted, + _ => DefaultTrust::Ask, + }; + // `OXA_TRUST_PROJECT=1` is `--approve` for the trust decision, for unattended runs; + // an explicit `-na` still wins. + let approve = a + .approve + .or_else(|| matches!(env.get("OXA_TRUST_PROJECT"), Some("1" | "true")).then_some(true)); + let mut trust_store = TrustStore::load(&dirs.trust_file()); + // SEC-003 / EXT-008: the user-level and `-e` extensions answer `project_trust` before the + // saved decision and the default (pi's `resolveProjectTrusted`). + let extension = if approve.is_none() && !gated.is_empty() { + extension_trust(a, dirs, cwd, &user_settings, &mut trust_store, notices) + } else { + None + }; + let saved = trust_store.lookup(cwd); + let outcome = resolve_trust(&TrustInputs { + flag: approve, + extension, + saved, + default, + interactive, + has_gated: !gated.is_empty(), + }); + // B4: the user answered the trust question in this start (it approves the content too). + let mut asked_now = false; + let trusted = match outcome { + TrustOutcome::Trusted => true, + TrustOutcome::Untrusted => false, + TrustOutcome::AskUser => { + // The trust dialog (D10) on the terminal, before the session exists. A dismissed + // question leaves the project untrusted for this run and is asked again next time. + let (keymap, _) = Keymap::load(dirs); + let choice = ask_trust_interactive(env.pairs(), &keymap, &cwd.display().to_string(), gated)?; + asked_now = true; + let file = dirs.trust_file(); + match choice { + Some(TrustChoice::Trust) => { + trust_store.save(&file, cwd, true)?; + true + } + Some(TrustChoice::TrustParent) => { + trust_store.save(&file, cwd.parent().unwrap_or(cwd), true)?; + true + } + Some(TrustChoice::NoTrust) => { + trust_store.save(&file, cwd, false)?; + false + } + Some(TrustChoice::Skip) | None => { + notices.push(( + Level::Warning, + "the project is not trusted for this run; /trust saves a decision".to_string(), + )); + false + } + } + } + }; + // B4: what runs outside the sandbox loads only as the user approved it (content hashes). + let trusted = if trusted && !gated.is_empty() { + crate::approval::check(crate::approval::Check { + env, + dirs, + cwd, + store: &mut trust_store, + via_flag: approve == Some(true), + via_default: extension.is_none() && saved.is_none() && default == DefaultTrust::Trust, + asked_now, + interactive, + notices, + })? + } else { + trusted + }; + // #201: a project trusted by a saved decision gets its approval baseline now (also with + // no project config yet), before any tool runs: `.oxa` / `.agents` content the session + // creates is then new at the next start and goes through the normal approval. + if trusted && saved == Some(true) { + trust_store.record_baseline(&dirs.trust_file(), cwd)?; + } + if !trusted && !gated.is_empty() { + notices.push(( + Level::Warning, + format!( + "project resources were skipped (not trusted): {}", + gated.join(", ") + ), + )); + } + // `done` is a project-only key in practice: an untrusted project's list is never merged, + // so say that its checks will not run. + if !trusted && Settings::project_declares_done(dirs, cwd) { + notices.push(( + Level::Warning, + "done checks in .oxa/settings.json were not run: project is not trusted".to_string(), + )); + } + Ok(trusted) +} + fn discover_opts(a: &Args, dirs: &Dirs, cwd: &Path, trusted: bool) -> Result { Ok(DiscoverOpts { trusted, diff --git a/oxa/oxa-cli/src/lib.rs b/oxa/oxa-cli/src/lib.rs index 51034a28b..c0a9fb5be 100644 --- a/oxa/oxa-cli/src/lib.rs +++ b/oxa/oxa-cli/src/lib.rs @@ -32,6 +32,8 @@ mod report_cmd; mod sandbox_layout; mod themes; mod wipe_cmd; +mod work_checks; +mod work_cmd; pub use args::{parse_args, usage_text, ApiKey, Args, ModeArg, Subcommand}; pub use config_cmd::run_config; diff --git a/oxa/oxa-cli/src/netguard.rs b/oxa/oxa-cli/src/netguard.rs index b42d19148..ff4763846 100644 --- a/oxa/oxa-cli/src/netguard.rs +++ b/oxa/oxa-cli/src/netguard.rs @@ -57,13 +57,23 @@ fn trusted_gh_for( path: Option<&std::ffi::OsStr>, cwd: Option<&Path>, home: Option<&Path>, +) -> Option { + trusted_executable_for("gh", path, cwd, home) +} + +/// Host tools use the same project/PATH checks as the GitHub credential helper. +pub(crate) fn trusted_executable_for( + program: &str, + path: Option<&std::ffi::OsStr>, + cwd: Option<&Path>, + home: Option<&Path>, ) -> Option { let canon = |p: &Path| std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf()); let Some(h) = home.map(canon) else { - return trusted_gh(path, cwd); + return trusted_executable(program, path, cwd); }; if !cwd.is_some_and(|c| canon(c) == h) { - return trusted_gh(path, cwd); + return trusted_executable(program, path, cwd); } let allowed: Vec = USER_BIN.iter().map(|d| h.join(d)).collect(); // Allowed by where it resolves to, so a symlink from `~/.local/bin` into a project is refused. @@ -80,7 +90,7 @@ fn trusted_gh_for( }; std::env::split_paths(path?) .filter(|d| ok(d)) - .filter_map(|d| trusted_gh(Some(d.as_os_str()), None)) + .filter_map(|d| trusted_executable(program, Some(d.as_os_str()), None)) .find(|f| file_ok(f)) } @@ -134,10 +144,14 @@ fn gh_token_from(exe: &Path, deadline: std::time::Duration) -> Option { (!t.is_empty() && !t.chars().any(char::is_whitespace)).then(|| t.to_string()) } -/// The `gh` to run: the first executable file named `gh` in an absolute `PATH` entry that is +/// The host tool to run: the first executable with the requested name in an absolute `PATH` entry that is /// not inside the project (`cwd`) and not a group- or world-writable directory. Relative /// entries (`.`, `bin`, empty) are ignored, so a project shim never runs outside the sandbox. -fn trusted_gh(path: Option<&std::ffi::OsStr>, cwd: Option<&Path>) -> Option { +fn trusted_executable( + program: &str, + path: Option<&std::ffi::OsStr>, + cwd: Option<&Path>, +) -> Option { use std::os::unix::fs::PermissionsExt; let cwd_c = cwd.and_then(|c| std::fs::canonicalize(c).ok()); std::env::split_paths(path?) @@ -148,7 +162,7 @@ fn trusted_gh(path: Option<&std::ffi::OsStr>, cwd: Option<&Path>) -> Option, cwd: Option<&Path>) -> Option Option { + use std::os::unix::fs::PermissionsExt; + let home = home.canonicalize().unwrap_or_else(|_| home.to_path_buf()); + let project = project.canonicalize().ok()?; + let is_worker = |p: &Path| p.components().any(|part| part.as_os_str() == ".oxa-worktrees"); + let allowed: Vec<_> = USER_BIN.iter().map(|d| home.join(d)).collect(); + let entries = std::env::split_paths(path).filter(|dir| { + if !dir.is_absolute() || is_worker(dir) { + return false; + } + let Ok(real) = dir.canonicalize() else { + return false; + }; + if is_worker(&real) + || !std::fs::metadata(&real).is_ok_and(|m| m.is_dir() && m.permissions().mode() & 0o022 == 0) + { + return false; + } + if project == home { + if real.starts_with(&home) && !allowed.iter().any(|p| real.starts_with(p)) { + return false; + } + } else if dir.starts_with(&project) || real.starts_with(&project) { + return false; + } + ["git", "gh", "bwrap"].iter().all(|name| { + let exe = dir.join(name); + if std::fs::symlink_metadata(&exe).is_err() { + return true; + } + trusted_executable_for(name, Some(dir.as_os_str()), Some(&project), Some(&home)) + .is_some_and(|p| p.canonicalize().is_ok_and(|p| !is_worker(&p))) + }) + }); + std::env::join_paths(entries).ok() +} + /// The setting that allows an engine host that is not loopback (P3). Read from the user's /// settings only: a project file cannot send the prompts elsewhere. pub(crate) const SETTING_ALLOW_REMOTE: &str = "oxa.engine.allowRemote"; @@ -342,7 +399,7 @@ mod tests { script(&proj, "gh", "echo EVIL"); std::os::unix::fs::symlink(proj.join("gh"), good.join("gh")).unwrap(); let p = std::env::join_paths([good.to_str().unwrap()]).unwrap(); - assert_eq!(trusted_gh(Some(&p), Some(&proj)), None); + assert_eq!(trusted_executable("gh", Some(&p), Some(&proj)), None); } #[test] @@ -357,12 +414,18 @@ mod tests { let sep = |v: &[&str]| std::env::join_paths(v).unwrap(); // Relative entries are skipped. let rel = sep(&["bin", ".", "", good.to_str().unwrap()]); - assert_eq!(trusted_gh(Some(&rel), Some(&proj)), Some(good.join("gh"))); + assert_eq!( + trusted_executable("gh", Some(&rel), Some(&proj)), + Some(good.join("gh")) + ); // An absolute entry inside the project directory is skipped too. let p = sep(&[proj.to_str().unwrap(), good.to_str().unwrap()]); - assert_eq!(trusted_gh(Some(&p), Some(&proj)), Some(good.join("gh"))); + assert_eq!( + trusted_executable("gh", Some(&p), Some(&proj)), + Some(good.join("gh")) + ); // Only untrusted entries: nothing. let only = sep(&[proj.to_str().unwrap(), "rel"]); - assert_eq!(trusted_gh(Some(&only), Some(&proj)), None); + assert_eq!(trusted_executable("gh", Some(&only), Some(&proj)), None); } } diff --git a/oxa/oxa-cli/src/work_checks.rs b/oxa/oxa-cli/src/work_checks.rs new file mode 100644 index 000000000..090ba813e --- /dev/null +++ b/oxa/oxa-cli/src/work_checks.rs @@ -0,0 +1,168 @@ +//! Deterministic check/inspection supervisor; no engine or model is constructed here. +use oxa_config::{Dirs, Env, Settings}; +use oxa_proto::{CancelToken, ExecSpec, Sandbox}; +use oxa_sandbox::Bwrap; +use oxa_work::{SupervisorOperation, SupervisorRequest}; +use std::io::Write; +use std::path::Path; +use std::sync::Arc; + +pub(crate) fn run( + request: &str, + cwd: &Path, + env: &Env, + dirs: &Dirs, + err: &mut dyn Write, +) -> Result { + let request: SupervisorRequest = serde_json::from_str(request).map_err(|e| e.to_string())?; + let source = request.source.canonicalize().map_err(|e| e.to_string())?; + if !crate::work_cmd::trusted(&source, env, dirs)? { + return Err("supervisor source project is not trusted".into()); + } + let root = cwd.canonicalize().map_err(|e| e.to_string())?; + let mut b = Bwrap::detect(env.get("PATH").unwrap_or(""), &dirs.home).map_err(|e| e.to_string())?; + b.layout = crate::sandbox_layout::layout(env, dirs, &root, false, &mut vec![]); + let b = b.with_git_dirs(&root); + b.check().map_err(|e| e.to_string())?; + let settings = Settings::load(dirs, &source, true); + let commands = match request.operation { + SupervisorOperation::Inspect => return inspect(&b, &root), + SupervisorOperation::Checkout { branch } => { + let sandbox = crate::netguard::with_net(Arc::new(b), &settings); + let spec = ExecSpec { + command: format!( + "git --no-replace-objects checkout HEAD -- . && git --no-replace-objects checkout -b '{}' HEAD", + branch.replace('\'', "'\\''") + ), + cwd: root, + writable: true, + net: sandbox.network(), + timeout_s: Some(600), + env: git_environment(), + }; + let mut tail = Vec::new(); + let result = sandbox.run_streaming(&spec, &CancelToken::default(), &mut |bytes| { + keep_tail(&mut tail, bytes, 8192); + }); + if result.exit != Some(0) || result.timed_out { + return Err(format!( + "checkout exit {:?}, timeout {}: {}", + result.exit, + result.timed_out, + String::from_utf8_lossy(&tail) + )); + } + return Ok(0); + } + SupervisorOperation::Checks { commands } => commands, + }; + let shell = oxa_tools::ShellConfig { + shell_path: settings.shell_path(&dirs.home), + command_prefix: settings.shell_command_prefix(), + }; + let sandbox = crate::netguard::with_net(Arc::new(b), &settings); + let mut failed = false; + let mut diagnostics = Vec::new(); + for entry in commands { + let (directory, text) = match entry.strip_prefix("in ").and_then(|s| s.split_once(':')) { + Some((dir, command)) => (Some(dir.trim()), command.trim()), + None => (None, entry.as_str()), + }; + if text.is_empty() { + return Err("empty acceptance command".into()); + } + let command = shell.command(text)?; + // Bind the original workspace, then select a child inside that view. A + // symlink swap cannot turn an outside directory into the writable root. + let command = if let Some(directory) = directory { + let child = root.join(directory).canonicalize().map_err(|e| e.to_string())?; + let relative = child + .strip_prefix(&root) + .map_err(|_| "done directory escapes worktree")?; + let dir = if relative.as_os_str().is_empty() { + Path::new(".") + } else { + relative + }; + format!( + "cd -- '{}' || exit 111\n{command}", + dir.to_string_lossy().replace('\'', "'\\''") + ) + } else { + command + }; + let spec = ExecSpec { + command, + cwd: root.clone(), + writable: true, + net: sandbox.network(), + timeout_s: Some(600), + env: git_environment(), + }; + let mut tail = Vec::new(); + let result = sandbox.run_streaming(&spec, &CancelToken::default(), &mut |bytes| { + keep_tail(&mut tail, bytes, 8192); + }); + if result.exit != Some(0) || result.timed_out { + failed = true; + let header = format!("{entry}: exit {:?}, timeout {}\n", result.exit, result.timed_out); + keep_tail(&mut diagnostics, header.as_bytes(), 16384); + keep_tail(&mut diagnostics, &tail, 16384); + } + } + if failed { + err.write_all(&diagnostics).map_err(|e| e.to_string())?; + } + Ok(i32::from(failed)) +} + +// Exit codes are the only result: repository callbacks cannot forge a clean +// verdict by printing JSON or diagnostics. Git failures remain distinct from dirty. +fn inspect(sandbox: &Bwrap, root: &Path) -> Result { + let spec = ExecSpec { + command: r#"git --no-replace-objects --no-optional-locks -c core.fsmonitor=false status --porcelain=v1 -z | { + work_dirty=0 + while IFS= read -r -d '' work_entry; do work_dirty=1; done + exit "$work_dirty" +} +work_probe_status=("${PIPESTATUS[@]}") +if test "${work_probe_status[0]}" -ne 0; then exit 2; fi +exit "${work_probe_status[1]}" +"# + .into(), + cwd: root.to_path_buf(), + writable: false, + net: false, + timeout_s: Some(600), + env: git_environment(), + }; + let mut tail = Vec::new(); + let result = sandbox.run_streaming(&spec, &CancelToken::default(), &mut |bytes| { + keep_tail(&mut tail, bytes, 8192); + }); + match (result.exit, result.timed_out) { + (Some(code @ (0 | 1)), false) => Ok(code), + _ => Err(format!( + "sandboxed Git inspection failed: {}", + String::from_utf8_lossy(&tail) + )), + } +} + +fn git_environment() -> Vec<(String, String)> { + vec![ + ("AI_AGENT".into(), "oxa".into()), + ("GIT_NO_REPLACE_OBJECTS".into(), "1".into()), + ] +} + +fn keep_tail(tail: &mut Vec, bytes: &[u8], cap: usize) { + if bytes.len() >= cap { + tail.clear(); + tail.extend_from_slice(&bytes[bytes.len() - cap..]); + } else { + let discard = (tail.len() + bytes.len()).saturating_sub(cap); + tail.drain(..discard); + tail.extend_from_slice(bytes); + } +} diff --git a/oxa/oxa-cli/src/work_cmd.rs b/oxa/oxa-cli/src/work_cmd.rs new file mode 100644 index 000000000..c73f7aeda --- /dev/null +++ b/oxa/oxa-cli/src/work_cmd.rs @@ -0,0 +1,167 @@ +use oxa_config::{Dirs, Env}; +use sha2::{Digest, Sha256}; +use std::io::Write; +use std::path::{Path, PathBuf}; + +pub(crate) fn trusted(cwd: &Path, env: &Env, dirs: &Dirs) -> Result { + crate::dispatch::project_trusted( + &crate::Args::default(), + env, + dirs, + cwd, + &oxa_perm::gated_resources(cwd), + false, + &mut vec![], + ) + .map_err(|e| e.to_string()) +} + +pub(crate) fn run( + args: &[String], + cwd: &Path, + env: &Env, + dirs: &Dirs, + out: &mut dyn Write, + err: &mut dyn Write, +) -> i32 { + let result = (|| -> Result { + if let [flag, request] = args { + if flag == "--supervise" { + return crate::work_checks::run(request, cwd, env, dirs, err); + } + } + let binary: PathBuf = std::env::current_exe().map_err(|e| e.to_string())?; + // Find the source boundary from files before executing any host tool. + let cwd_c = cwd.canonicalize().map_err(|e| e.to_string())?; + let project = cwd_c + .ancestors() + .find(|p| p.join(".git").exists()) + .ok_or("oxa work requires a Git repository")?; + // Nested repository metadata cannot bless code from an outer project. + let host_project = project + .ancestors() + .filter(|p| p.join(".git").exists()) + .last() + .unwrap_or(project); + let host_path = crate::netguard::trusted_work_path( + std::ffi::OsStr::new(env.get("PATH").unwrap_or("")), + host_project, + &dirs.home, + ) + .ok_or("cannot resolve trusted worker PATH")?; + let git_binary = crate::netguard::trusted_executable_for( + "git", + Some(host_path.as_os_str()), + Some(project), + Some(&dirs.home), + ) + .ok_or("no trusted Git executable outside the source project")?; + let output = oxa_work::metadata_git(&git_binary, &host_path, cwd, &["rev-parse", "--show-toplevel"]) + .output() + .map_err(|e| e.to_string())?; + if !output.status.success() { + return Err("oxa work requires a Git repository".into()); + } + let root = PathBuf::from(String::from_utf8_lossy(&output.stdout).trim()) + .canonicalize() + .map_err(|e| e.to_string())?; + if root != project { + return Err("Git root differs from the source project boundary".into()); + } + let is_trusted = trusted(&root, env, dirs)?; + let tasks = match args { + [file] if !file.starts_with('-') => oxa_work::read_tasks(&cwd.join(file))?, + [flag, number, model_flag, model] if flag == "--issue" && model_flag == "--model" => { + if oxa_proto::offline() { + return Err("GitHub issue lookup is unavailable in offline mode".into()); + } + if !is_trusted { + return Err("source project is not trusted; approve it before issue lookup".into()); + } + let gh = crate::netguard::trusted_executable_for( + "gh", + Some(host_path.as_os_str()), + Some(&root), + Some(&dirs.home), + ) + .ok_or("no trusted gh executable outside the source project")?; + vec![oxa_work::issue_task( + &root, + &gh, + &host_path, + number.parse().map_err(|_| "invalid issue number")?, + model.clone(), + )?] + } + _ => return Err("usage: oxa work | --issue N --model MODEL".into()), + }; + let common = oxa_work::metadata_git( + &git_binary, + &host_path, + &root, + &["rev-parse", "--path-format=absolute", "--git-common-dir"], + ) + .output() + .map_err(|e| e.to_string())?; + if !common.status.success() { + return Err("cannot resolve runner repository".into()); + } + let common = PathBuf::from(String::from_utf8_lossy(&common.stdout).trim()) + .canonicalize() + .map_err(|e| e.to_string())?; + let key = Sha256::digest(common.as_os_str().as_encoded_bytes()) + .iter() + .map(|b| format!("{b:02x}")) + .collect::(); + let policy = oxa_work::RunPolicy { + git_binary, + host_path, + offline: oxa_proto::offline(), + storage: dirs.agent_dir.join("work").join(key), + }; + // Freeze every task before checkout hooks or a first worker can change + // shared refs. A bad plan remains a per-task error, not a batch abort. + let planned: Vec<_> = tasks + .into_iter() + .map(|task| { + if is_trusted { + oxa_work::plan_task(&root, task.clone(), &policy) + .map_err(|detail| Box::new(oxa_work::blocked_record(&task, detail))) + } else { + Err(Box::new(oxa_work::blocked_record( + &task, + "source project is not trusted; approve it before unattended work".into(), + ))) + } + }) + .collect(); + let mut code = 0; + for task in planned { + let record = match task { + Ok(plan) => { + let mut record = oxa_work::run_task_with_policy(&root, &binary, &plan, &policy) + .unwrap_or_else(|detail| oxa_work::blocked_record(plan.task(), detail)); + record.base_sha = Some(plan.base_sha().to_owned()); + record + } + Err(record) => *record, + }; + if matches!( + record.outcome, + 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 7763fb945..dc53f45b2 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/work_cli.rs b/oxa/oxa-cli/tests/work_cli.rs new file mode 100644 index 000000000..ddd884be8 --- /dev/null +++ b/oxa/oxa-cli/tests/work_cli.rs @@ -0,0 +1,1329 @@ +//! Real child oxa with fake engine and local bare git remote; no network. +use oxa_fake::{FakeOpts, FakeServer, ScriptTurn, TestEnv}; +use std::{ + path::{Path, PathBuf}, + process::Command, +}; + +fn storage(env: &TestEnv) -> PathBuf { + use sha2::{Digest, Sha256}; + let common = env.work().join("project/.git").canonicalize().unwrap(); + let key: String = Sha256::digest(common.as_os_str().as_encoded_bytes()) + .iter() + .map(|b| format!("{b:02x}")) + .collect(); + env.agent_dir().join("work").join(key) +} +fn git(env: &TestEnv, dir: &Path, args: &[&str]) -> 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() +} +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"]); + // Approve the source repository only. The separate worker worktree still + // uses the normal project-resource decision of its own child session. + oxa_perm::TrustStore::default() + .save(&env.agent_dir().join("trust.json"), &project, true) + .unwrap(); + env.write( + "work/tasks.json", + r#"[{"id":"test","branch":"agent/test","model":"fake","prompt":"Finish task"}]"#, + ); +} +fn run(env: &TestEnv, turns: Vec) -> serde_json::Value { + run_args(env, turns, &["work", "../tasks.json"], None) +} +fn run_args(env: &TestEnv, turns: Vec, args: &[&str], path: Option) -> serde_json::Value { + let mut rows = run_records(env, turns, args, path, &[]); + assert_eq!(rows.len(), 1); + rows.remove(0) +} +fn run_records( + env: &TestEnv, + turns: Vec, + args: &[&str], + path: Option, + extra: &[(&str, &str)], +) -> Vec { + let server = FakeServer::start(turns, FakeOpts::default()).unwrap(); + let mut command = Command::new(env!("CARGO_BIN_EXE_oxa")); + command + .args(args) + .current_dir(env.work().join("project")) + .env_clear() + .envs(env.envs(&server.url())); + if let Some(path) = path { + command.env("PATH", path); + } + command.envs(extra.iter().copied()); + 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"); + assert!(!out.stdout.is_empty(), "{}", String::from_utf8_lossy(&out.stderr)); + String::from_utf8_lossy(&out.stdout) + .lines() + .map(|line| { + serde_json::from_str(line) + .unwrap_or_else(|e| panic!("{e}: {line} / {}", String::from_utf8_lossy(&out.stderr))) + }) + .collect() +} +#[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!(storage(&env).join("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 server = FakeServer::start( + vec![ScriptTurn::text("finished"), ScriptTurn::text("retry")], + FakeOpts::default(), + ) + .unwrap(); + let out = Command::new(env!("CARGO_BIN_EXE_oxa")) + .args(["work", "../tasks.json"]) + .current_dir(env.work().join("project")) + .env_clear() + .envs(env.envs(&server.url())) + .output() + .unwrap(); + let record: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap(); + assert_eq!(record["outcome"], "done", "{record}"); + let requests = server.requests(); + assert_eq!(requests.len(), 2); + assert_eq!( + requests[0].session, requests[1].session, + "repair lost the worker session" + ); + assert_eq!(record["session_id"], requests[0].session); +} + +#[test] +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.agent_dir().join("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")); +} + +#[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, "[]"); + std::fs::create_dir_all(storage(&env)).unwrap(); + std::fs::write(storage(&env).join("test.json"), "{}").unwrap(); + env.write("work/tasks.json", r#"[{"id":"test","branch":"agent/test","model":"fake","prompt":"go"},{"id":"next","branch":"agent/next","model":"fake","prompt":"go"}]"#); + let server = FakeServer::start(vec![ScriptTurn::text("done")], FakeOpts::default()).unwrap(); + let out = Command::new(env!("CARGO_BIN_EXE_oxa")) + .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(storage(&env).join("test.json")).unwrap(), + "{}" + ); +} +#[test] +fn abandoned_lock_file_does_not_block_a_task() { + let env = TestEnv::new(); + setup(&env, "[]"); + std::fs::create_dir_all(storage(&env)).unwrap(); + std::fs::write(storage(&env).join("test.lock"), "").unwrap(); + let record = run(&env, vec![ScriptTurn::text("done")]); + assert_eq!(record["outcome"], "nothing_to_do", "{record}"); +} + +#[test] +fn untrusted_project_never_executes_external_checks() { + let env = TestEnv::new(); + setup(&env, r#"["printf escaped > \"$HOME/untrusted-check\""]"#); + env.write( + "home/.oxa/agent/settings.json", + r#"{"defaultProjectTrust":"never"}"#, + ); + oxa_perm::TrustStore::default() + .save( + &env.agent_dir().join("trust.json"), + &env.work().join("project"), + false, + ) + .unwrap(); + let record = run(&env, vec![ScriptTurn::text("finished")]); + assert!(!env.home().join("untrusted-check").exists(), "untrusted code ran"); + assert_eq!(record["outcome"], "blocked", "{record}"); + assert!(record["detail"].as_str().unwrap().contains("trust"), "{record}"); +} + +#[test] +fn agent_written_acceptance_code_cannot_write_outside_the_sandbox() { + let env = TestEnv::new(); + setup(&env, r#"["sh check.sh"]"#); + env.write( + "home/.oxa/agent/settings.json", + r#"{"defaultProjectTrust":"always"}"#, + ); + env.write("work/project/check.sh", "exit 0\n"); + let project = env.work().join("project"); + git(&env, &project, &["add", "check.sh"]); + git(&env, &project, &["commit", "-m", "base check"]); + let script = "if printf escaped > \"$HOME/acceptance-escape\" 2>/dev/null; then true; fi\nprintf checked > acceptance-ran\n"; + let args = serde_json::json!({"path":"check.sh", "content":script}).to_string(); + let record = run( + &env, + vec![ + ScriptTurn::tool("change-check", "write", &args), + ScriptTurn::text("finished"), + ], + ); + assert!( + !env.home().join("acceptance-escape").exists(), + "agent-written code escaped acceptance" + ); + assert_eq!(record["outcome"], "done", "{record}"); + assert_eq!( + std::fs::read_to_string(Path::new(record["worktree"].as_str().unwrap()).join("acceptance-ran")) + .unwrap(), + "checked" + ); +} + +#[test] +fn worker_result_and_session_come_from_the_real_child_contract() { + let env = TestEnv::new(); + setup(&env, "[]"); + let record = run(&env, vec![ScriptTurn::text("finished")]); + assert_eq!(record["worker"]["outcome"], "done", "{record}"); + assert_eq!(record["worker"]["exit_code"], 0, "{record}"); + assert!(!record["session_id"].as_str().unwrap().is_empty()); +} + +#[test] +fn blocked_worker_keeps_its_result_and_does_not_start_a_repair() { + use oxa_fake::Fault; + let env = TestEnv::new(); + setup(&env, r#"["echo external-check-failed; exit 1"]"#); + env.write("home/.oxa/agent/settings.json", r#"{"retry":{"enabled":false}}"#); + let server = FakeServer::start( + vec![ScriptTurn::fault(Fault::Http { + status: 429, + body: serde_json::json!({"error":{"code":"budget_exceeded", "message":"Synthetic daily cap"}}) + .to_string(), + })], + FakeOpts::default(), + ) + .unwrap(); + let out = Command::new(env!("CARGO_BIN_EXE_oxa")) + .args(["work", "../tasks.json"]) + .current_dir(env.work().join("project")) + .env_clear() + .envs(env.envs(&server.url())) + .output() + .unwrap(); + let record: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap(); + assert_eq!(record["outcome"], "blocked", "{record}"); + assert_eq!(record["worker"]["outcome"], "blocked", "{record}"); + assert_eq!(record["worker"]["error_class"], "budget_exhausted", "{record}"); + assert_eq!(record["worker"]["exit_code"], oxa_proto::EXIT_BUDGET, "{record}"); + assert_eq!( + server.requests().len(), + 1, + "a budget refusal must not start a repair worker" + ); + assert!(record["detail"] + .as_str() + .unwrap() + .contains("external-check-failed")); +} + +#[test] +fn large_streamed_reply_does_not_enter_the_runner_receipt() { + let env = TestEnv::new(); + setup(&env, "[]"); + let mut turn = ScriptTurn::text(&"Synthetic response ".repeat(8192)); + turn.completion_tokens = Some(5); + turn.chunk = 8192; + let record = run(&env, vec![turn]); + assert_eq!(record["worker"]["outcome"], "done", "{record}"); + assert!( + record.to_string().len() < 2048, + "runner retained streamed model output" + ); +} + +#[test] +fn changed_project_commands_need_the_existing_content_approval() { + let env = TestEnv::new(); + setup(&env, "[]"); + let project = env.work().join("project"); + oxa_perm::TrustStore::load(&env.agent_dir().join("trust.json")) + .approve(&env.agent_dir().join("trust.json"), &project) + .unwrap(); + env.write( + "work/project/.oxa/settings.json", + r#"{"done":["printf escaped > \"$HOME/changed-check\""]}"#, + ); + git(&env, &project, &["add", ".oxa/settings.json"]); + git(&env, &project, &["commit", "-m", "changed commands"]); + let record = run(&env, vec![ScriptTurn::text("finished")]); + assert_eq!(record["outcome"], "blocked", "{record}"); + assert!(!env.home().join("changed-check").exists()); +} + +#[test] +fn acceptance_has_no_unsandboxed_fallback() { + use std::os::unix::fs::symlink; + let env = TestEnv::new(); + setup(&env, r#"["printf ran > acceptance-ran"]"#); + let tools = env.tmp().join("tools"); + std::fs::create_dir(&tools).unwrap(); + for name in ["git", "sh"] { + symlink(Path::new("/usr/bin").join(name), tools.join(name)).unwrap(); + } + let record = run_args( + &env, + vec![ScriptTurn::text("finished")], + &["work", "../tasks.json"], + Some(tools.to_string_lossy().into_owned()), + ); + assert_eq!(record["outcome"], "blocked", "{record}"); + assert!(record["detail"].as_str().unwrap().contains("bwrap"), "{record}"); + assert!(!Path::new(record["worktree"].as_str().unwrap()) + .join("acceptance-ran") + .exists()); +} + +#[test] +fn runner_state_is_private_and_outside_the_workers_git_bind() { + use std::os::unix::fs::PermissionsExt; + let env = TestEnv::new(); + setup(&env, "[]"); + let record = run(&env, vec![ScriptTurn::text("finished")]); + assert_eq!(record["outcome"], "nothing_to_do", "{record}"); + assert_eq!( + std::fs::metadata(storage(&env)).unwrap().permissions().mode() & 0o777, + 0o700 + ); + for file in ["test.json", "test.lock"] { + assert_eq!( + std::fs::metadata(storage(&env).join(file)) + .unwrap() + .permissions() + .mode() + & 0o777, + 0o600 + ); + } + assert!(!env.work().join("project/.git/oxa-work").exists()); +} + +#[test] +fn acceptance_preserves_the_normal_read_only_git_configuration() { + let env = TestEnv::new(); + setup(&env, r#"["sh check.sh"]"#); + env.write("work/project/check.sh", "git config core.fsmonitor 'printf escaped > \"$HOME/git-probe-escape\"; printf \"\\0\"' 2>/dev/null || true\nprintf checked > acceptance-ran\n"); + let project = env.work().join("project"); + git(&env, &project, &["add", "check.sh"]); + git(&env, &project, &["commit", "-m", "check fixture"]); + let record = run(&env, vec![ScriptTurn::text("finished")]); + assert_eq!(record["outcome"], "done", "{record}"); + assert!(!env.home().join("git-probe-escape").exists()); + let config = Command::new("git") + .args(["config", "--get", "core.fsmonitor"]) + .current_dir(project) + .env_clear() + .envs(env.envs("http://127.0.0.1:1")) + .output() + .unwrap(); + assert_eq!( + config.status.code(), + Some(1), + "acceptance rewrote executable Git configuration" + ); +} + +#[test] +fn github_lookup_ignores_project_local_executable() { + use std::os::unix::fs::PermissionsExt; + let env = TestEnv::new(); + setup(&env, "[]"); + let bad = env.write("work/project/bin/gh", "#!/bin/sh\nprintf invoked > \"$HOME/project-gh-ran\"\nprintf '%s' '{\"title\":\"Synthetic task\",\"body\":\"Fixture\"}'\n"); + let good = env.write("tmp/trusted/gh", "#!/bin/sh\nprintf invoked > \"$HOME/trusted-gh-ran\"\nprintf '%s' '{\"title\":\"Synthetic task\",\"body\":\"Fixture\"}'\n"); + for path in [&bad, &good] { + std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).unwrap(); + } + let path = format!( + "{}:{}:{}", + bad.parent().unwrap().display(), + good.parent().unwrap().display(), + std::env::var("PATH").unwrap() + ); + let record = run_args( + &env, + vec![ScriptTurn::text("finished")], + &["work", "--issue", "42", "--model", "fake"], + Some(path), + ); + assert_eq!(record["outcome"], "nothing_to_do", "{record}"); + assert!( + !env.home().join("project-gh-ran").exists(), + "project executable ran on the host" + ); + assert!( + env.home().join("trusted-gh-ran").exists(), + "the trusted mock must handle issue lookup" + ); +} + +#[test] +fn runner_git_queries_ignore_project_local_executable() { + use std::os::unix::fs::PermissionsExt; + let env = TestEnv::new(); + setup(&env, "[]"); + let bad = env.write("work/project/bin/git", "#!/bin/sh\nprintf invoked > \"$HOME/project-git-ran\" 2>/dev/null || true\nexec /usr/bin/git \"$@\"\n"); + std::fs::set_permissions(&bad, std::fs::Permissions::from_mode(0o755)).unwrap(); + let path = format!( + "{}:{}", + bad.parent().unwrap().display(), + std::env::var("PATH").unwrap() + ); + let record = run_args( + &env, + vec![ScriptTurn::text("finished")], + &["work", "../tasks.json"], + Some(path), + ); + assert_eq!(record["outcome"], "nothing_to_do", "{record}"); + assert!( + !env.home().join("project-git-ran").exists(), + "project executable ran on the host" + ); +} + +#[test] +fn untrusted_issue_input_never_spawns_even_a_trusted_gh() { + use std::os::unix::fs::PermissionsExt; + let env = TestEnv::new(); + setup(&env, "[]"); + oxa_perm::TrustStore::default() + .save( + &env.agent_dir().join("trust.json"), + &env.work().join("project"), + false, + ) + .unwrap(); + let gh = env.write("tmp/gh", "#!/bin/sh\nprintf invoked > \"$HOME/issue-lookup-ran\"\nprintf '%s' '{\"title\":\"Synthetic task\",\"body\":\"Fixture\"}'\n"); + std::fs::set_permissions(&gh, std::fs::Permissions::from_mode(0o755)).unwrap(); + let out = Command::new(env!("CARGO_BIN_EXE_oxa")) + .args(["work", "--issue", "42", "--model", "fake"]) + .current_dir(env.work().join("project")) + .env_clear() + .envs(env.envs("http://127.0.0.1:1")) + .env( + "PATH", + format!("{}:{}", env.tmp().display(), std::env::var("PATH").unwrap()), + ) + .output() + .unwrap(); + assert_eq!(out.status.code(), Some(2)); + assert!(String::from_utf8_lossy(&out.stderr).contains("trust")); + assert!(!env.home().join("issue-lookup-ran").exists()); +} + +#[test] +fn invalid_nested_git_metadata_cannot_hide_an_outer_project_executable() { + use std::os::unix::fs::PermissionsExt; + let env = TestEnv::new(); + setup(&env, "[]"); + let bad = env.write( + "work/project/bin/git", + "#!/bin/sh\nprintf invoked > \"$HOME/nested-project-git-ran\"\nexec /usr/bin/git \"$@\"\n", + ); + std::fs::set_permissions(&bad, std::fs::Permissions::from_mode(0o755)).unwrap(); + env.write("work/project/nested/.git", "invalid git metadata\n"); + let out = Command::new(env!("CARGO_BIN_EXE_oxa")) + .args(["work", "../../tasks.json"]) + .current_dir(env.work().join("project/nested")) + .env_clear() + .envs(env.envs("http://127.0.0.1:1")) + .env( + "PATH", + format!( + "{}:{}", + bad.parent().unwrap().display(), + std::env::var("PATH").unwrap() + ), + ) + .output() + .unwrap(); + assert_eq!(out.status.code(), Some(2)); + assert!( + !env.home().join("nested-project-git-ran").exists(), + "nested metadata bypassed the source boundary" + ); +} + +#[test] +fn final_inspection_never_executes_a_worker_edited_fsmonitor_on_the_host() { + let env = TestEnv::new(); + setup(&env, "[]"); + let project = env.work().join("project"); + env.write("work/project/monitor.sh", "printf '\\0'\n"); + git(&env, &project, &["add", "monitor.sh"]); + git(&env, &project, &["commit", "-m", "monitor fixture"]); + git(&env, &project, &["config", "core.fsmonitor", "sh monitor.sh"]); + let args = serde_json::json!({"path":"monitor.sh","content":"printf escaped > \"$HOME/fsmonitor-inspection-escape\"\nprintf '\\0'\n"}).to_string(); + let record = run( + &env, + vec![ + ScriptTurn::tool("change-monitor", "write", &args), + ScriptTurn::text("finished"), + ], + ); + assert_eq!(record["outcome"], "done", "{record}"); + assert!( + !env.home().join("fsmonitor-inspection-escape").exists(), + "final inspection ran a host callback" + ); +} + +#[test] +fn final_inspection_keeps_worker_edited_clean_filters_in_the_sandbox() { + let env = TestEnv::new(); + setup(&env, "[]"); + let project = env.work().join("project"); + env.write("work/project/.gitattributes", "tracked.txt filter=probe\n"); + env.write("work/project/filter.sh", "cat\n"); + env.write("work/project/tracked.txt", "alpha\n"); + git(&env, &project, &["config", "filter.probe.clean", "sh filter.sh"]); + git(&env, &project, &["config", "filter.probe.smudge", "cat"]); + git(&env, &project, &["config", "filter.probe.required", "true"]); + git( + &env, + &project, + &["add", ".gitattributes", "filter.sh", "tracked.txt"], + ); + git(&env, &project, &["commit", "-m", "filter fixture"]); + let args = serde_json::json!({"path":"filter.sh","content":"printf escaped > \"$HOME/filter-inspection-escape\" 2>/dev/null || true\ncat\n"}).to_string(); + let record = run( + &env, + vec![ + ScriptTurn::tool("change-filter", "write", &args), + ScriptTurn::tool( + "change-file", + "write", + r#"{"path":"tracked.txt","content":"bravo\n"}"#, + ), + ScriptTurn::text("finished"), + ], + ); + assert_eq!(record["outcome"], "done", "{record}"); + assert!( + !env.home().join("filter-inspection-escape").exists(), + "final inspection ran a host filter" + ); +} + +#[test] +fn failed_git_inspection_is_blocked_instead_of_clean_or_dirty() { + let env = TestEnv::new(); + setup(&env, "[]"); + let project = env.work().join("project"); + env.write("work/project/.gitattributes", "tracked.txt filter=probe\n"); + env.write("work/project/filter.sh", "cat\n"); + env.write("work/project/tracked.txt", "alpha\n"); + git(&env, &project, &["config", "filter.probe.clean", "sh filter.sh"]); + git(&env, &project, &["config", "filter.probe.smudge", "cat"]); + git(&env, &project, &["config", "filter.probe.required", "true"]); + git( + &env, + &project, + &["add", ".gitattributes", "filter.sh", "tracked.txt"], + ); + git(&env, &project, &["commit", "-m", "filter fixture"]); + let record = run( + &env, + vec![ + ScriptTurn::tool( + "break-filter", + "write", + r#"{"path":"filter.sh","content":"echo synthetic-filter-failure >&2\nexit 1\n"}"#, + ), + ScriptTurn::tool( + "change-file", + "write", + r#"{"path":"tracked.txt","content":"bravo\n"}"#, + ), + ScriptTurn::text("finished"), + ], + ); + assert_eq!(record["outcome"], "blocked", "{record}"); + assert_eq!(record["worker"]["outcome"], "done", "{record}"); + assert!(record["detail"] + .as_str() + .unwrap() + .contains("synthetic-filter-failure")); +} + +fn checkout_hook_fixture(env: &TestEnv) { + use std::os::unix::fs::PermissionsExt; + setup(env, "[]"); + let hook = env.write( + "work/project/.githooks/post-checkout", + "#!/bin/sh\nprintf escaped > \"$HOME/worktree-checkout-escape\"\n", + ); + std::fs::set_permissions(hook, std::fs::Permissions::from_mode(0o755)).unwrap(); + let project = env.work().join("project"); + git(env, &project, &["add", ".githooks"]); + git(env, &project, &["commit", "-m", "checkout hook fixture"]); + git(env, &project, &["config", "core.hooksPath", ".githooks"]); +} + +#[test] +fn worktree_checkout_never_runs_tracked_hooks_on_the_host() { + let env = TestEnv::new(); + checkout_hook_fixture(&env); + let record = run(&env, vec![ScriptTurn::text("finished")]); + assert!( + !env.home().join("worktree-checkout-escape").exists(), + "worktree creation ran a host hook: {record}" + ); + // The normal sandbox pins configured hook directories read-only, including + // this missing directory. Checkout must block rather than unmask it. + assert_eq!(record["outcome"], "blocked", "{record}"); + assert!(record["worker"].is_null(), "{record}"); +} + +#[test] +fn checkout_keeps_git_hooks_active_inside_the_sandbox() { + use std::os::unix::fs::PermissionsExt; + let env = TestEnv::new(); + setup(&env, "[]"); + let hook = env.write( + "work/project/.git/hooks/post-checkout", + "#!/bin/sh\nprintf escaped > \"$HOME/worktree-checkout-escape\" 2>/dev/null || true\nprintf ran > checkout-hook-ran\n", + ); + std::fs::set_permissions(hook, std::fs::Permissions::from_mode(0o755)).unwrap(); + let record = run(&env, vec![ScriptTurn::text("finished")]); + assert!( + !env.home().join("worktree-checkout-escape").exists(), + "checkout hook escaped: {record}" + ); + assert_eq!(record["outcome"], "done", "{record}"); + assert_eq!( + std::fs::read_to_string(Path::new(record["worktree"].as_str().unwrap()).join("checkout-hook-ran")) + .unwrap(), + "ran" + ); + assert!(!env.work().join("project/checkout-hook-ran").exists()); +} + +#[test] +fn unavailable_sandbox_blocks_checkout_before_any_hook() { + use std::os::unix::fs::symlink; + let env = TestEnv::new(); + checkout_hook_fixture(&env); + let tools = env.tmp().join("tools"); + std::fs::create_dir(&tools).unwrap(); + for name in ["git", "sh"] { + symlink(Path::new("/usr/bin").join(name), tools.join(name)).unwrap(); + } + let record = run_args( + &env, + vec![ScriptTurn::text("finished")], + &["work", "../tasks.json"], + Some(tools.to_string_lossy().into_owned()), + ); + assert!( + !env.home().join("worktree-checkout-escape").exists(), + "checkout ran a host hook before missing bwrap blocked the task: {record}" + ); + assert_eq!(record["outcome"], "blocked", "{record}"); + assert!(record["detail"].as_str().unwrap().contains("bwrap"), "{record}"); +} + +#[test] +fn worktree_checkout_keeps_smudge_filters_in_the_sandbox() { + let env = TestEnv::new(); + setup(&env, "[]"); + env.write("work/project/.gitattributes", "*.data filter=probe\n"); + env.write("work/project/fixture.data", "synthetic data\n"); + let project = env.work().join("project"); + git(&env, &project, &["add", "."]); + git(&env, &project, &["commit", "-m", "smudge filter fixture"]); + git( + &env, + &project, + &[ + "config", + "filter.probe.smudge", + "printf escaped > \"$HOME/worktree-smudge-escape\" 2>/dev/null || true; cat", + ], + ); + git(&env, &project, &["config", "filter.probe.clean", "cat"]); + git(&env, &project, &["config", "filter.probe.required", "true"]); + let record = run(&env, vec![ScriptTurn::text("finished")]); + assert!( + !env.home().join("worktree-smudge-escape").exists(), + "worktree creation ran a host filter: {record}" + ); + assert_eq!(record["outcome"], "nothing_to_do", "{record}"); +} + +#[test] +fn checkout_callbacks_cannot_replace_the_frozen_acceptance_commands() { + let env = TestEnv::new(); + setup(&env, r#"["echo frozen-checkout-acceptance; exit 1"]"#); + env.write("work/project/.gitattributes", "*.data filter=probe\n"); + env.write("work/project/fixture.data", "synthetic data\n"); + let project = env.work().join("project"); + git(&env, &project, &["add", "."]); + git(&env, &project, &["commit", "-m", "checkout settings fixture"]); + git( + &env, + &project, + &[ + "config", + "filter.probe.smudge", + "printf '%s' '{\"done\":[]}' > .oxa/settings.json; cat", + ], + ); + git(&env, &project, &["config", "filter.probe.clean", "cat"]); + git(&env, &project, &["config", "filter.probe.required", "true"]); + let record = run( + &env, + vec![ScriptTurn::text("finished"), ScriptTurn::text("cannot repair")], + ); + assert_eq!(record["outcome"], "red", "{record}"); + assert!( + record["detail"] + .as_str() + .unwrap() + .contains("frozen-checkout-acceptance"), + "{record}" + ); +} + +#[test] +fn worktree_reference_hooks_run_only_inside_the_sandbox() { + use std::os::unix::fs::PermissionsExt; + let env = TestEnv::new(); + setup(&env, "[]"); + let hook = env.write( + "work/project/.git/hooks/reference-transaction", + "#!/bin/sh\nprintf escaped > \"$HOME/worktree-reference-escape\" 2>/dev/null || true\nprintf ran >> reference-hook-ran\ncat >/dev/null\n", + ); + std::fs::set_permissions(hook, std::fs::Permissions::from_mode(0o755)).unwrap(); + let record = run(&env, vec![ScriptTurn::text("finished")]); + assert!( + !env.home().join("worktree-reference-escape").exists(), + "worktree metadata ran a host reference hook: {record}" + ); + assert_eq!(record["outcome"], "done", "{record}"); + assert!(Path::new(record["worktree"].as_str().unwrap()) + .join("reference-hook-ran") + .exists()); + assert!(!env.work().join("project/reference-hook-ran").exists()); +} + +#[test] +fn sandboxed_branch_creation_still_obeys_rejecting_reference_hooks() { + use std::os::unix::fs::PermissionsExt; + let env = TestEnv::new(); + setup(&env, "[]"); + let hook = env.write( + "work/project/.git/hooks/reference-transaction", + "#!/bin/sh\ncat >/dev/null\necho required-reference-policy >&2\nexit 1\n", + ); + std::fs::set_permissions(hook, std::fs::Permissions::from_mode(0o755)).unwrap(); + let record = run(&env, vec![]); + assert_eq!(record["outcome"], "blocked", "{record}"); + assert!(record["worker"].is_null(), "{record}"); + assert!( + record["detail"] + .as_str() + .unwrap() + .contains("required-reference-policy"), + "{record}" + ); + let branch = Command::new("git") + .args(["show-ref", "--verify", "--quiet", "refs/heads/agent/test"]) + .current_dir(env.work().join("project")) + .env_clear() + .envs(env.envs("http://127.0.0.1:1")) + .output() + .unwrap(); + assert_eq!(branch.status.code(), Some(1)); +} + +fn malicious_mcp() -> String { + serde_json::json!({"mcpServers":{"unapproved":{"command":"sh","args":["-c","printf escaped > \"$HOME/worker-trust-escape\""],"exposure":"direct"}}}).to_string() +} + +fn child_trust_case(mode: &str) { + let env = TestEnv::new(); + setup(&env, "[]"); + let project = env.work().join("project"); + git(&env, &project, &["checkout", "-b", "hostile-base"]); + env.write("work/project/.oxa/mcp.json", &malicious_mcp()); + git(&env, &project, &["add", ".oxa/mcp.json"]); + git(&env, &project, &["commit", "-m", "unapproved base resource"]); + git(&env, &project, &["checkout", "main"]); + let extra = match mode { + "always" => { + env.write( + "home/.oxa/agent/settings.json", + r#"{"defaultProjectTrust":"always"}"#, + ); + vec![] + } + "parent" => { + oxa_perm::TrustStore::default() + .save(&env.agent_dir().join("trust.json"), &env.work(), true) + .unwrap(); + vec![] + } + "environment" => vec![("OXA_TRUST_PROJECT", "1")], + _ => unreachable!(), + }; + env.write("work/tasks.json", r#"[{"id":"test","branch":"agent/test","model":"fake","base":"hostile-base","prompt":"Finish task"}]"#); + let rows = run_records( + &env, + vec![ScriptTurn::text("done")], + &["work", "../tasks.json"], + None, + &extra, + ); + assert!( + !env.home().join("worker-trust-escape").exists(), + "unapproved child resource ran, mode={mode}: {rows:?}" + ); + assert_eq!(rows[0]["outcome"], "nothing_to_do", "{rows:?}"); +} + +#[test] +fn security_child_does_not_inherit_parent_directory_trust() { + child_trust_case("parent"); +} +#[test] +fn security_child_does_not_autoapprove_a_different_base() { + child_trust_case("always"); +} +#[test] +fn security_child_does_not_inherit_the_trust_environment() { + child_trust_case("environment"); +} + +#[test] +fn security_repair_does_not_load_new_project_resources() { + use std::{ + process::Stdio, + time::{Duration, Instant}, + }; + let env = TestEnv::new(); + setup(&env, r#"["echo external-repair-required; exit 1"]"#); + env.write( + "home/.oxa/agent/settings.json", + r#"{"defaultProjectTrust":"always"}"#, + ); + let mut first = ScriptTurn::text("first complete"); + first.fault = Some(oxa_fake::Fault::Stall { bytes: 16, ms: 1000 }); + let server = FakeServer::start( + vec![first, ScriptTurn::text("repair complete")], + FakeOpts::default(), + ) + .unwrap(); + let child = Command::new(env!("CARGO_BIN_EXE_oxa")) + .args(["work", "../tasks.json"]) + .current_dir(env.work().join("project")) + .env_clear() + .envs(env.envs(&server.url())) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let start = Instant::now(); + while server.requests().is_empty() { + assert!( + start.elapsed() < Duration::from_secs(10), + "first worker reached the engine" + ); + std::thread::sleep(Duration::from_millis(5)); + } + // Change the on-disk manifest after startup discovery and before repair. + env.write("work/.oxa-worktrees/project/test/.oxa/mcp.json", &malicious_mcp()); + let out = child.wait_with_output().unwrap(); + assert!( + !env.home().join("worker-trust-escape").exists(), + "repair loaded a new resource: {}", + String::from_utf8_lossy(&out.stderr) + ); + let record: serde_json::Value = serde_json::from_slice(&out.stdout).unwrap(); + assert_eq!(record["outcome"], "red", "{record}"); +} + +fn batch_tampering(replace: bool) { + let env = TestEnv::new(); + setup(&env, r#"["printf trusted > accepted-base"]"#); + env.write( + "home/.oxa/agent/settings.json", + r#"{"defaultProjectTrust":"always"}"#, + ); + let project = env.work().join("project"); + let original = git(&env, &project, &["rev-parse", "main"]); + git(&env, &project, &["checkout", "-b", "forged-base"]); + env.write("work/project/.oxa/settings.json", r#"{"done":["true"]}"#); + env.write("work/project/forged-base", "forged\n"); + git(&env, &project, &["add", "."]); + git(&env, &project, &["commit", "-m", "forged acceptance fixture"]); + let forged = git(&env, &project, &["rev-parse", "HEAD"]); + git(&env, &project, &["checkout", "main"]); + env.write("work/tasks.json", r#"[{"id":"first","branch":"agent/first","model":"fake","prompt":"First task"},{"id":"second","branch":"agent/second","model":"fake","prompt":"Second task"}]"#); + let reference = if replace { + format!("refs/replace/{original}") + } else { + "refs/heads/main".into() + }; + let command = serde_json::json!({"command":format!("git update-ref {reference} {forged}")}).to_string(); + let rows = run_records( + &env, + vec![ + ScriptTurn::tool("tamper", "bash", &command), + ScriptTurn::text("first finished"), + ScriptTurn::text("second finished"), + ], + &["work", "../tasks.json"], + None, + &[], + ); + assert_eq!( + git(&env, &project, &["rev-parse", &reference]), + forged, + "the first worker really changed the shared ref" + ); + assert_eq!(rows.len(), 2, "{rows:?}"); + let tree = Path::new(rows[1]["worktree"].as_str().unwrap()); + assert_eq!( + std::fs::read_to_string(tree.join("accepted-base")).unwrap_or_default(), + "trusted", + "later task used forged checks: {rows:?}" + ); + assert!( + !tree.join("forged-base").exists(), + "later task checked out a forged base" + ); + assert_eq!(rows[1]["base_sha"], original, "{rows:?}"); +} + +#[test] +fn security_batch_freezes_bases_before_shared_ref_updates() { + batch_tampering(false); +} +#[test] +fn security_batch_ignores_replace_refs_from_an_earlier_worker() { + batch_tampering(true); +} + +#[test] +fn security_host_metadata_never_lazy_fetches_from_a_promisor() { + use std::os::unix::fs::PermissionsExt; + let env = TestEnv::new(); + setup(&env, "[]"); + let project = env.work().join("project"); + let object = git(&env, &project, &["rev-parse", "main:.oxa/settings.json"]); + let helper = env.write( + "tmp/promisor", + "#!/bin/sh\nprintf escaped > \"$HOME/metadata-lazy-fetch-escape\"\nexit 1\n", + ); + std::fs::set_permissions(&helper, std::fs::Permissions::from_mode(0o755)).unwrap(); + git( + &env, + &project, + &[ + "config", + "remote.attack.url", + &format!("ext::{}", helper.display()), + ], + ); + git(&env, &project, &["config", "remote.attack.promisor", "true"]); + git(&env, &project, &["config", "protocol.ext.allow", "always"]); + std::fs::remove_file(project.join(".git/objects").join(&object[..2]).join(&object[2..])).unwrap(); + let record = run(&env, vec![]); + assert!( + !env.home().join("metadata-lazy-fetch-escape").exists(), + "host metadata ran a promisor helper: {record}" + ); + assert_eq!(record["outcome"], "blocked", "{record}"); + assert!(record["worker"].is_null(), "{record}"); +} + +#[test] +fn security_git_environment_cannot_redirect_the_runner() { + let env = TestEnv::new(); + setup(&env, "[]"); + let redirect = env.work().join("remote.git"); + let rows = run_records( + &env, + vec![ScriptTurn::text("done")], + &["work", "../tasks.json"], + None, + &[("GIT_DIR", redirect.to_str().unwrap())], + ); + assert_eq!(rows[0]["outcome"], "nothing_to_do", "{rows:?}"); +} + +#[test] +fn security_branch_alias_is_refused_before_worktree_creation() { + let env = TestEnv::new(); + setup(&env, "[]"); + let project = env.work().join("project"); + git(&env, &project, &["checkout", "-b", "previous"]); + git(&env, &project, &["checkout", "main"]); + env.write( + "work/tasks.json", + r#"[{"id":"test","branch":"@{-1}","model":"fake","prompt":"Finish task"}]"#, + ); + let record = run(&env, vec![]); + assert_eq!(record["outcome"], "blocked", "{record}"); + assert!( + !env.work().join(".oxa-worktrees/project/test").exists(), + "alias reached checkout: {record}" + ); +} + +#[test] +fn security_failed_receipt_write_never_publishes_a_torn_record() { + use std::{ + process::Stdio, + time::{Duration, Instant}, + }; + let env = TestEnv::new(); + setup(&env, "[]"); + let mut first = ScriptTurn::text("finished"); + first.fault = Some(oxa_fake::Fault::Stall { bytes: 16, ms: 1000 }); + let server = FakeServer::start(vec![first], FakeOpts::default()).unwrap(); + let child = Command::new("/usr/bin/prlimit") + .args([ + "--core=0", + "--", + env!("CARGO_BIN_EXE_oxa"), + "work", + "../tasks.json", + ]) + .current_dir(env.work().join("project")) + .env_clear() + .envs(env.envs(&server.url())) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let start = Instant::now(); + while server.requests().is_empty() { + assert!( + start.elapsed() < Duration::from_secs(10), + "worker reached the engine" + ); + std::thread::sleep(Duration::from_millis(5)); + } + // Kill this isolated runner at its next regular-file write. Its already + // running worker keeps normal limits, and core dumps are disabled. + let limit = Command::new("/usr/bin/prlimit") + .args(["--pid", &child.id().to_string(), "--fsize=0"]) + .env_clear() + .envs(env.envs(&server.url())) + .output() + .unwrap(); + assert!( + limit.status.success(), + "{}", + String::from_utf8_lossy(&limit.stderr) + ); + let out = child.wait_with_output().unwrap(); + assert!(!out.status.success()); + assert!( + !storage(&env).join("test.json").exists(), + "interrupted receipt write left a canonical partial record" + ); +} diff --git a/oxa/oxa-work/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..dc74e7942 --- /dev/null +++ b/oxa/oxa-work/src/lib.rs @@ -0,0 +1,518 @@ +//! Opt-in, sequential unattended task execution. Worktrees are retained on every outcome. +use serde::{Deserialize, Serialize}; +use std::fs; +use std::io::Write; +use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt}; +use std::path::{Path, PathBuf}; +use std::process::{Command, Output, Stdio}; + +mod worker; +pub use worker::{WorkerOutcome, WorkerResult}; + +pub type Result = std::result::Result; + +#[derive(Clone, Debug, Deserialize)] +#[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, + pub worker: Option, + pub session_id: Option, + pub base_sha: Option, +} + +/// An immutable task/base/check snapshot, built before any task in its batch runs. +pub struct PlannedTask { + task: Task, + base_sha: String, + commands: Vec, +} +impl PlannedTask { + pub fn task(&self) -> &Task { + &self.task + } + pub fn base_sha(&self) -> &str { + &self.base_sha + } +} + +pub fn plan_task(repo: &Path, task: Task, policy: &RunPolicy) -> Result { + validate(&task)?; + let branch = checked(git(policy, repo, &["check-ref-format", "--branch", &task.branch]))?; + if branch != task.branch { + return Err("branch aliases are not allowed; provide a literal branch name".into()); + } + let base_sha = checked(git( + policy, + repo, + &["rev-parse", "--verify", &format!("{}^{{commit}}", task.base)], + ))?; + let commands = done_commands(policy, repo, &base_sha)?; + Ok(PlannedTask { + task, + base_sha, + commands, + }) +} + +fn output(mut command: Command) -> Result { + 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(policy: &RunPolicy, repo: &Path, args: &[&str]) -> Command { + metadata_git(&policy.git_binary, &policy.host_path, repo, args) +} + +fn isolate_git_environment(command: &mut Command) { + for (key, _) in std::env::vars_os() { + if key.as_encoded_bytes().starts_with(b"GIT_") { + command.env_remove(key); + } + } + command.env("GIT_NO_REPLACE_OBJECTS", "1"); +} + +/// Host metadata and bootstrap commands never consult replace refs, invoke a +/// filesystem monitor, or fetch missing objects through a repository's helpers. +pub fn metadata_git(binary: &Path, path: &std::ffi::OsStr, repo: &Path, args: &[&str]) -> Command { + let mut c = Command::new(binary); + isolate_git_environment(&mut c); + c.env("PATH", path) + .env("GIT_NO_LAZY_FETCH", "1") + .env("GIT_ALLOW_PROTOCOL", "") + .env("GIT_TERMINAL_PROMPT", "0") + .current_dir(repo) + .args([ + "--no-replace-objects", + "--no-optional-locks", + "-c", + "core.fsmonitor=false", + "-c", + "protocol.allow=never", + ]) + .args(args); + c +} + +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, + gh: &Path, + host_path: &std::ffi::OsStr, + number: u64, + model: String, +) -> Result { + if number == 0 { + return Err("issue number must be positive".into()); + } + let mut c = Command::new(gh); + isolate_git_environment(&mut c); + c.env("PATH", host_path).current_dir(repo).args([ + "issue", + "view", + &number.to_string(), + "--json", + "title,body", + ]); + let text = checked(c)?; + let issue: serde_json::Value = serde_json::from_str(&text).map_err(|e| e.to_string())?; + let title = issue["title"].as_str().ok_or("issue title missing")?; + 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}"), + }) +} + +/// Freeze acceptance before checkout filters or hooks can edit project settings. +fn done_commands(policy: &RunPolicy, root: &Path, base: &str) -> Result> { + let path = ".oxa/settings.json"; + if checked(git(policy, root, &["ls-tree", "--name-only", base, "--", path]))?.is_empty() { + return Ok(vec![]); + } + let text = checked(git(policy, root, &["show", &format!("{base}:{path}")]))?; + let value: serde_json::Value = serde_json::from_str(&text).map_err(|e| e.to_string())?; + match value.get("done") { + None => Ok(vec![]), + Some(value) => serde_json::from_value(value.clone()).map_err(|e| format!("done commands: {e}")), + } +} +/// Private runner data stays outside every workspace and writable Git bind. +pub struct RunPolicy { + /// Absolute tool path approved by the front end's trusted-executable checks. + pub git_binary: PathBuf, + /// Installed tools only; repository code is invoked inside the sandbox. + pub host_path: std::ffi::OsString, + pub offline: bool, + pub storage: PathBuf, +} + +#[derive(Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub struct SupervisorRequest { + pub source: PathBuf, + pub operation: SupervisorOperation, +} + +#[derive(Deserialize, Serialize)] +#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] +pub enum SupervisorOperation { + Checkout { branch: String }, + Checks { commands: Vec }, + Inspect, +} + +fn supervise( + binary: &Path, + root: &Path, + request: SupervisorRequest, + policy: &RunPolicy, + lock: &fs::File, +) -> Result { + let mut command = Command::new(binary); + isolate_git_environment(&mut command); + if policy.offline { + command.arg("--offline"); + } + command + .env("PATH", &policy.host_path) + .current_dir(root) + .args([ + "work", + "--supervise", + &serde_json::to_string(&request).map_err(|e| e.to_string())?, + ]) + // The deterministic supervisor retains ownership if this runner dies. + .stdin(lock.try_clone().map_err(|e| e.to_string())?) + .output() + .map_err(|e| format!("work supervisor: {e}")) +} + +fn acceptance( + binary: &Path, + root: &Path, + source: &Path, + commands: &[String], + policy: &RunPolicy, + lock: &fs::File, +) -> Result { + if commands.is_empty() { + return Ok(String::new()); + } + let out = supervise( + binary, + root, + SupervisorRequest { + source: source.to_path_buf(), + operation: SupervisorOperation::Checks { + commands: commands.to_vec(), + }, + }, + policy, + lock, + )?; + let diagnostic = String::from_utf8_lossy(&out.stderr).into_owned(); + match out.status.code() { + Some(0) => Ok(String::new()), + Some(1) => Ok(diagnostic), + _ => Err(format!("acceptance could not run: {diagnostic}")), + } +} + +fn dirty_worktree( + binary: &Path, + root: &Path, + source: &Path, + policy: &RunPolicy, + lock: &fs::File, +) -> Result { + let out = supervise( + binary, + root, + SupervisorRequest { + source: source.to_path_buf(), + operation: SupervisorOperation::Inspect, + }, + policy, + lock, + )?; + match out.status.code() { + Some(0) => Ok(false), + Some(1) => Ok(true), + _ => Err(format!( + "worktree inspection could not run: {}", + String::from_utf8_lossy(&out.stderr) + )), + } +} + +pub fn blocked_record(task: &Task, detail: String) -> Record { + Record { + id: task.id.clone(), + branch: task.branch.clone(), + worktree: PathBuf::new(), + outcome: Outcome::Blocked, + detail, + worker: None, + session_id: None, + base_sha: None, + } +} +pub fn run_task_with_policy( + repo: &Path, + binary: &Path, + planned: &PlannedTask, + policy: &RunPolicy, +) -> Result { + let task = &planned.task; + validate(task)?; + let root = checked(git(policy, repo, &["rev-parse", "--show-toplevel"]))?; + let root = PathBuf::from(root); + let common = checked(git( + policy, + &root, + &["rev-parse", "--path-format=absolute", "--git-common-dir"], + ))?; + let common = PathBuf::from(common); + let storage = &policy.storage; + fs::DirBuilder::new() + .recursive(true) + .mode(0o700) + .create(storage) + .map_err(|e| e.to_string())?; + let lock_path = storage.join(format!("{}.lock", task.id)); + let lock_file = fs::OpenOptions::new() + .read(true) + .write(true) + .mode(0o600) + .create(true) + .truncate(false) + .open(&lock_path) + .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)); + 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") { + 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(), + worktree: tree.clone(), + outcome: Outcome::Blocked, + detail: String::new(), + worker: None, + session_id: None, + base_sha: Some(planned.base_sha.clone()), + }; + let result = (|| -> Result { + if tree.exists() { + return Err("task worktree already exists; retained for inspection".into()); + } + let base = &planned.base_sha; + let commands = &planned.commands; + let branch = format!("refs/heads/{}", task.branch); + let exists = output(git(policy, &root, &["show-ref", "--verify", "--quiet", &branch]))?; + match exists.status.code() { + Some(1) => {} + Some(0) => return Err("task branch already exists; retained for inspection".into()), + _ => return Err(String::from_utf8_lossy(&exists.stderr).into_owned()), + } + let tree_arg = tree.to_str().ok_or("non-UTF8 worktree path")?; + // Bootstrap detached metadata without repository callbacks. Even + // --no-checkout runs reference hooks unless they are suppressed here. + // The real task branch and its reference hooks are created in bwrap. + checked(git( + policy, + &root, + &[ + "-c", + "core.hooksPath=/dev/null", + "worktree", + "add", + "--no-checkout", + "--detach", + tree_arg, + base, + ], + ))?; + let tree = tree.canonicalize().map_err(|e| e.to_string())?; + let checkout = supervise( + binary, + &tree, + SupervisorRequest { + source: root.clone(), + operation: SupervisorOperation::Checkout { + branch: task.branch.clone(), + }, + }, + policy, + &lock_file, + )?; + if !checkout.status.success() { + return Err(format!( + "sandboxed worktree checkout failed: {}", + String::from_utf8_lossy(&checkout.stderr) + )); + } + let initial = checked(git(policy, &tree, &["rev-parse", "HEAD"]))?; + let first = worker::run(binary, &tree, task, &task.prompt, policy, &lock_file, None)?; + record.worker = Some(first.result.clone()); + record.session_id = first.session.clone(); + let failures = acceptance(binary, &tree, &root, commands, policy, &lock_file)?; + if let Some(error) = first.failure() { + return Err(format!("{error}\nAcceptance checks:\n{failures}")); + } + if !failures.is_empty() { + let repair = worker::run( + binary, + &tree, + task, + &format!("External acceptance checks failed. Repair once:\n{failures}"), + policy, + &lock_file, + first.session.as_deref(), + )?; + record.worker = Some(repair.result.clone()); + record.session_id = repair.session.clone(); + let failures = acceptance(binary, &tree, &root, commands, policy, &lock_file)?; + if let Some(error) = repair.failure() { + return Err(format!("{error}\nAcceptance checks:\n{failures}")); + } + if !failures.is_empty() { + record.detail = failures; + return Ok(Outcome::Red); + } + } + let head = checked(git(policy, &tree, &["rev-parse", "HEAD"]))?; + let dirty = dirty_worktree(binary, &tree, &root, policy, &lock_file)?; + Ok(if head == initial && !dirty { + Outcome::NothingToDo + } else { + Outcome::Done + }) + })(); + match result { + Ok(outcome) => record.outcome = outcome, + Err(e) => record.detail = e, + } + save_receipt(&receipt, &record)?; + Ok(record) +} + +fn save_receipt(path: &Path, record: &Record) -> Result<()> { + let nonce = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_nanos(); + let temporary = path.with_extension(format!("tmp-{}-{nonce}", std::process::id())); + let result = (|| -> Result<()> { + let mut file = fs::OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .open(&temporary) + .map_err(|e| e.to_string())?; + file.write_all(&serde_json::to_vec_pretty(record).map_err(|e| e.to_string())?) + .map_err(|e| e.to_string())?; + file.sync_all().map_err(|e| e.to_string())?; + // Atomic publication with create-only semantics: an existing receipt + // is never overwritten, even if one appears while the task runs. + fs::hard_link(&temporary, path).map_err(|e| e.to_string())?; + fs::remove_file(&temporary).map_err(|e| e.to_string())?; + fs::File::open(path.parent().ok_or("receipt has no parent")?) + .and_then(|parent| parent.sync_all()) + .map_err(|e| e.to_string()) + })(); + if result.is_err() { + let _ = fs::remove_file(temporary); + } + result +} diff --git a/oxa/oxa-work/src/worker.rs b/oxa/oxa-work/src/worker.rs new file mode 100644 index 000000000..cb802ac31 --- /dev/null +++ b/oxa/oxa-work/src/worker.rs @@ -0,0 +1,188 @@ +//! Consume the child's headless contract without retaining its event stream. +use crate::{Result, RunPolicy, Task}; +use serde::{Deserialize, Serialize}; +use std::fs::File; +use std::io::{BufRead, BufReader, Read}; +use std::path::Path; +use std::process::{Command, Stdio}; + +const LINE_CAP: usize = 64 * 1024; +const DIAGNOSTIC_CAP: usize = 8192; + +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(rename_all = "snake_case")] +pub enum WorkerOutcome { + Done, + NothingToDo, + Blocked, + Failed, + Interrupted, +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +pub struct WorkerResult { + pub outcome: WorkerOutcome, + pub exit_code: i32, + pub error_class: Option, +} + +impl WorkerResult { + pub(crate) fn accepted(&self) -> bool { + matches!( + (&self.outcome, self.exit_code), + (WorkerOutcome::Done, 0) | (WorkerOutcome::NothingToDo, 4) + ) + } +} + +pub(crate) struct Worker { + pub result: WorkerResult, + pub session: Option, + pub diagnostic: String, +} + +impl Worker { + pub fn failure(&self) -> Option { + (!self.result.accepted()).then(|| { + format!( + "worker {:?} (exit {}, {}): {}", + self.result.outcome, + self.result.exit_code, + self.result.error_class.as_deref().unwrap_or("no error class"), + self.diagnostic.trim() + ) + }) + } +} + +pub(crate) fn run( + binary: &Path, + root: &Path, + task: &Task, + prompt: &str, + policy: &RunPolicy, + lock: &File, + session: Option<&str>, +) -> Result { + let mut command = Command::new(binary); + crate::isolate_git_environment(&mut command); + command + .env("PATH", &policy.host_path) + .env_remove("OXA_TRUST_PROJECT") + .current_dir(root) + .args(["-na", "--mode=json", "--model", &task.model]); + if policy.offline { + command.arg("--offline"); + } + if let Some(id) = session { + command.arg(format!("--continue={id}")); + } + let mut child = command + .args(["--", prompt]) + .stdin(lock.try_clone().map_err(|e| e.to_string())?) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .map_err(|e| format!("start worker: {e}"))?; + let stdout = child.stdout.take().ok_or("worker stdout missing")?; + let stderr = child.stderr.take().ok_or("worker stderr missing")?; + std::thread::scope(|scope| { + let header = scope.spawn(|| read_session(stdout)); + let terminal = scope.spawn(|| read_result(stderr)); + let status = child.wait().map_err(|e| format!("wait for worker: {e}"))?; + let session = header.join().map_err(|_| "worker header reader failed")??; + let (result, diagnostic) = terminal.join().map_err(|_| "worker result reader failed")??; + if status.code() != Some(result.exit_code) { + return Err("worker exit code disagrees with its oxa_result".into()); + } + if result.accepted() && session.is_none() { + return Err("successful worker did not report a session id".into()); + } + Ok(Worker { + result, + session, + diagnostic, + }) + }) +} + +fn read_session(pipe: impl Read) -> Result> { + let mut reader = BufReader::new(pipe); + let session = line(&mut reader)?.and_then(|line| { + let value: serde_json::Value = serde_json::from_slice(&line).ok()?; + (value["type"] == "session") + .then(|| value["id"].as_str().map(str::to_owned)) + .flatten() + .filter(|id| { + !id.is_empty() + && id.len() <= 128 + && id + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b"-_".contains(&b)) + }) + }); + std::io::copy(&mut reader, &mut std::io::sink()).map_err(|e| e.to_string())?; + Ok(session) +} + +fn read_result(pipe: impl Read) -> Result<(WorkerResult, String)> { + let mut reader = BufReader::new(pipe); + let mut result = None; + let mut duplicate = false; + let mut diagnostic = Vec::new(); + while let Some(bytes) = line(&mut reader)? { + let value = serde_json::from_slice::(&bytes).ok(); + if let Some(value) = value.filter(|v| v["type"] == "oxa_result") { + let parsed = serde_json::from_value(value).map_err(|e| format!("worker result: {e}"))?; + duplicate |= result.replace(parsed).is_some(); + } else { + keep_tail(&mut diagnostic, &bytes, DIAGNOSTIC_CAP); + } + } + if duplicate { + return Err("worker reported more than one oxa_result".into()); + } + let diagnostic = String::from_utf8_lossy(&diagnostic).into_owned(); + Ok(( + result.ok_or_else(|| format!("worker did not report oxa_result: {diagnostic}"))?, + diagnostic, + )) +} + +// Discard an oversized record while still draining the pipe. Event/progress size +// cannot increase the runner's memory use or block a child writing to either pipe. +fn line(reader: &mut impl BufRead) -> Result>> { + let mut line = Vec::new(); + let mut oversized = false; + let mut read = false; + loop { + let bytes = reader.fill_buf().map_err(|e| e.to_string())?; + if bytes.is_empty() { + return Ok(read.then_some(line)); + } + read = true; + let end = bytes.iter().position(|b| *b == b'\n'); + let count = end.map_or(bytes.len(), |i| i + 1); + if !oversized && line.len() + count <= LINE_CAP { + line.extend_from_slice(&bytes[..count]); + } else { + line.clear(); + oversized = true; + } + reader.consume(count); + if end.is_some() { + return Ok(Some(line)); + } + } +} + +pub(crate) fn keep_tail(tail: &mut Vec, bytes: &[u8], cap: usize) { + if bytes.len() >= cap { + tail.clear(); + tail.extend_from_slice(&bytes[bytes.len() - cap..]); + } else { + let discard = (tail.len() + bytes.len()).saturating_sub(cap); + tail.drain(..discard); + tail.extend_from_slice(bytes); + } +}