Skip to content
Merged
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
30 changes: 22 additions & 8 deletions oxa/docs/work.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@ Run it inside the project repository. The JSON file is an array:
```

`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,
IDs and branches must be unique within one file. Existing task branches can be
continued. 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
Expand Down Expand Up @@ -59,21 +60,34 @@ JSON lines include the worker result, session ID and captured `base_sha` and rep
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
JSON line and does not skip later tasks. If a task cannot be locked or has an
incompatible 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/<repository>/<id>`
beside the repository (or the separate git directory). Private result receipts and
locks live under `~/.oxa/agent/work/<repository-hash>/` (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), outside the worker's writable Git bind. New receipts are published
atomically without overwriting an existing receipt; a validated matching receipt
is replaced atomically under the task lock when continuing. 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
cleanup, commit, push or PR creation 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.

To continue a task, run the same task file again. A matching retained receipt and
linked worktree are reused. The source checkout is never used as the task worktree.
An existing branch checked out elsewhere is blocked. Dirty retained work is kept
and blocked until committed. A clean retained branch gets an ordinary sandboxed
merge of the captured base; 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
that merge and merge the captured base too. Aborted or unresolved merges and branch
switches remain blocked even if acceptance passes. Worker, merge and acceptance
failures are retained together. Receipt replacement keeps private modes.
34 changes: 29 additions & 5 deletions oxa/oxa-cli/src/work_checks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,14 @@ pub(crate) fn run(
let settings = Settings::load(dirs, &source, true);
let commands = match request.operation {
SupervisorOperation::Inspect => return inspect(&b, &root),
SupervisorOperation::Checkout { branch } => {
SupervisorOperation::Checkout { branch, create } => {
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('\'', "'\\''")
),
command: if create {
format!("git --no-replace-objects checkout HEAD -- . && git --no-replace-objects checkout -b '{}' HEAD", branch.replace('\'', "'\\''"))
} else {
"git --no-replace-objects checkout HEAD -- .".into()
},
cwd: root,
writable: true,
net: sandbox.network(),
Expand All @@ -54,6 +55,29 @@ pub(crate) fn run(
}
return Ok(0);
}
SupervisorOperation::Merge { base } => {
let sandbox = crate::netguard::with_net(Arc::new(b), &settings);
let spec = ExecSpec {
command: format!(
"git --no-replace-objects merge --no-edit -- '{}'",
base.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 base merge did not complete; worktree retained".into());
}
return Ok(i32::from(result.exit != Some(0)));
}
SupervisorOperation::Checks { commands } => commands,
};
let shell = oxa_tools::ShellConfig {
Expand Down
82 changes: 82 additions & 0 deletions oxa/oxa-cli/tests/common/work.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
use oxa_fake::{FakeOpts, FakeServer, ScriptTurn, TestEnv};
use std::{path::Path, process::Command};
pub fn git(env: &TestEnv, dir: &Path, args: &[&str]) -> String {
let out = Command::new("git")
.args(args)
.current_dir(dir)
.env_clear()
.envs(env.envs("http://127.0.0.1:1"))
.env("GIT_AUTHOR_NAME", "Test")
.env("GIT_AUTHOR_EMAIL", "test@example.invalid")
.env("GIT_COMMITTER_NAME", "Test")
.env("GIT_COMMITTER_EMAIL", "test@example.invalid")
.output()
.unwrap();
assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
String::from_utf8_lossy(&out.stdout).trim().into()
}
pub fn setup(env: &TestEnv, done: &str) {
git(env, &env.work(), &["init", "--bare", "remote.git"]);
git(env, &env.work(), &["init", "-b", "main", "project"]);
let project = env.work().join("project");
git(env, &project, &["config", "user.name", "Test"]);
git(env, &project, &["config", "user.email", "test@example.invalid"]);
env.write(
"work/project/.oxa/settings.json",
&format!(r#"{{"done":{done}}}"#),
);
git(env, &project, &["add", "."]);
git(env, &project, &["commit", "-m", "fixture"]);
git(env, &project, &["remote", "add", "origin", "../remote.git"]);
git(env, &project, &["push", "origin", "main"]);
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"}]"#,
);
}
pub fn run(env: &TestEnv, turns: Vec<ScriptTurn>) -> serde_json::Value {
run_args(env, turns, &["work", "../tasks.json"], None)
}
pub fn run_args(
env: &TestEnv,
turns: Vec<ScriptTurn>,
args: &[&str],
path: Option<String>,
) -> serde_json::Value {
run_observed(env, turns, args, path).0
}
pub fn run_observed(
env: &TestEnv,
turns: Vec<ScriptTurn>,
args: &[&str],
path: Option<String>,
) -> (serde_json::Value, Vec<oxa_fake::Recorded>) {
let server = FakeServer::start(turns, FakeOpts::default()).unwrap();
let mut command = Command::new(env!("CARGO_BIN_EXE_oxa"));
command
.args(args)
.current_dir(env.work().join("project"))
.env_clear()
.envs(env.envs(&server.url()));
if let Some(path) = path {
command.env("PATH", path);
}
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
tx.send(command.output().unwrap()).unwrap();
});
let out = rx
.recv_timeout(std::time::Duration::from_secs(90))
.expect("runner finished");
let record = serde_json::from_slice(&out.stdout).unwrap_or_else(|e| {
panic!(
"{e}: {} / {}",
String::from_utf8_lossy(&out.stdout),
String::from_utf8_lossy(&out.stderr)
)
});
(record, server.requests())
}
24 changes: 21 additions & 3 deletions oxa/oxa-cli/tests/work_cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -243,13 +243,31 @@ printf '%s' '{"title":"Synthetic task","body":"Fix the test fixture"}'
assert_eq!(record["outcome"], "nothing_to_do", "{record}");
}
#[test]
fn setup_failure_records_blocked_and_keeps_existing_branch() {
fn branch_checked_out_elsewhere_is_blocked_without_changing_it() {
let env = TestEnv::new();
setup(&env, "[]");
git(&env, &env.work().join("project"), &["branch", "agent/test"]);
let project = env.work().join("project");
git(&env, &project, &["branch", "agent/test"]);
let original = git(&env, &project, &["rev-parse", "agent/test"]);
let occupied = env.work().join("occupied");
git(
&env,
&project,
&["worktree", "add", occupied.to_str().unwrap(), "agent/test"],
);
let record = run(&env, vec![]);
assert_eq!(record["outcome"], "blocked", "{record}");
assert!(record["detail"].as_str().unwrap().contains("already exists"));
assert!(
record["detail"]
.as_str()
.unwrap()
.contains(occupied.to_str().unwrap()),
"{record}"
);
assert!(record["worker"].is_null());
assert!(!env.work().join(".oxa-worktrees/project/test").exists());
assert_eq!(git(&env, &occupied, &["rev-parse", "HEAD"]), original);
assert_eq!(git(&env, &project, &["symbolic-ref", "--short", "HEAD"]), "main");
}

#[test]
Expand Down
Loading
Loading