Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions oxa/docs/work.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
25 changes: 25 additions & 0 deletions oxa/oxa-cli/src/work_checks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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('\'', "'\\''");
Expand Down
95 changes: 94 additions & 1 deletion oxa/oxa-cli/tests/work_continue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand All @@ -28,6 +28,39 @@ fn diverge(env: &TestEnv, conflict: bool) {
fn tree(record: &serde_json::Value) -> &Path {
Path::new(record["worktree"].as_str().unwrap())
}
/// 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 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"]);
git(env, &other, &["config", "user.email", "test@example.invalid"]);
match from {
Some(rev) => {
git(env, &other, &["checkout", "-b", "agent/test", rev]);
}
None => {
// 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);
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,
Expand Down Expand Up @@ -169,6 +202,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();
Expand Down
1 change: 1 addition & 0 deletions oxa/oxa-work/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String> },
Inspect,
Expand Down
85 changes: 84 additions & 1 deletion oxa/oxa-work/src/tree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Option<String>> {
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,
Expand Down Expand Up @@ -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,
Expand All @@ -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,
Expand Down
Loading