From d0c9ed9fe4d605c5b21fb0a29ecc9f3e5303f3ef Mon Sep 17 00:00:00 2001 From: Oscar Nordstrom <13300531+n0rpan@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:00:52 +0100 Subject: [PATCH 01/13] work: start a new task branch at its published head A task for an already pushed branch (for example a pull request's head) started a fresh worktree at the captured base, because the local branch did not exist. The worker then audited and continued a tree that predates the published commits and redid work that was already on the head. Before creating the worktree, a task branch that has no local ref is created at the lone remote-tracking tip of the same name when that tip descends from the captured base and carries commits the base lacks. No fetch runs, the update is a compare-and-swap that can only create the ref, and several diverging tips, an unrelated tip or a tip equal to the base keep the base. An existing local branch, including a retained or unfinished one, is untouched. Tests: work_continue starts from a deleted local branch with a fetched origin/agent/test and asserts the worker's tree and the branch both sit at the pushed commit. Fixes #1052 --- oxa/CHANGELOG.md | 4 ++ oxa/docs/work.md | 7 ++- oxa/oxa-cli/tests/work_continue.rs | 20 +++++++++ oxa/oxa-work/src/tree.rs | 71 ++++++++++++++++++++++++++++++ 4 files changed, 101 insertions(+), 1 deletion(-) diff --git a/oxa/CHANGELOG.md b/oxa/CHANGELOG.md index a5ad2e566..3f1f2d4d1 100644 --- a/oxa/CHANGELOG.md +++ b/oxa/CHANGELOG.md @@ -2,6 +2,10 @@ ## [Unreleased] +### Fixed + +- `oxa work` starts a new task branch at its published head (`origin/`) when that tip descends from the captured base, instead of always at the base. A task for an already pushed pull-request branch now audits and continues that head rather than redoing work from a tree that predates it; several diverging tips or an unrelated one keep the base. See [work.md](docs/work.md). + ### Changed - Provider preconnect (#881): qualified as not implementable through the existing gateway pool. The pinned reqwest 0.12 transport has no preconnect or pool-insertion API, so warming the selected provider would need a real authenticated request after the first frame; no warm-up was added. The limitation and the owner's options are in [provider-preconnect.md](docs/design/provider-preconnect.md). diff --git a/oxa/docs/work.md b/oxa/docs/work.md index 1d6f6791c..18d64f4af 100644 --- a/oxa/docs/work.md +++ b/oxa/docs/work.md @@ -120,7 +120,12 @@ Finished successful work is returned without another worker or check run; add change requires a new ID. Unsupported or corrupt checkpoints are preserved and refused. A matching linked worktree is reused; the source checkout is never used as the task worktree. An existing branch checked -out elsewhere is blocked. Dirty retained work is preserved and saved before +out elsewhere is blocked. A new task branch that is already published starts at +its pushed head instead of the base: the branch is created at the lone +remote-tracking tip of the same name when that tip descends from the captured +base (never for several diverging tips or an unrelated one), so reviewing or +continuing a pull request works from its head. Fetch first; no fetch is run here. +Dirty retained work is preserved and saved before retrying. A clean retained branch gets an ordinary sandboxed merge of the captured base; no reset, stash, force checkout or automatic fetch runs. diff --git a/oxa/oxa-cli/tests/work_continue.rs b/oxa/oxa-cli/tests/work_continue.rs index dc7492baf..a59c08165 100644 --- a/oxa/oxa-cli/tests/work_continue.rs +++ b/oxa/oxa-cli/tests/work_continue.rs @@ -74,6 +74,26 @@ fn existing_branch_fast_forwards_to_base_before_agent() { &["merge-base", "--is-ancestor", "main", "agent/test"], ); } +#[test] +fn fresh_worktree_starts_at_the_published_task_branch_head() { + let env = TestEnv::new(); + setup(&env, "[]"); + git(&env, &project(&env), &["checkout", "-b", "agent/test"]); + commit_file(&env, "pr.txt", "from the pull request\n"); + git(&env, &project(&env), &["push", "origin", "agent/test"]); + git(&env, &project(&env), &["checkout", "main"]); + git(&env, &project(&env), &["branch", "-D", "agent/test"]); + git(&env, &project(&env), &["fetch", "origin"]); + let pushed = git(&env, &project(&env), &["rev-parse", "origin/agent/test"]); + let record = run(&env, vec![ScriptTurn::text("nothing")]); + assert_eq!(record["outcome"], "nothing_to_do", "{record}"); + assert_eq!( + std::fs::read_to_string(tree(&record).join("pr.txt")).unwrap(), + "from the pull request\n" + ); + assert_eq!(git(&env, &project(&env), &["rev-parse", "agent/test"]), pushed); +} + #[test] fn divergent_branch_gets_normal_merge_without_losing_task_commit() { let env = TestEnv::new(); diff --git a/oxa/oxa-work/src/tree.rs b/oxa/oxa-work/src/tree.rs index fb135b4ae..a44d23511 100644 --- a/oxa/oxa-work/src/tree.rs +++ b/oxa/oxa-work/src/tree.rs @@ -80,6 +80,74 @@ pub(crate) fn validate(policy: &RunPolicy, repo: &Path, tree: &Path, task: &Task Ok(()) } +/// A published task branch may have no local ref at all: the worktree would +/// then start at the base, so a worker auditing a pull request's head would +/// redo work from a tree that predates it. Only a lone remote-tracking tip +/// that descends from the captured base (and carries commits the base lacks) is +/// adopted; no fetch runs, and an unrelated or diverging tip is never preferred +/// over the base. +fn adopt_published_head(policy: &RunPolicy, repo: &Path, branch: &str, base: &str) -> Result<()> { + let base_sha = checked(git( + policy, + repo, + &["rev-parse", "--verify", &format!("{base}^{{commit}}")], + ))?; + let pattern = format!("refs/remotes/*/{branch}"); + let tracking = checked(git( + policy, + repo, + &["for-each-ref", "--format=%(refname)", &pattern], + ))?; + let mut heads = Vec::new(); + for name in tracking.lines().filter(|name| !name.ends_with("/HEAD")) { + // A stale or dangling tracking ref is ignored, not turned into a block. + let read = output(git( + policy, + repo, + &["rev-parse", "--verify", &format!("{name}^{{commit}}")], + ))?; + if !read.status.success() { + continue; + } + let tip = String::from_utf8_lossy(&read.stdout).trim().to_owned(); + if tip != base_sha + && output(git( + policy, + repo, + &["merge-base", "--is-ancestor", &base_sha, &tip], + ))? + .status + .code() + == Some(0) + { + heads.push(tip); + } + } + heads.sort(); + heads.dedup(); + let [tip] = heads.as_slice() else { + return Ok(()); + }; + // The branch does not exist yet, so only a zero old value can match. + let created = "0".repeat(40); + let updated = output(git( + policy, + repo, + &[ + "update-ref", + "-m", + "oxa work: start the task branch at its published head", + &format!("refs/heads/{branch}"), + tip, + &created, + ], + ))?; + if !updated.status.success() { + return Err(String::from_utf8_lossy(&updated.stderr).into()); + } + Ok(()) +} + pub(crate) fn prepare( repo: &Path, tree: &Path, @@ -98,6 +166,9 @@ pub(crate) fn prepare( Some(1) => true, _ => return Err(String::from_utf8_lossy(&exists.stderr).into()), }; + if create { + adopt_published_head(policy, repo, &task.branch, base)?; + } let tree_arg = tree.to_str().ok_or("non-UTF8 worktree path")?; let mut args = vec![ "-c", From 079bd613c8fe5913549ee75812ed49253e752555 Mon Sep 17 00:00:00 2001 From: Oscar Nordstrom <13300531+n0rpan@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:19:03 +0100 Subject: [PATCH 02/13] work: attach a fresh worktree to an adopted published branch Adopting the published head created refs/heads/ before the worktree existed, but the sandboxed checkout still ran `git checkout -b HEAD` for a task without a local branch and failed with "a branch named '' already exists", blocking every task whose branch had just been adopted. The adoption now reports whether it created the ref. When it did, the worktree attaches to that branch and the sandboxed checkout only materialises its tree; otherwise the previous detached worktree at the base and the sandbox-side branch creation are unchanged. Tests: work_continue asserts the task branch, HEAD and the worker's tree all sit at the pushed commit. --- oxa/oxa-cli/tests/work_continue.rs | 5 +++++ oxa/oxa-work/src/tree.rs | 22 ++++++++++++---------- 2 files changed, 17 insertions(+), 10 deletions(-) diff --git a/oxa/oxa-cli/tests/work_continue.rs b/oxa/oxa-cli/tests/work_continue.rs index a59c08165..cf4e5cb24 100644 --- a/oxa/oxa-cli/tests/work_continue.rs +++ b/oxa/oxa-cli/tests/work_continue.rs @@ -92,6 +92,11 @@ fn fresh_worktree_starts_at_the_published_task_branch_head() { "from the pull request\n" ); assert_eq!(git(&env, &project(&env), &["rev-parse", "agent/test"]), pushed); + assert_eq!( + git(&env, &project(&env), &["symbolic-ref", "--quiet", "HEAD"]), + "refs/heads/agent/test" + ); + assert_eq!(git(&env, tree(&record), &["rev-parse", "HEAD"]), pushed); } #[test] diff --git a/oxa/oxa-work/src/tree.rs b/oxa/oxa-work/src/tree.rs index a44d23511..7b9e9e942 100644 --- a/oxa/oxa-work/src/tree.rs +++ b/oxa/oxa-work/src/tree.rs @@ -85,8 +85,9 @@ pub(crate) fn validate(policy: &RunPolicy, repo: &Path, tree: &Path, task: &Task /// redo work from a tree that predates it. Only a lone remote-tracking tip /// that descends from the captured base (and carries commits the base lacks) is /// adopted; no fetch runs, and an unrelated or diverging tip is never preferred -/// over the base. -fn adopt_published_head(policy: &RunPolicy, repo: &Path, branch: &str, base: &str) -> Result<()> { +/// over the base. Returns whether the local branch was created, so the caller +/// attaches the worktree to it instead of creating the ref a second time. +fn adopt_published_head(policy: &RunPolicy, repo: &Path, branch: &str, base: &str) -> Result { let base_sha = checked(git( policy, repo, @@ -126,7 +127,7 @@ fn adopt_published_head(policy: &RunPolicy, repo: &Path, branch: &str, base: &st heads.sort(); heads.dedup(); let [tip] = heads.as_slice() else { - return Ok(()); + return Ok(false); }; // The branch does not exist yet, so only a zero old value can match. let created = "0".repeat(40); @@ -145,7 +146,7 @@ fn adopt_published_head(policy: &RunPolicy, repo: &Path, branch: &str, base: &st if !updated.status.success() { return Err(String::from_utf8_lossy(&updated.stderr).into()); } - Ok(()) + Ok(true) } pub(crate) fn prepare( @@ -166,9 +167,7 @@ pub(crate) fn prepare( Some(1) => true, _ => return Err(String::from_utf8_lossy(&exists.stderr).into()), }; - if create { - adopt_published_head(policy, repo, &task.branch, base)?; - } + let adopted = create && adopt_published_head(policy, repo, &task.branch, base)?; let tree_arg = tree.to_str().ok_or("non-UTF8 worktree path")?; let mut args = vec![ "-c", @@ -177,11 +176,14 @@ pub(crate) fn prepare( "add", "--no-checkout", ]; - if create { + // An adopted branch already exists at its published tip, so the + // worktree attaches to it; otherwise it starts detached at the base and + // the sandboxed checkout creates the branch. + if create && !adopted { args.push("--detach"); } args.push(tree_arg); - args.push(if create { base } else { &task.branch }); + args.push(if create && !adopted { base } else { &task.branch }); // Only metadata on the host. Git still refuses a branch checked out // elsewhere; no task-branch update or checkout callback runs here. checked(git(policy, repo, &args))?; @@ -192,7 +194,7 @@ pub(crate) fn prepare( source: repo.to_path_buf(), operation: SupervisorOperation::Checkout { branch: task.branch.clone(), - create, + create: create && !adopted, }, }, policy, From 584c04164a31c03558bfba52c7ee905eb616a96c Mon Sep 17 00:00:00 2001 From: Oscar Nordstrom <13300531+n0rpan@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:27:10 +0100 Subject: [PATCH 03/13] work: start the task worktree at the published head, not the source checkout The published-head test asserted `symbolic-ref HEAD` in the source checkout, which `oxa work` deliberately never moves: it stays on the captured base while the task branch is created for the worktree. The assertion therefore checked the wrong repository and failed. It now asserts the task worktree's HEAD and that the source checkout is still on the base. Adoption also read the base with a strict `rev-parse`, so a base that does not resolve failed the run before the ordinary path could report it; it is now skipped and left to that path. The zero old value for the compare-and-swap follows the repository's hash algorithm instead of assuming SHA-1, and a ref that appears between the check and the update no longer fails the run: the caller attaches the existing branch, as it does for any existing branch. Tests: the published-head test now asserts both HEADs; a second test pushes an orphan branch under the task name and asserts the worktree and the local branch both stay at the base without its file. --- oxa/oxa-cli/tests/work_continue.rs | 30 ++++++++++++++++++++++++++++-- oxa/oxa-work/src/tree.rs | 25 ++++++++++++++++--------- 2 files changed, 44 insertions(+), 11 deletions(-) diff --git a/oxa/oxa-cli/tests/work_continue.rs b/oxa/oxa-cli/tests/work_continue.rs index cf4e5cb24..6cf1cd157 100644 --- a/oxa/oxa-cli/tests/work_continue.rs +++ b/oxa/oxa-cli/tests/work_continue.rs @@ -74,6 +74,7 @@ fn existing_branch_fast_forwards_to_base_before_agent() { &["merge-base", "--is-ancestor", "main", "agent/test"], ); } + #[test] fn fresh_worktree_starts_at_the_published_task_branch_head() { let env = TestEnv::new(); @@ -92,11 +93,36 @@ fn fresh_worktree_starts_at_the_published_task_branch_head() { "from the pull request\n" ); assert_eq!(git(&env, &project(&env), &["rev-parse", "agent/test"]), pushed); + assert_eq!(git(&env, tree(&record), &["rev-parse", "HEAD"]), pushed); assert_eq!( - git(&env, &project(&env), &["symbolic-ref", "--quiet", "HEAD"]), + git(&env, tree(&record), &["symbolic-ref", "--quiet", "HEAD"]), "refs/heads/agent/test" ); - assert_eq!(git(&env, tree(&record), &["rev-parse", "HEAD"]), pushed); + // The source checkout stays where it was; only the task worktree moves. + assert_eq!( + git(&env, &project(&env), &["symbolic-ref", "--quiet", "HEAD"]), + "refs/heads/main" + ); +} + +#[test] +fn unrelated_published_tip_keeps_the_base() { + let env = TestEnv::new(); + setup(&env, "[]"); + // An orphan commit shares no history with the captured base, so it is not + // proof that the pushed branch continues this task. + git(&env, &project(&env), &["checkout", "--orphan", "agent/test"]); + commit_file(&env, "unrelated.txt", "from an unrelated history\n"); + git(&env, &project(&env), &["push", "origin", "agent/test"]); + git(&env, &project(&env), &["checkout", "main"]); + git(&env, &project(&env), &["branch", "-D", "agent/test"]); + git(&env, &project(&env), &["fetch", "origin"]); + let base = git(&env, &project(&env), &["rev-parse", "main"]); + let record = run(&env, vec![ScriptTurn::text("nothing")]); + assert_eq!(record["outcome"], "nothing_to_do", "{record}"); + assert_eq!(git(&env, tree(&record), &["rev-parse", "HEAD"]), base); + assert!(!tree(&record).join("unrelated.txt").exists()); + assert_eq!(git(&env, &project(&env), &["rev-parse", "agent/test"]), base); } #[test] diff --git a/oxa/oxa-work/src/tree.rs b/oxa/oxa-work/src/tree.rs index 7b9e9e942..045a3f205 100644 --- a/oxa/oxa-work/src/tree.rs +++ b/oxa/oxa-work/src/tree.rs @@ -88,11 +88,15 @@ pub(crate) fn validate(policy: &RunPolicy, repo: &Path, tree: &Path, task: &Task /// over the base. Returns whether the local branch was created, so the caller /// attaches the worktree to it instead of creating the ref a second time. fn adopt_published_head(policy: &RunPolicy, repo: &Path, branch: &str, base: &str) -> Result { - let base_sha = checked(git( + let base_sha = match output(git( policy, repo, - &["rev-parse", "--verify", &format!("{base}^{{commit}}")], - ))?; + &["rev-parse", "--verify", "--quiet", &format!("{base}^{{commit}}")], + ))? { + // An unresolvable base is left to the ordinary path, which reports it. + out if !out.status.success() => return Ok(false), + out => String::from_utf8_lossy(&out.stdout).trim().to_owned(), + }; let pattern = format!("refs/remotes/*/{branch}"); let tracking = checked(git( policy, @@ -129,8 +133,12 @@ fn adopt_published_head(policy: &RunPolicy, repo: &Path, branch: &str, base: &st let [tip] = heads.as_slice() else { return Ok(false); }; - // The branch does not exist yet, so only a zero old value can match. - let created = "0".repeat(40); + // The branch does not exist yet, so only a zero old value can match; the + // zero width follows the repository's hash algorithm. + let created = checked(git(policy, repo, &["hash-object", "--stdin"]))? + .chars() + .map(|_| '0') + .collect::(); let updated = output(git( policy, repo, @@ -143,10 +151,9 @@ fn adopt_published_head(policy: &RunPolicy, repo: &Path, branch: &str, base: &st &created, ], ))?; - if !updated.status.success() { - return Err(String::from_utf8_lossy(&updated.stderr).into()); - } - Ok(true) + // A ref that appeared in the meantime is not an error: the caller then + // falls back to the existing branch, which is what it would have used. + Ok(updated.status.success()) } pub(crate) fn prepare( From d066af7fafe1176c033cd2915c7509c662f8f09b Mon Sep 17 00:00:00 2001 From: oxa-agent Date: Tue, 17 Nov 2026 22:18:37 +0100 Subject: [PATCH 04/13] test(work): expose published-head hook escape and ambiguous tips (#1052) --- oxa/oxa-cli/tests/work_continue.rs | 80 +++++++++++++++++++++++++++--- 1 file changed, 72 insertions(+), 8 deletions(-) diff --git a/oxa/oxa-cli/tests/work_continue.rs b/oxa/oxa-cli/tests/work_continue.rs index 6cf1cd157..9c7aa060f 100644 --- a/oxa/oxa-cli/tests/work_continue.rs +++ b/oxa/oxa-cli/tests/work_continue.rs @@ -75,17 +75,21 @@ fn existing_branch_fast_forwards_to_base_before_agent() { ); } +fn published_task(env: &TestEnv) -> String { + setup(env, "[]"); + git(env, &project(env), &["checkout", "-b", "agent/test"]); + commit_file(env, "pr.txt", "from the pull request\n"); + git(env, &project(env), &["push", "origin", "agent/test"]); + git(env, &project(env), &["checkout", "main"]); + git(env, &project(env), &["branch", "-D", "agent/test"]); + git(env, &project(env), &["fetch", "origin"]); + git(env, &project(env), &["rev-parse", "origin/agent/test"]) +} + #[test] fn fresh_worktree_starts_at_the_published_task_branch_head() { let env = TestEnv::new(); - setup(&env, "[]"); - git(&env, &project(&env), &["checkout", "-b", "agent/test"]); - commit_file(&env, "pr.txt", "from the pull request\n"); - git(&env, &project(&env), &["push", "origin", "agent/test"]); - git(&env, &project(&env), &["checkout", "main"]); - git(&env, &project(&env), &["branch", "-D", "agent/test"]); - git(&env, &project(&env), &["fetch", "origin"]); - let pushed = git(&env, &project(&env), &["rev-parse", "origin/agent/test"]); + let pushed = published_task(&env); let record = run(&env, vec![ScriptTurn::text("nothing")]); assert_eq!(record["outcome"], "nothing_to_do", "{record}"); assert_eq!( @@ -105,6 +109,66 @@ fn fresh_worktree_starts_at_the_published_task_branch_head() { ); } +#[test] +fn published_head_reference_hooks_run_only_in_the_task_sandbox() { + use std::os::unix::fs::PermissionsExt; + let env = TestEnv::new(); + let pushed = published_task(&env); + let hook = env.write( + "work/project/.git/hooks/reference-transaction", + "#!/bin/sh\ncat >/dev/null\nprintf escaped > \"$HOME/published-head-host-hook\" 2>/dev/null || true\nprintf ran > published-head-hook-ran\n", + ); + std::fs::set_permissions(hook, std::fs::Permissions::from_mode(0o755)).unwrap(); + let record = run(&env, vec![ScriptTurn::text("nothing")]); + assert!(!env.home().join("published-head-host-hook").exists(), "{record}"); + assert!( + !project(&env).join("published-head-hook-ran").exists(), + "{record}" + ); + assert!(tree(&record).join("published-head-hook-ran").exists(), "{record}"); + assert_eq!(record["outcome"], "done", "{record}"); + git( + &env, + tree(&record), + &["merge-base", "--is-ancestor", &pushed, "HEAD"], + ); +} + +#[test] +fn a_divergent_matching_remote_tip_prevents_published_head_adoption() { + let env = TestEnv::new(); + published_task(&env); + let base = git(&env, &project(&env), &["rev-parse", "main"]); + git(&env, &project(&env), &["checkout", "--orphan", "other"]); + commit_file(&env, "unrelated.txt", "another published history\n"); + let other = git(&env, &project(&env), &["rev-parse", "HEAD"]); + git(&env, &project(&env), &["checkout", "main"]); + git(&env, &project(&env), &["remote", "add", "other", "../remote.git"]); + git( + &env, + &project(&env), + &["update-ref", "refs/remotes/other/agent/test", &other], + ); + let record = run(&env, vec![ScriptTurn::text("nothing")]); + assert_eq!(record["outcome"], "nothing_to_do", "{record}"); + assert_eq!(git(&env, tree(&record), &["rev-parse", "HEAD"]), base); + assert!(!tree(&record).join("pr.txt").exists()); +} + +#[test] +fn identical_matching_remote_tips_keep_the_published_head_eligible() { + let env = TestEnv::new(); + let pushed = published_task(&env); + git( + &env, + &project(&env), + &["update-ref", "refs/remotes/mirror/agent/test", &pushed], + ); + let record = run(&env, vec![ScriptTurn::text("nothing")]); + assert_eq!(record["outcome"], "nothing_to_do", "{record}"); + assert_eq!(git(&env, tree(&record), &["rev-parse", "HEAD"]), pushed); +} + #[test] fn unrelated_published_tip_keeps_the_base() { let env = TestEnv::new(); From ca01b0031a6b6ee760f1ac84c3d042ca8326a363 Mon Sep 17 00:00:00 2001 From: oxa-agent Date: Tue, 17 Nov 2026 22:40:40 +0100 Subject: [PATCH 05/13] fix(work): create published task branches through the sandbox (#1052) --- oxa/oxa-cli/tests/work_continue.rs | 24 +++++++++ oxa/oxa-work/src/tree.rs | 78 +++++++++++++----------------- 2 files changed, 57 insertions(+), 45 deletions(-) diff --git a/oxa/oxa-cli/tests/work_continue.rs b/oxa/oxa-cli/tests/work_continue.rs index 9c7aa060f..0ea538fa7 100644 --- a/oxa/oxa-cli/tests/work_continue.rs +++ b/oxa/oxa-cli/tests/work_continue.rs @@ -169,6 +169,30 @@ fn identical_matching_remote_tips_keep_the_published_head_eligible() { assert_eq!(git(&env, tree(&record), &["rev-parse", "HEAD"]), pushed); } +#[test] +fn published_branch_creation_keeps_required_reference_hook_policy() { + use std::os::unix::fs::PermissionsExt; + let env = TestEnv::new(); + published_task(&env); + let hook = env.write("work/project/.git/hooks/reference-transaction", "#!/bin/sh\nwhile read old new reference; do if test \"$reference\" = refs/heads/agent/test; then echo required-published-reference-policy >&2; exit 1; fi; done\n"); + std::fs::set_permissions(hook, std::fs::Permissions::from_mode(0o755)).unwrap(); + let (record, requests) = run_observed(&env, vec![], &["work", "../tasks.json"], None); + assert_eq!(record["outcome"], "blocked", "{record}"); + assert!(requests.is_empty()); + assert!(record["detail"] + .as_str() + .unwrap() + .contains("required-published-reference-policy")); + assert_eq!( + git( + &env, + &project(&env), + &["for-each-ref", "--format=%(refname)", "refs/heads/agent/test"] + ), + "" + ); +} + #[test] fn unrelated_published_tip_keeps_the_base() { let env = TestEnv::new(); diff --git a/oxa/oxa-work/src/tree.rs b/oxa/oxa-work/src/tree.rs index 045a3f205..477e15c57 100644 --- a/oxa/oxa-work/src/tree.rs +++ b/oxa/oxa-work/src/tree.rs @@ -85,16 +85,16 @@ pub(crate) fn validate(policy: &RunPolicy, repo: &Path, tree: &Path, task: &Task /// redo work from a tree that predates it. Only a lone remote-tracking tip /// that descends from the captured base (and carries commits the base lacks) is /// adopted; no fetch runs, and an unrelated or diverging tip is never preferred -/// over the base. Returns whether the local branch was created, so the caller -/// attaches the worktree to it instead of creating the ref a second time. -fn adopt_published_head(policy: &RunPolicy, repo: &Path, branch: &str, base: &str) -> Result { +/// over the base. Selection is read-only; the existing sandboxed checkout creates +/// the branch at this commit and retains its normal reference hook policy. +fn published_head(policy: &RunPolicy, repo: &Path, branch: &str, base: &str) -> Result> { let base_sha = match output(git( policy, repo, &["rev-parse", "--verify", "--quiet", &format!("{base}^{{commit}}")], ))? { // An unresolvable base is left to the ordinary path, which reports it. - out if !out.status.success() => return Ok(false), + out if !out.status.success() => return Ok(None), out => String::from_utf8_lossy(&out.stdout).trim().to_owned(), }; let pattern = format!("refs/remotes/*/{branch}"); @@ -115,45 +115,26 @@ fn adopt_published_head(policy: &RunPolicy, repo: &Path, branch: &str, base: &st continue; } let tip = String::from_utf8_lossy(&read.stdout).trim().to_owned(); - if tip != base_sha - && output(git( - policy, - repo, - &["merge-base", "--is-ancestor", &base_sha, &tip], - ))? - .status - .code() - == Some(0) - { - heads.push(tip); - } + heads.push(tip); } heads.sort(); heads.dedup(); let [tip] = heads.as_slice() else { - return Ok(false); + return Ok(None); }; - // The branch does not exist yet, so only a zero old value can match; the - // zero width follows the repository's hash algorithm. - let created = checked(git(policy, repo, &["hash-object", "--stdin"]))? - .chars() - .map(|_| '0') - .collect::(); - let updated = output(git( - policy, - repo, - &[ - "update-ref", - "-m", - "oxa work: start the task branch at its published head", - &format!("refs/heads/{branch}"), - tip, - &created, - ], - ))?; - // A ref that appeared in the meantime is not an error: the caller then - // falls back to the existing branch, which is what it would have used. - Ok(updated.status.success()) + if tip == &base_sha + || output(git( + policy, + repo, + &["merge-base", "--is-ancestor", &base_sha, tip], + ))? + .status + .code() + != Some(0) + { + return Ok(None); + } + Ok(Some(tip.clone())) } pub(crate) fn prepare( @@ -174,7 +155,11 @@ pub(crate) fn prepare( Some(1) => true, _ => return Err(String::from_utf8_lossy(&exists.stderr).into()), }; - let adopted = create && adopt_published_head(policy, repo, &task.branch, base)?; + let published = if create { + published_head(policy, repo, &task.branch, base)? + } else { + None + }; let tree_arg = tree.to_str().ok_or("non-UTF8 worktree path")?; let mut args = vec![ "-c", @@ -183,14 +168,17 @@ pub(crate) fn prepare( "add", "--no-checkout", ]; - // An adopted branch already exists at its published tip, so the - // worktree attaches to it; otherwise it starts detached at the base and - // the sandboxed checkout creates the branch. - if create && !adopted { + // A fresh branch is created only by the sandboxed checkout. If another + // writer creates it meanwhile, Git refuses instead of replacing its work. + if create { args.push("--detach"); } args.push(tree_arg); - args.push(if create && !adopted { base } else { &task.branch }); + args.push(if create { + published.as_deref().unwrap_or(base) + } else { + &task.branch + }); // Only metadata on the host. Git still refuses a branch checked out // elsewhere; no task-branch update or checkout callback runs here. checked(git(policy, repo, &args))?; @@ -201,7 +189,7 @@ pub(crate) fn prepare( source: repo.to_path_buf(), operation: SupervisorOperation::Checkout { branch: task.branch.clone(), - create: create && !adopted, + create, }, }, policy, From 60744954623c728c986d29c02cc909d206910a5a Mon Sep 17 00:00:00 2001 From: oxa-agent Date: Tue, 17 Nov 2026 23:35:09 +0100 Subject: [PATCH 06/13] Prove adopted checkout hooks cannot receive networked credentials (#1052) --- oxa/oxa-cli/tests/common/work.rs | 12 +++++++- oxa/oxa-cli/tests/work_continue.rs | 47 ++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+), 1 deletion(-) diff --git a/oxa/oxa-cli/tests/common/work.rs b/oxa/oxa-cli/tests/common/work.rs index 59d09defa..6d2c31ca4 100644 --- a/oxa/oxa-cli/tests/common/work.rs +++ b/oxa/oxa-cli/tests/common/work.rs @@ -53,6 +53,15 @@ pub fn run_observed( turns: Vec, args: &[&str], path: Option, +) -> (serde_json::Value, Vec) { + run_observed_with_env(env, turns, args, path, &[]) +} +pub fn run_observed_with_env( + env: &TestEnv, + turns: Vec, + args: &[&str], + path: Option, + extra: &[(&str, &str)], ) -> (serde_json::Value, Vec) { let server = FakeServer::start(turns, FakeOpts::default()).unwrap(); let mut command = Command::new(env!("CARGO_BIN_EXE_oxa")); @@ -60,7 +69,8 @@ pub fn run_observed( .args(args) .current_dir(env.work().join("project")) .env_clear() - .envs(env.envs(&server.url())); + .envs(env.envs(&server.url())) + .envs(extra.iter().copied()); if let Some(path) = path { command.env("PATH", path); } diff --git a/oxa/oxa-cli/tests/work_continue.rs b/oxa/oxa-cli/tests/work_continue.rs index 0ea538fa7..9cf48e341 100644 --- a/oxa/oxa-cli/tests/work_continue.rs +++ b/oxa/oxa-cli/tests/work_continue.rs @@ -134,6 +134,53 @@ fn published_head_reference_hooks_run_only_in_the_task_sandbox() { ); } +#[test] +fn published_checkout_hooks_have_neither_network_nor_github_credentials() { + use std::os::unix::fs::{DirBuilderExt, PermissionsExt}; + let env = TestEnv::new(); + published_task(&env); + git( + &env, + &project(&env), + &["checkout", "-b", "published", "origin/agent/test"], + ); + commit_file(&env, "checkout-policy.sh", "printf ran > adopted-hook-ran\nif test -n \"${GH_TOKEN-}\"; then printf exposed > adopted-hook-credentials; fi\nreadlink /proc/self/ns/net > adopted-hook-network\n"); + git(&env, &project(&env), &["push", "origin", "published:agent/test"]); + git(&env, &project(&env), &["checkout", "main"]); + git(&env, &project(&env), &["branch", "-D", "published"]); + git(&env, &project(&env), &["fetch", "origin"]); + let hook = env.write( + "work/project/.git/hooks/post-checkout", + "#!/bin/sh\nif test -f checkout-policy.sh; then sh checkout-policy.sh; fi\n", + ); + std::fs::set_permissions(hook, std::fs::Permissions::from_mode(0o755)).unwrap(); + let tools = env.tmp().join("trusted-tools"); + std::fs::DirBuilder::new().mode(0o700).create(&tools).unwrap(); + let gh = env.write("tmp/trusted-tools/gh", "#!/bin/sh\ntest \"$*\" = 'auth token --hostname github.com' || exit 9\nprintf '%s\\n' SYNTH_CHECKOUT_CREDENTIAL\n"); + std::fs::set_permissions(gh, std::fs::Permissions::from_mode(0o755)).unwrap(); + let path = format!("{}:{}", tools.display(), std::env::var("PATH").unwrap()); + // Only this fixture gh is reachable first, under a throwaway HOME. No real login is read. + let (record, _) = work::run_observed_with_env( + &env, + vec![ScriptTurn::text("nothing")], + &["work", "../tasks.json"], + Some(path), + &[("OXA_TEST_ISOLATION", "0")], + ); + assert_eq!(record["outcome"], "done", "{record}"); + assert!(tree(&record).join("adopted-hook-ran").exists(), "{record}"); + assert!( + !tree(&record).join("adopted-hook-credentials").exists(), + "checkout exposed credentials: {record}" + ); + let hook_net = std::fs::read_to_string(tree(&record).join("adopted-hook-network")).unwrap(); + assert_ne!( + hook_net.trim(), + std::fs::read_link("/proc/self/ns/net").unwrap().to_str().unwrap(), + "checkout retained host networking" + ); +} + #[test] fn a_divergent_matching_remote_tip_prevents_published_head_adoption() { let env = TestEnv::new(); From 91fb75354001d646e830c4a2b464261573720e65 Mon Sep 17 00:00:00 2001 From: oxa-agent Date: Tue, 17 Nov 2026 23:49:17 +0100 Subject: [PATCH 07/13] Apply the adopted checkout execution policy (#1052) --- oxa/oxa-cli/src/work_checks.rs | 25 ++++++++++++++++----- oxa/oxa-cli/tests/work_continue.rs | 36 ++++++++++++++++++++++++------ oxa/oxa-work/src/lib.rs | 28 ++++++++++++++++++----- oxa/oxa-work/src/tree.rs | 1 + 4 files changed, 72 insertions(+), 18 deletions(-) diff --git a/oxa/oxa-cli/src/work_checks.rs b/oxa/oxa-cli/src/work_checks.rs index a86a7f9e0..2d09877ec 100644 --- a/oxa/oxa-cli/src/work_checks.rs +++ b/oxa/oxa-cli/src/work_checks.rs @@ -62,20 +62,35 @@ pub(crate) fn run( let commands = match request.operation { SupervisorOperation::Inspect => return inspect(&b, &root), SupervisorOperation::InspectCommitted { index } => return inspect_committed(&b, &root, &index), - SupervisorOperation::Checkout { branch, create } => { - let sandbox = crate::netguard::with_net(Arc::new(b), &settings); + SupervisorOperation::Checkout { + branch, + create, + adopted, + } => { + // Adopted content is materialized without ambient GitHub authority. + // The ordinary checkout path retains its existing hook policy. + let sandbox: Arc = if adopted { + Arc::new(b) + } else { + crate::netguard::with_net(Arc::new(b), &settings) + }; + let git = if adopted { + "git --no-replace-objects -c core.hooksPath=/dev/null -c credential.helper=" + } else { + "git --no-replace-objects" + }; let spec = ExecSpec { command: if create { format!( - "git --no-replace-objects checkout HEAD -- . && git --no-replace-objects checkout -b {} HEAD", + "{git} checkout HEAD -- . && {git} checkout -b {} HEAD", sh_quote(&branch) ) } else { - "git --no-replace-objects checkout HEAD -- .".into() + format!("{git} checkout HEAD -- .") }, cwd: root, writable: true, - net: sandbox.network(), + net: !adopted && sandbox.network(), timeout_s: Some(600), env: git_environment(), }; diff --git a/oxa/oxa-cli/tests/work_continue.rs b/oxa/oxa-cli/tests/work_continue.rs index 9cf48e341..0e41f8d1c 100644 --- a/oxa/oxa-cli/tests/work_continue.rs +++ b/oxa/oxa-cli/tests/work_continue.rs @@ -110,10 +110,11 @@ fn fresh_worktree_starts_at_the_published_task_branch_head() { } #[test] -fn published_head_reference_hooks_run_only_in_the_task_sandbox() { +fn ordinary_fresh_branch_reference_hooks_run_only_in_the_task_sandbox() { use std::os::unix::fs::PermissionsExt; let env = TestEnv::new(); - let pushed = published_task(&env); + setup(&env, "[]"); + let pushed = git(&env, &project(&env), &["rev-parse", "main"]); let hook = env.write( "work/project/.git/hooks/reference-transaction", "#!/bin/sh\ncat >/dev/null\nprintf escaped > \"$HOME/published-head-host-hook\" 2>/dev/null || true\nprintf ran > published-head-hook-ran\n", @@ -145,10 +146,20 @@ fn published_checkout_hooks_have_neither_network_nor_github_credentials() { &["checkout", "-b", "published", "origin/agent/test"], ); commit_file(&env, "checkout-policy.sh", "printf ran > adopted-hook-ran\nif test -n \"${GH_TOKEN-}\"; then printf exposed > adopted-hook-credentials; fi\nreadlink /proc/self/ns/net > adopted-hook-network\n"); + env.write("work/project/.gitattributes", "*.payload filter=adopted\n"); + env.write("work/project/fixture.payload", "synthetic payload\n"); + git( + &env, + &project(&env), + &["add", ".gitattributes", "fixture.payload"], + ); + git(&env, &project(&env), &["commit", "-m", "fixture filter input"]); git(&env, &project(&env), &["push", "origin", "published:agent/test"]); git(&env, &project(&env), &["checkout", "main"]); git(&env, &project(&env), &["branch", "-D", "published"]); git(&env, &project(&env), &["fetch", "origin"]); + git(&env, &project(&env), &["config", "filter.adopted.smudge", "printf ran > adopted-filter-ran; if test -n \"${GH_TOKEN-}${GITHUB_TOKEN-}\"; then printf exposed > adopted-filter-credentials; fi; if test -r \"$HOME/.config/gh/config.yml\"; then printf exposed > adopted-filter-config; fi; readlink /proc/self/ns/net > adopted-filter-network; cat"]); + env.write("home/.config/gh/config.yml", "version: 1\n"); let hook = env.write( "work/project/.git/hooks/post-checkout", "#!/bin/sh\nif test -f checkout-policy.sh; then sh checkout-policy.sh; fi\n", @@ -165,15 +176,26 @@ fn published_checkout_hooks_have_neither_network_nor_github_credentials() { vec![ScriptTurn::text("nothing")], &["work", "../tasks.json"], Some(path), - &[("OXA_TEST_ISOLATION", "0")], + &[ + ("OXA_TEST_ISOLATION", "0"), + ("GH_TOKEN", "SYNTH_AMBIENT_CREDENTIAL"), + ("GITHUB_TOKEN", "SYNTH_AMBIENT_CREDENTIAL"), + ], ); assert_eq!(record["outcome"], "done", "{record}"); - assert!(tree(&record).join("adopted-hook-ran").exists(), "{record}"); + assert!(!tree(&record).join("adopted-hook-ran").exists(), "{record}"); assert!( !tree(&record).join("adopted-hook-credentials").exists(), "checkout exposed credentials: {record}" ); - let hook_net = std::fs::read_to_string(tree(&record).join("adopted-hook-network")).unwrap(); + assert!(!tree(&record).join("adopted-hook-network").exists(), "{record}"); + assert!(tree(&record).join("adopted-filter-ran").exists(), "{record}"); + assert!( + !tree(&record).join("adopted-filter-credentials").exists(), + "{record}" + ); + assert!(!tree(&record).join("adopted-filter-config").exists(), "{record}"); + let hook_net = std::fs::read_to_string(tree(&record).join("adopted-filter-network")).unwrap(); assert_ne!( hook_net.trim(), std::fs::read_link("/proc/self/ns/net").unwrap().to_str().unwrap(), @@ -217,10 +239,10 @@ fn identical_matching_remote_tips_keep_the_published_head_eligible() { } #[test] -fn published_branch_creation_keeps_required_reference_hook_policy() { +fn ordinary_branch_creation_keeps_required_reference_hook_policy() { use std::os::unix::fs::PermissionsExt; let env = TestEnv::new(); - published_task(&env); + setup(&env, "[]"); let hook = env.write("work/project/.git/hooks/reference-transaction", "#!/bin/sh\nwhile read old new reference; do if test \"$reference\" = refs/heads/agent/test; then echo required-published-reference-policy >&2; exit 1; fi; done\n"); std::fs::set_permissions(hook, std::fs::Permissions::from_mode(0o755)).unwrap(); let (record, requests) = run_observed(&env, vec![], &["work", "../tasks.json"], None); diff --git a/oxa/oxa-work/src/lib.rs b/oxa/oxa-work/src/lib.rs index 5e6b7b6ef..8eaeaabe1 100644 --- a/oxa/oxa-work/src/lib.rs +++ b/oxa/oxa-work/src/lib.rs @@ -492,13 +492,29 @@ pub struct SupervisorRequest { #[derive(Deserialize, Serialize)] #[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)] pub enum SupervisorOperation { - Checkout { branch: String, create: bool }, - Merge { base: String }, - Save { task_id: String }, - Checks { commands: Vec }, - CommittedChecks { commands: Vec, index: PathBuf }, + Checkout { + branch: String, + create: bool, + #[serde(default)] + adopted: bool, + }, + Merge { + base: String, + }, + Save { + task_id: String, + }, + Checks { + commands: Vec, + }, + CommittedChecks { + commands: Vec, + index: PathBuf, + }, Inspect, - InspectCommitted { index: PathBuf }, + InspectCommitted { + index: PathBuf, + }, } fn supervise( diff --git a/oxa/oxa-work/src/tree.rs b/oxa/oxa-work/src/tree.rs index fb633f586..84a5374af 100644 --- a/oxa/oxa-work/src/tree.rs +++ b/oxa/oxa-work/src/tree.rs @@ -223,6 +223,7 @@ pub(crate) fn prepare( operation: SupervisorOperation::Checkout { branch: task.branch.clone(), create, + adopted: published.is_some(), }, }, policy, From b4099cff503809fe5a013fedc955225a5342da82 Mon Sep 17 00:00:00 2001 From: oxa-agent Date: Tue, 17 Nov 2026 23:55:44 +0100 Subject: [PATCH 08/13] Keep committed acceptance on the existing checkout policy (#1052) --- oxa/oxa-work/src/committed.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/oxa/oxa-work/src/committed.rs b/oxa/oxa-work/src/committed.rs index e9200cc6a..9daeb8016 100644 --- a/oxa/oxa-work/src/committed.rs +++ b/oxa/oxa-work/src/committed.rs @@ -101,6 +101,7 @@ pub fn verify_saved_task(repo: &Path, binary: &Path, policy: &RunPolicy, id: &st operation: SupervisorOperation::Checkout { branch: saved.task.branch, create: false, + adopted: false, }, }, policy, From 09f29dbb120f9fea5287dd89bfa741b5d9f86b56 Mon Sep 17 00:00:00 2001 From: oxa-agent Date: Wed, 18 Nov 2026 00:36:41 +0100 Subject: [PATCH 09/13] Exercise adopted save callback authority with synthetic fixtures (#1052) --- oxa/oxa-cli/tests/work_continue.rs | 75 +++++++++++++++++++++++++++--- 1 file changed, 69 insertions(+), 6 deletions(-) diff --git a/oxa/oxa-cli/tests/work_continue.rs b/oxa/oxa-cli/tests/work_continue.rs index 0e41f8d1c..4c4ccd88e 100644 --- a/oxa/oxa-cli/tests/work_continue.rs +++ b/oxa/oxa-cli/tests/work_continue.rs @@ -86,6 +86,15 @@ fn published_task(env: &TestEnv) -> String { git(env, &project(env), &["rev-parse", "origin/agent/test"]) } +fn synthetic_github_path(env: &TestEnv) -> String { + use std::os::unix::fs::{DirBuilderExt, PermissionsExt}; + let tools = env.tmp().join("trusted-tools"); + std::fs::DirBuilder::new().mode(0o700).create(&tools).unwrap(); + let gh = env.write("tmp/trusted-tools/gh", "#!/bin/sh\ntest \"$*\" = 'auth token --hostname github.com' || exit 9\nprintf '%s\\n' SYNTH_CHECKOUT_CREDENTIAL\n"); + std::fs::set_permissions(gh, std::fs::Permissions::from_mode(0o755)).unwrap(); + format!("{}:{}", tools.display(), std::env::var("PATH").unwrap()) +} + #[test] fn fresh_worktree_starts_at_the_published_task_branch_head() { let env = TestEnv::new(); @@ -137,7 +146,7 @@ fn ordinary_fresh_branch_reference_hooks_run_only_in_the_task_sandbox() { #[test] fn published_checkout_hooks_have_neither_network_nor_github_credentials() { - use std::os::unix::fs::{DirBuilderExt, PermissionsExt}; + use std::os::unix::fs::PermissionsExt; let env = TestEnv::new(); published_task(&env); git( @@ -165,11 +174,7 @@ fn published_checkout_hooks_have_neither_network_nor_github_credentials() { "#!/bin/sh\nif test -f checkout-policy.sh; then sh checkout-policy.sh; fi\n", ); std::fs::set_permissions(hook, std::fs::Permissions::from_mode(0o755)).unwrap(); - let tools = env.tmp().join("trusted-tools"); - std::fs::DirBuilder::new().mode(0o700).create(&tools).unwrap(); - let gh = env.write("tmp/trusted-tools/gh", "#!/bin/sh\ntest \"$*\" = 'auth token --hostname github.com' || exit 9\nprintf '%s\\n' SYNTH_CHECKOUT_CREDENTIAL\n"); - std::fs::set_permissions(gh, std::fs::Permissions::from_mode(0o755)).unwrap(); - let path = format!("{}:{}", tools.display(), std::env::var("PATH").unwrap()); + let path = synthetic_github_path(&env); // Only this fixture gh is reachable first, under a throwaway HOME. No real login is read. let (record, _) = work::run_observed_with_env( &env, @@ -203,6 +208,64 @@ fn published_checkout_hooks_have_neither_network_nor_github_credentials() { ); } +#[test] +fn adopted_save_callbacks_have_no_ambient_authority() { + use std::os::unix::fs::PermissionsExt; + let env = TestEnv::new(); + published_task(&env); + git( + &env, + &project(&env), + &["checkout", "-b", "published", "origin/agent/test"], + ); + let hook = env.write("work/project/hooks/pre-commit", "#!/bin/sh\nprintf ran > adopted-save-ran\nif test -n \"${GH_TOKEN-}${GITHUB_TOKEN-}\"; then printf exposed > adopted-save-credentials; fi\nif test -r \"$HOME/.config/gh/config.yml\"; then printf exposed > adopted-save-config; fi\nreadlink /proc/self/ns/net > adopted-save-network\n"); + std::fs::set_permissions(hook, std::fs::Permissions::from_mode(0o755)).unwrap(); + env.write("work/project/.gitignore", "/adopted-save-*\n"); + git(&env, &project(&env), &["add", "hooks/pre-commit", ".gitignore"]); + git(&env, &project(&env), &["commit", "-m", "fixture saved hook"]); + git(&env, &project(&env), &["push", "origin", "published:agent/test"]); + git(&env, &project(&env), &["checkout", "main"]); + git(&env, &project(&env), &["branch", "-D", "published"]); + git(&env, &project(&env), &["fetch", "origin"]); + git(&env, &project(&env), &["config", "core.hooksPath", "hooks"]); + env.write("home/.config/gh/config.yml", "version: 1\n"); + let (record, _) = work::run_observed_with_env( + &env, + vec![ + ScriptTurn::tool( + "edit", + "write", + r#"{"path":"changed.txt","content":"synthetic change\n"}"#, + ), + ScriptTurn::text("done"), + ], + &["work", "../tasks.json"], + Some(synthetic_github_path(&env)), + &[ + ("OXA_TEST_ISOLATION", "0"), + ("GH_TOKEN", "SYNTH_AMBIENT_CREDENTIAL"), + ("GITHUB_TOKEN", "SYNTH_AMBIENT_CREDENTIAL"), + ], + ); + assert_eq!(record["outcome"], "done", "{record}"); + assert_eq!( + std::fs::read_to_string(tree(&record).join("changed.txt")).unwrap(), + "synthetic change\n" + ); + assert!(tree(&record).join("adopted-save-ran").exists(), "{record}"); + assert!( + !tree(&record).join("adopted-save-credentials").exists(), + "save exposed credentials: {record}" + ); + assert!(!tree(&record).join("adopted-save-config").exists(), "{record}"); + let hook_net = std::fs::read_to_string(tree(&record).join("adopted-save-network")).unwrap(); + assert_ne!( + hook_net.trim(), + std::fs::read_link("/proc/self/ns/net").unwrap().to_str().unwrap() + ); + assert_eq!(git(&env, tree(&record), &["status", "--porcelain"]), ""); +} + #[test] fn a_divergent_matching_remote_tip_prevents_published_head_adoption() { let env = TestEnv::new(); From 522bf83256b27197e938bf089d2e05ba61c902fa Mon Sep 17 00:00:00 2001 From: oxa-agent Date: Wed, 18 Nov 2026 00:51:10 +0100 Subject: [PATCH 10/13] Reach local save and merge callbacks in authority regressions (#1052) --- oxa/oxa-cli/tests/work_continue.rs | 40 +++++++++++++++++++++++++----- 1 file changed, 34 insertions(+), 6 deletions(-) diff --git a/oxa/oxa-cli/tests/work_continue.rs b/oxa/oxa-cli/tests/work_continue.rs index 4c4ccd88e..add04e533 100644 --- a/oxa/oxa-cli/tests/work_continue.rs +++ b/oxa/oxa-cli/tests/work_continue.rs @@ -218,16 +218,20 @@ fn adopted_save_callbacks_have_no_ambient_authority() { &project(&env), &["checkout", "-b", "published", "origin/agent/test"], ); - let hook = env.write("work/project/hooks/pre-commit", "#!/bin/sh\nprintf ran > adopted-save-ran\nif test -n \"${GH_TOKEN-}${GITHUB_TOKEN-}\"; then printf exposed > adopted-save-credentials; fi\nif test -r \"$HOME/.config/gh/config.yml\"; then printf exposed > adopted-save-config; fi\nreadlink /proc/self/ns/net > adopted-save-network\n"); - std::fs::set_permissions(hook, std::fs::Permissions::from_mode(0o755)).unwrap(); + env.write("work/project/save-callback.sh", "printf ran > adopted-save-ran\nif test -n \"${GH_TOKEN-}${GITHUB_TOKEN-}\"; then printf exposed > adopted-save-credentials; fi\nif test -r \"$HOME/.config/gh/config.yml\"; then printf exposed > adopted-save-config; fi\nreadlink /proc/self/ns/net > adopted-save-network\n"); env.write("work/project/.gitignore", "/adopted-save-*\n"); - git(&env, &project(&env), &["add", "hooks/pre-commit", ".gitignore"]); + git(&env, &project(&env), &["add", "save-callback.sh", ".gitignore"]); git(&env, &project(&env), &["commit", "-m", "fixture saved hook"]); git(&env, &project(&env), &["push", "origin", "published:agent/test"]); git(&env, &project(&env), &["checkout", "main"]); git(&env, &project(&env), &["branch", "-D", "published"]); git(&env, &project(&env), &["fetch", "origin"]); - git(&env, &project(&env), &["config", "core.hooksPath", "hooks"]); + // A repository-installed callback can invoke files from the adopted head. + let hook = env.write( + "work/project/.git/hooks/pre-commit", + "#!/bin/sh\nexec sh save-callback.sh\n", + ); + std::fs::set_permissions(hook, std::fs::Permissions::from_mode(0o755)).unwrap(); env.write("home/.config/gh/config.yml", "version: 1\n"); let (record, _) = work::run_observed_with_env( &env, @@ -575,10 +579,21 @@ fn automatic_merge_hooks_stay_inside_the_sandbox() { diverge(&env, false); let hook = env.write( "work/project/.git/hooks/post-merge", - "#!/bin/sh\nprintf escaped > \"$HOME/continuation-hook-escape\" 2>/dev/null || true\nprintf ran > post-merge-ran\n", + "#!/bin/sh\nprintf escaped > \"$HOME/continuation-hook-escape\" 2>/dev/null || true\nprintf ran > post-merge-ran\nif test -n \"${GH_TOKEN-}${GITHUB_TOKEN-}\"; then printf exposed > \"$(git rev-parse --git-path merge-credentials)\"; fi\nif test -r \"$HOME/.config/gh/config.yml\"; then printf exposed > \"$(git rev-parse --git-path merge-config)\"; fi\nreadlink /proc/self/ns/net > \"$(git rev-parse --git-path merge-network)\"\n", ); std::fs::set_permissions(hook, std::fs::Permissions::from_mode(0o755)).unwrap(); - let record = run(&env, vec![ScriptTurn::text("nothing")]); + env.write("home/.config/gh/config.yml", "version: 1\n"); + let (record, _) = work::run_observed_with_env( + &env, + vec![ScriptTurn::text("nothing")], + &["work", "../tasks.json"], + Some(synthetic_github_path(&env)), + &[ + ("OXA_TEST_ISOLATION", "0"), + ("GH_TOKEN", "SYNTH_AMBIENT_CREDENTIAL"), + ("GITHUB_TOKEN", "SYNTH_AMBIENT_CREDENTIAL"), + ], + ); assert!(!env.home().join("continuation-hook-escape").exists(), "{record}"); assert_eq!(record["outcome"], "done", "{record}"); assert_eq!( @@ -586,6 +601,19 @@ fn automatic_merge_hooks_stay_inside_the_sandbox() { "ran" ); assert!(!project(&env).join("post-merge-ran").exists()); + let marker = |name: &str| { + PathBuf::from(git( + &env, + tree(&record), + &["rev-parse", "--path-format=absolute", "--git-path", name], + )) + }; + assert!(!marker("merge-credentials").exists(), "{record}"); + assert!(!marker("merge-config").exists(), "{record}"); + assert_ne!( + std::fs::read_to_string(marker("merge-network")).unwrap().trim(), + std::fs::read_link("/proc/self/ns/net").unwrap().to_str().unwrap() + ); } #[test] From 8433387ebfd51ca9b9ba4900aebded1ec27466b5 Mon Sep 17 00:00:00 2001 From: oxa-agent Date: Wed, 18 Nov 2026 00:57:49 +0100 Subject: [PATCH 11/13] Keep automatic local Git callbacks without network authority (#1052) --- oxa/oxa-cli/src/work_checks.rs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/oxa/oxa-cli/src/work_checks.rs b/oxa/oxa-cli/src/work_checks.rs index 2d09877ec..802baf635 100644 --- a/oxa/oxa-cli/src/work_checks.rs +++ b/oxa/oxa-cli/src/work_checks.rs @@ -109,17 +109,17 @@ pub(crate) fn run( return Ok(0); } SupervisorOperation::Merge { base } => { - let sandbox = crate::netguard::with_net(Arc::new(b), &settings); + // Local Git callbacks do not need repository network authority. let spec = ExecSpec { command: format!("git --no-replace-objects merge --no-edit -- {}", sh_quote(&base)), cwd: root, writable: true, - net: sandbox.network(), + net: false, timeout_s: Some(600), env: git_environment(), }; let mut tail = Vec::new(); - let result = sandbox.run_streaming(&spec, &CancelToken::default(), &mut |bytes| { + let result = b.run_streaming(&spec, &CancelToken::default(), &mut |bytes| { keep_tail(&mut tail, bytes, 8192); }); err.write_all(&tail).map_err(|e| e.to_string())?; @@ -129,7 +129,7 @@ pub(crate) fn run( return Ok(i32::from(result.exit != Some(0))); } SupervisorOperation::Save { task_id } => { - let sandbox = crate::netguard::with_net(Arc::new(b), &settings); + // Keep save callbacks local, including content from an adopted head. let message = sh_quote(&format!("oxa work: save task {task_id}")); let spec = ExecSpec { command: format!( @@ -149,12 +149,12 @@ git --no-replace-objects commit -m {message} ), cwd: root, writable: true, - net: sandbox.network(), + net: false, timeout_s: Some(600), env: git_environment(), }; let mut tail = Vec::new(); - let result = sandbox.run_streaming(&spec, &CancelToken::default(), &mut |bytes| { + let result = b.run_streaming(&spec, &CancelToken::default(), &mut |bytes| { keep_tail(&mut tail, bytes, 8192); }); if result.exit != Some(0) || result.timed_out { From 4c11c23de47d296ac427a709a734f2a54e558866 Mon Sep 17 00:00:00 2001 From: oxa-agent Date: Wed, 18 Nov 2026 01:53:51 +0100 Subject: [PATCH 12/13] Exercise adopted acceptance authority with isolated fixtures (#1052) --- oxa/oxa-cli/tests/work_continue.rs | 73 +++++++++++++++++++++++++++++- 1 file changed, 72 insertions(+), 1 deletion(-) diff --git a/oxa/oxa-cli/tests/work_continue.rs b/oxa/oxa-cli/tests/work_continue.rs index 7d0a012a2..7d7ab3cad 100644 --- a/oxa/oxa-cli/tests/work_continue.rs +++ b/oxa/oxa-cli/tests/work_continue.rs @@ -77,6 +77,10 @@ fn existing_branch_fast_forwards_to_base_before_agent() { fn published_task(env: &TestEnv) -> String { setup(env, "[]"); + publish_prepared_task(env) +} + +fn publish_prepared_task(env: &TestEnv) -> String { git(env, &project(env), &["checkout", "-b", "agent/test"]); commit_file(env, "pr.txt", "from the pull request\n"); git(env, &project(env), &["push", "origin", "agent/test"]); @@ -90,7 +94,7 @@ fn synthetic_github_path(env: &TestEnv) -> String { use std::os::unix::fs::{DirBuilderExt, PermissionsExt}; let tools = env.tmp().join("trusted-tools"); std::fs::DirBuilder::new().mode(0o700).create(&tools).unwrap(); - let gh = env.write("tmp/trusted-tools/gh", "#!/bin/sh\ntest \"$*\" = 'auth token --hostname github.com' || exit 9\nprintf '%s\\n' SYNTH_CHECKOUT_CREDENTIAL\n"); + let gh = env.write("tmp/trusted-tools/gh", "#!/bin/sh\ntest \"$*\" = 'auth token --hostname github.com' || exit 9\nprintf looked > \"$0.called\"\nprintf '%s\\n' SYNTH_CHECKOUT_CREDENTIAL\n"); std::fs::set_permissions(gh, std::fs::Permissions::from_mode(0o755)).unwrap(); format!("{}:{}", tools.display(), std::env::var("PATH").unwrap()) } @@ -301,6 +305,73 @@ fn adopted_save_callbacks_have_no_ambient_authority() { assert_eq!(git(&env, tree(&record), &["status", "--porcelain"]), ""); } +#[test] +fn adopted_acceptance_has_no_github_authority_and_preserves_network_policy() { + for offline in [false, true] { + let env = TestEnv::new(); + setup( + &env, + r#"["test -f answer.txt && git diff --check && sh acceptance.sh"]"#, + ); + env.write("work/project/acceptance.sh", "true\n"); + env.write("work/project/.gitignore", "/adopted-acceptance-*\n"); + git(&env, &project(&env), &["add", "acceptance.sh", ".gitignore"]); + git(&env, &project(&env), &["commit", "-m", "fixture acceptance"]); + publish_prepared_task(&env); + git( + &env, + &project(&env), + &["checkout", "-b", "published", "origin/agent/test"], + ); + env.write("work/project/acceptance.sh", "printf ran > adopted-acceptance-ran\nif test -n \"${GH_TOKEN-}${GITHUB_TOKEN-}\"; then printf exposed > adopted-acceptance-credentials; fi\nreadlink /proc/self/ns/net > adopted-acceptance-network\n"); + git(&env, &project(&env), &["add", "acceptance.sh"]); + git( + &env, + &project(&env), + &["commit", "-m", "fixture published acceptance"], + ); + git(&env, &project(&env), &["push", "origin", "published:agent/test"]); + git(&env, &project(&env), &["checkout", "main"]); + git(&env, &project(&env), &["branch", "-D", "published"]); + git(&env, &project(&env), &["fetch", "origin"]); + let args = if offline { + vec!["--offline", "work", "../tasks.json"] + } else { + vec!["work", "../tasks.json"] + }; + let (record, _) = work::run_observed_with( + &env, + vec![ + ScriptTurn::tool( + "edit", + "write", + r#"{"path":"answer.txt","content":"synthetic change\n"}"#, + ), + ScriptTurn::text("done"), + ], + &args, + Some(synthetic_github_path(&env)), + |command| { + command.envs([ + ("OXA_TEST_ISOLATION", "0"), + ("GH_TOKEN", "SYNTH_AMBIENT_CREDENTIAL"), + ("GITHUB_TOKEN", "SYNTH_AMBIENT_CREDENTIAL"), + ]); + }, + ); + assert_eq!(record["outcome"], "done", "{record}"); + assert!(tree(&record).join("adopted-acceptance-ran").exists(), "{record}"); + assert!( + !tree(&record).join("adopted-acceptance-credentials").exists(), + "{record}" + ); + assert!(!env.tmp().join("trusted-tools/gh.called").exists(), "{record}"); + let network = std::fs::read_to_string(tree(&record).join("adopted-acceptance-network")).unwrap(); + let host = std::fs::read_link("/proc/self/ns/net").unwrap(); + assert_eq!(network.trim() == host.to_str().unwrap(), !offline, "{record}"); + } +} + #[test] fn a_divergent_matching_remote_tip_prevents_published_head_adoption() { let env = TestEnv::new(); From 206fa3e404850a6282b00cf4ef3807007c7dac44 Mon Sep 17 00:00:00 2001 From: oxa-agent Date: Wed, 18 Nov 2026 02:08:51 +0100 Subject: [PATCH 13/13] Keep automatic acceptance free of GitHub authentication (#1052) --- oxa/oxa-cli/src/netguard.rs | 12 +++++++++++- oxa/oxa-cli/src/work_checks.rs | 2 +- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/oxa/oxa-cli/src/netguard.rs b/oxa/oxa-cli/src/netguard.rs index da65b45ca..6c4a4bcc8 100644 --- a/oxa/oxa-cli/src/netguard.rs +++ b/oxa/oxa-cli/src/netguard.rs @@ -9,12 +9,22 @@ use std::sync::Arc; /// O-167(b): the process sandbox with the bash network decision (`oxa.sandbox.net`, default /// on; always off while offline). Read once at startup. pub(crate) fn with_net(sandbox: Arc, settings: &Settings) -> Arc { + with_policy(sandbox, settings, true) +} + +/// Acceptance commands keep the user's network policy without GitHub authentication. +pub(crate) fn without_github(sandbox: Arc, settings: &Settings) -> Arc { + with_policy(sandbox, settings, false) +} + +fn with_policy(sandbox: Arc, settings: &Settings, github_auth: bool) -> Arc { let runner_owns_github = std::env::var_os(oxa_work::RUNNER_GITHUB_ENV).is_some_and(|value| value == "1"); let on = !runner_owns_github && sandbox_net_setting(settings.string(SETTING_SANDBOX_NET).as_deref()); let offline = oxa_proto::offline(); // The `gh` lookup can stall (a mise shim may try to install gh): run it lazily, at the first // bash command that has the network, never at startup. - let lookup = on + let lookup = github_auth + && on && !offline && !test_isolated( std::env::var(oxa_proto::names::ENV_TEST_ISOLATION) diff --git a/oxa/oxa-cli/src/work_checks.rs b/oxa/oxa-cli/src/work_checks.rs index 04ee49344..b794d61fb 100644 --- a/oxa/oxa-cli/src/work_checks.rs +++ b/oxa/oxa-cli/src/work_checks.rs @@ -179,7 +179,7 @@ git --no-replace-objects commit -m {message} shell_path: settings.shell_path(&dirs.home), command_prefix: settings.shell_command_prefix(), }; - let sandbox = crate::netguard::with_net(Arc::new(b), &settings); + let sandbox = crate::netguard::without_github(Arc::new(b), &settings); let mut failed = false; let mut diagnostics = Vec::new(); for entry in commands {