From c5d156b88e480f94e1fef942c97f568ea19cf8d7 Mon Sep 17 00:00:00 2001 From: Oscar Nordstrom <13300531+n0rpan@users.noreply.github.com> Date: Tue, 17 Nov 2026 19:14:39 +0100 Subject: [PATCH 1/2] work: start a resumed worktree at its pushed PR head Resuming a PR from a retained worktree audited whatever commit the earlier run left there. When the PR branch was pushed on from elsewhere, the local branch still pointed at the older commit, so the worker read an obsolete tree and a later push could drop the commits made in between. Before the base merge, a retained worktree whose lone remote-tracking tip of the same branch strictly extends its HEAD now starts at that published head through the sandboxed supervisor, as an ordinary fast-forward. No fetch, reset or force update is added: a tip that is not ahead, several diverging tips or a dangling tracking ref keep the retained commits, and a tip that stops being a fast-forward refuses the resume instead of rewriting it. The initial commit recorded for the run is taken after the advance. Tests: work_continue resumes a worktree after the PR branch was pushed on from another clone and checks the worktree head and tree, and checks that a pushed head the local commit is not an ancestor of is left untouched. Fixes #1006 --- oxa/docs/work.md | 9 +++- oxa/oxa-cli/src/work_checks.rs | 25 +++++++++ oxa/oxa-cli/tests/work_continue.rs | 86 +++++++++++++++++++++++++++++- oxa/oxa-work/src/lib.rs | 1 + oxa/oxa-work/src/tree.rs | 85 ++++++++++++++++++++++++++++- 5 files changed, 202 insertions(+), 4 deletions(-) diff --git a/oxa/docs/work.md b/oxa/docs/work.md index 8d2695a6f..c95af1bc4 100644 --- a/oxa/docs/work.md +++ b/oxa/docs/work.md @@ -147,8 +147,13 @@ 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 -retrying. A clean retained branch gets an ordinary sandboxed -merge of the captured base; no reset, stash, force checkout or automatic fetch runs. +retrying. A clean retained branch whose pushed head strictly extends its local +commit starts at that published head through a sandboxed fast-forward, so a +resumed PR audits its current head instead of the checkout an earlier run left. +A tip that is not ahead, several diverging tips or a dangling tracking ref keep +the local commits. The captured base is then +integrated with an ordinary sandboxed merge; no reset, stash, force checkout or +automatic fetch runs. An unfinished merge is passed to the worker with its old pending commit, the captured current base and at most twenty conflicted paths. The worker must finish diff --git a/oxa/oxa-cli/src/work_checks.rs b/oxa/oxa-cli/src/work_checks.rs index 8b265c526..930e9563c 100644 --- a/oxa/oxa-cli/src/work_checks.rs +++ b/oxa/oxa-cli/src/work_checks.rs @@ -78,6 +78,31 @@ pub(crate) fn run( } return Ok(i32::from(result.exit != Some(0))); } + // Only a fast-forward: the branch's own commits or the published head, never a + // rewrite. A tip that does not apply leaves the retained commits untouched. + SupervisorOperation::FastForward { tip } => { + let sandbox = crate::netguard::with_net(Arc::new(b), &settings); + let spec = ExecSpec { + command: format!( + "git --no-replace-objects merge --ff-only --no-edit -- '{}'", + tip.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); + }); + err.write_all(&tail).map_err(|e| e.to_string())?; + if result.timed_out || result.exit.is_none() { + return Err("sandboxed fast-forward did not complete; worktree retained".into()); + } + return Ok(i32::from(result.exit != Some(0))); + } SupervisorOperation::Save { task_id } => { let sandbox = crate::netguard::with_net(Arc::new(b), &settings); let message = format!("oxa work: save task {task_id}").replace('\'', "'\\''"); diff --git a/oxa/oxa-cli/tests/work_continue.rs b/oxa/oxa-cli/tests/work_continue.rs index dc7492baf..8b4a67aed 100644 --- a/oxa/oxa-cli/tests/work_continue.rs +++ b/oxa/oxa-cli/tests/work_continue.rs @@ -3,7 +3,7 @@ mod work; use oxa_fake::{ScriptTurn, TestEnv}; use std::path::{Path, PathBuf}; -use work::{git, run, run_observed, setup}; +use work::{git, run, run_args, run_observed, setup}; fn project(env: &TestEnv) -> PathBuf { env.work().join("project") @@ -28,6 +28,30 @@ fn diverge(env: &TestEnv, conflict: bool) { fn tree(record: &serde_json::Value) -> &Path { Path::new(record["worktree"].as_str().unwrap()) } +/// Publish `agent/test` from a second clone and update the source checkout's +/// remote-tracking ref, without touching the retained task worktree. With `from` +/// the pushed branch starts there instead of at the local task branch. +fn push_elsewhere(env: &TestEnv, from: Option<&str>, file: &str, content: &str) -> String { + let other = env.work().join("elsewhere"); + git(env, &env.work(), &["clone", "remote.git", "elsewhere"]); + git(env, &other, &["config", "user.name", "Test"]); + git(env, &other, &["config", "user.email", "test@example.invalid"]); + match from { + Some(rev) => { + git(env, &other, &["checkout", "-b", "agent/test", rev]); + } + None => { + git(env, &project(env), &["push", "origin", "agent/test"]); + git(env, &other, &["checkout", "agent/test"]); + } + } + env.write(&format!("work/elsewhere/{file}"), content); + git(env, &other, &["add", file]); + git(env, &other, &["commit", "-m", "pushed elsewhere"]); + git(env, &other, &["push", "origin", "agent/test"]); + git(env, &project(env), &["fetch", "origin"]); + git(env, &other, &["rev-parse", "HEAD"]) +} fn merge_head(env: &TestEnv, root: &Path) -> PathBuf { PathBuf::from(git( env, @@ -169,6 +193,66 @@ fn dirty_retained_worktree_is_blocked_without_dropping_edits() { "new retained edits" ); } +#[test] +fn resumed_worktree_starts_at_the_pushed_pr_head() { + let env = TestEnv::new(); + setup(&env, "[]"); + trust(&env); + let first = run( + &env, + vec![ + ScriptTurn::tool("write", "write", r#"{"path":"local.txt","content":"own work"}"#), + ScriptTurn::text("done"), + ], + ); + assert_eq!(first["outcome"], "done", "{first}"); + let local = git(&env, tree(&first), &["rev-parse", "HEAD"]); + let pushed = push_elsewhere(&env, None, "pushed.txt", "pushed elsewhere\n"); + assert_ne!(local, pushed); + let record = run_args( + &env, + vec![ScriptTurn::text("nothing new")], + &["work", "../tasks.json", "--rerun"], + None, + ); + assert_eq!(record["outcome"], "nothing_to_do", "{record}"); + assert_eq!(git(&env, tree(&record), &["rev-parse", "HEAD"]), pushed); + assert!(tree(&record).join("pushed.txt").exists()); + assert!(tree(&record).join("local.txt").exists()); + assert!(!project(&env).join("pushed.txt").exists()); +} + +#[test] +fn resumed_worktree_never_drops_a_local_commit_the_pushed_head_lacks() { + let env = TestEnv::new(); + setup(&env, "[]"); + trust(&env); + let first = run( + &env, + vec![ + ScriptTurn::tool("local", "write", r#"{"path":"local.txt","content":"own work"}"#), + ScriptTurn::text("done"), + ], + ); + assert_eq!(first["outcome"], "done", "{first}"); + let local = git(&env, tree(&first), &["rev-parse", "HEAD"]); + push_elsewhere(&env, Some("origin/main"), "other.txt", "other work\n"); + let record = run_args( + &env, + vec![ScriptTurn::text("still nothing")], + &["work", "../tasks.json", "--rerun"], + None, + ); + assert_eq!(record["outcome"], "nothing_to_do", "{record}"); + assert_eq!(git(&env, tree(&record), &["rev-parse", "HEAD"]), local); + assert_eq!( + git(&env, tree(&record), &["rev-list", "--parents", "-n", "1", "HEAD"]) + .split_whitespace() + .count(), + 2 + ); +} + #[test] fn continued_branch_cannot_replace_base_acceptance_commands() { let env = TestEnv::new(); diff --git a/oxa/oxa-work/src/lib.rs b/oxa/oxa-work/src/lib.rs index 4a878d711..1eaa13cd0 100644 --- a/oxa/oxa-work/src/lib.rs +++ b/oxa/oxa-work/src/lib.rs @@ -315,6 +315,7 @@ pub struct SupervisorRequest { pub enum SupervisorOperation { Checkout { branch: String, create: bool }, Merge { base: String }, + FastForward { tip: String }, Save { task_id: String }, Checks { commands: Vec }, Inspect, diff --git a/oxa/oxa-work/src/tree.rs b/oxa/oxa-work/src/tree.rs index fb135b4ae..bb7fb3651 100644 --- a/oxa/oxa-work/src/tree.rs +++ b/oxa/oxa-work/src/tree.rs @@ -80,6 +80,84 @@ pub(crate) fn validate(policy: &RunPolicy, repo: &Path, tree: &Path, task: &Task Ok(()) } +/// A retained worktree that still sits on an older commit of the branch whose +/// pushed head moved on would make the worker audit an obsolete tree. Start it +/// at that published head, through the sandboxed supervisor and only as a +/// fast-forward an ordinary merge performs. A tip that is not strictly ahead or +/// a dangling tracking ref keeps the retained commits; the sandboxed +/// fast-forward refuses the resume if it cannot apply. +fn advance_retained( + repo: &Path, + tree: &Path, + branch: &str, + local: &str, + binary: &Path, + policy: &RunPolicy, + lock: &fs::File, +) -> Result<()> { + let Some(tip) = pushed_head(policy, repo, branch, local)? else { + return Ok(()); + }; + let advanced = supervise( + binary, + tree, + SupervisorRequest { + source: repo.to_path_buf(), + operation: SupervisorOperation::FastForward { tip }, + }, + policy, + lock, + )?; + if advanced.status.success() { + return Ok(()); + } + // A concurrent push can make the tip non-fast-forward; never rewrite then. + Err(format!( + "pushed head is no longer a fast-forward of the retained worktree: {}", + String::from_utf8_lossy(&advanced.stderr) + )) +} + +/// The published task branch may have moved on since this worktree was retained. +/// Return the lone remote-tracking tip of the same branch that strictly extends +/// the local commit. No fetch or force update runs, and a tip that is not ahead, +/// several diverging tips, or a dangling tracking ref keep the local commits. +fn pushed_head(policy: &RunPolicy, repo: &Path, branch: &str, local: &str) -> Result> { + let pattern = format!("refs/remotes/*/{branch}"); + let tracking = checked(git( + policy, + repo, + &["for-each-ref", "--format=%(refname)", &pattern], + ))?; + let mut ahead = 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 != local + && output(git(policy, repo, &["merge-base", "--is-ancestor", local, &tip]))? + .status + .code() + == Some(0) + { + ahead.push(tip); + } + } + ahead.sort(); + ahead.dedup(); + Ok(match ahead.as_slice() { + [tip] => Some(tip.clone()), + _ => None, + }) +} + pub(crate) fn prepare( repo: &Path, tree: &Path, @@ -140,7 +218,7 @@ pub(crate) fn prepare( return Err(format!("retained worktree has {operation} in progress")); } } - let initial = checked(git(policy, tree, &["rev-parse", "HEAD"]))?; + let mut initial = checked(git(policy, tree, &["rev-parse", "HEAD"]))?; if merging(policy, tree)? { return Ok(Prepared { initial, @@ -150,6 +228,11 @@ pub(crate) fn prepare( if retained && dirty_worktree(binary, tree, repo, policy, lock)? { return Err("retained worktree has uncommitted changes; worker was not restarted".into()); } + if retained { + // A resumed PR must audit its published head, not the checkout an earlier run left. + advance_retained(repo, tree, &task.branch, &initial, binary, policy, lock)?; + initial = checked(git(policy, tree, &["rev-parse", "HEAD"]))?; + } let merged = supervise( binary, tree, From 724c7718c88c49f036370acecdc215612435c60c Mon Sep 17 00:00:00 2001 From: Oscar Nordstrom <13300531+n0rpan@users.noreply.github.com> Date: Tue, 17 Nov 2026 19:29:25 +0100 Subject: [PATCH 2/2] test(work): clone the pushed branch after publishing it The resumed-worktree tests cloned the second checkout before `agent/test` existed on the remote, because oxa itself never pushes: a work run leaves the branch local. The clone therefore had only a remote-tracking ref for it, and the DWIM `git checkout agent/test` failed with "pathspec 'agent/test' did not match any file(s) known to git", failing the lane on the push-elsewhere fixture rather than on the resume behaviour it tests. Publish the branch from the source checkout first and start the clone's branch from `origin/agent/test` explicitly. The worktree and tree assertions are unchanged. Fixes #1006 --- oxa/oxa-cli/tests/work_continue.rs | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/oxa/oxa-cli/tests/work_continue.rs b/oxa/oxa-cli/tests/work_continue.rs index 8b4a67aed..d99acf168 100644 --- a/oxa/oxa-cli/tests/work_continue.rs +++ b/oxa/oxa-cli/tests/work_continue.rs @@ -28,10 +28,14 @@ fn diverge(env: &TestEnv, conflict: bool) { fn tree(record: &serde_json::Value) -> &Path { Path::new(record["worktree"].as_str().unwrap()) } -/// Publish `agent/test` from a second clone and update the source checkout's +/// Publish `agent/test` from the source checkout first (oxa itself never pushes), +/// then extend it in a second clone and update the source checkout's /// remote-tracking ref, without touching the retained task worktree. With `from` -/// the pushed branch starts there instead of at the local task branch. +/// the pushed branch starts there instead of at the source checkout's task branch. fn push_elsewhere(env: &TestEnv, from: Option<&str>, file: &str, content: &str) -> String { + if from.is_none() { + git(env, &project(env), &["push", "origin", "agent/test"]); + } let other = env.work().join("elsewhere"); git(env, &env.work(), &["clone", "remote.git", "elsewhere"]); git(env, &other, &["config", "user.name", "Test"]); @@ -41,8 +45,13 @@ fn push_elsewhere(env: &TestEnv, from: Option<&str>, file: &str, content: &str) git(env, &other, &["checkout", "-b", "agent/test", rev]); } None => { - git(env, &project(env), &["push", "origin", "agent/test"]); - git(env, &other, &["checkout", "agent/test"]); + // The bare remote's default branch is absent, so the clone checks out + // nothing; start the branch from the published tip explicitly. + git( + env, + &other, + &["checkout", "-b", "agent/test", "origin/agent/test"], + ); } } env.write(&format!("work/elsewhere/{file}"), content);