diff --git a/oxa/CHANGELOG.md b/oxa/CHANGELOG.md index 92557ad7..c5277b1a 100644 --- a/oxa/CHANGELOG.md +++ b/oxa/CHANGELOG.md @@ -2,6 +2,9 @@ ## [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). ### Added - `oxa work --pr N --model MODEL` (#1019): the unattended packet for a pull request carries its title, body, reviews, issue comments and the names of failing checks at the current head, and the task branch is the pull request's own head branch. Review text and check names are labelled as data and bounded (reviews to 16 KiB, 40 check names); only failing checks travel, never passing ones. Malformed review or check lists are refused, never silently dropped. diff --git a/oxa/docs/work.md b/oxa/docs/work.md index e3b57c7a..cfdca620 100644 --- a/oxa/docs/work.md +++ b/oxa/docs/work.md @@ -205,7 +205,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/src/netguard.rs b/oxa/oxa-cli/src/netguard.rs index da65b45c..6c4a4bcc 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 4c38f634..b794d61f 100644 --- a/oxa/oxa-cli/src/work_checks.rs +++ b/oxa/oxa-cli/src/work_checks.rs @@ -65,27 +65,36 @@ pub(crate) fn run( SupervisorOperation::Checkout { branch, create, + adopted, normalize, } => { - let sandbox = crate::netguard::with_net(Arc::new(b), &settings); + // 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 mut command = if let Some(update) = normalize { // Materialize filters first, then advance under the caller's Git - // worktree hold. All reference and checkout hooks stay sandboxed. - format!("git --no-replace-objects read-tree --reset -u HEAD && test $(git symbolic-ref --quiet {}; echo $?) = 1 && git --no-replace-objects update-ref --no-deref {} {} {} && checkout_head=$(git rev-parse HEAD) && git hook run --ignore-missing post-checkout -- \"$checkout_head\" \"$checkout_head\" 0", sh_quote(&update.reference), sh_quote(&update.reference), sh_quote(&update.new), sh_quote(&update.old)) + // worktree hold, with the selected checkout callback policy. + format!("{git} read-tree --reset -u HEAD && test $({git} symbolic-ref --quiet {}; echo $?) = 1 && {git} update-ref --no-deref {} {} {} && checkout_head=$({git} rev-parse HEAD) && {git} hook run --ignore-missing post-checkout -- \"$checkout_head\" \"$checkout_head\" 0", sh_quote(&update.reference), sh_quote(&update.reference), sh_quote(&update.new), sh_quote(&update.old)) } else { - "git --no-replace-objects checkout HEAD -- .".into() + format!("{git} checkout HEAD -- .") }; if create { - command.push_str(&format!( - " && git --no-replace-objects checkout -b {} HEAD", - sh_quote(&branch) - )); + command.push_str(&format!(" && {git} checkout -b {} HEAD", sh_quote(&branch))); } let spec = ExecSpec { command, cwd: root, writable: true, - net: sandbox.network(), + net: !adopted && sandbox.network(), timeout_s: Some(600), env: git_environment(), }; @@ -104,17 +113,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())?; @@ -124,7 +133,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!( @@ -144,12 +153,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 { @@ -170,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 { diff --git a/oxa/oxa-cli/tests/work_continue.rs b/oxa/oxa-cli/tests/work_continue.rs index 643773b7..7d7ab3ca 100644 --- a/oxa/oxa-cli/tests/work_continue.rs +++ b/oxa/oxa-cli/tests/work_continue.rs @@ -74,6 +74,383 @@ fn existing_branch_fast_forwards_to_base_before_agent() { &["merge-base", "--is-ancestor", "main", "agent/test"], ); } + +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"]); + 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"]) +} + +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 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()) +} + +#[test] +fn fresh_worktree_starts_at_the_published_task_branch_head() { + let env = TestEnv::new(); + let pushed = published_task(&env); + 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); + assert_eq!(git(&env, tree(&record), &["rev-parse", "HEAD"]), pushed); + assert_eq!( + git(&env, tree(&record), &["symbolic-ref", "--quiet", "HEAD"]), + "refs/heads/agent/test" + ); + // 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 ordinary_fresh_branch_reference_hooks_run_only_in_the_task_sandbox() { + use std::os::unix::fs::PermissionsExt; + let env = TestEnv::new(); + 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", + ); + 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 published_checkout_hooks_have_neither_network_nor_github_credentials() { + published_checkout_policy(false); +} + +#[test] +fn normalizing_an_adopted_checkout_preserves_the_restricted_policy() { + published_checkout_policy(true); +} + +fn published_checkout_policy(normalize: bool) { + use std::os::unix::fs::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"); + 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"]); + let normalized_base = normalize.then(|| { + let (_, fetched) = lag_existing_base(&env); + git( + &env, + &project(&env), + &["checkout", "-b", "published", "origin/agent/test"], + ); + git(&env, &project(&env), &["merge", "--no-edit", "origin/main"]); + git(&env, &project(&env), &["push", "origin", "published:agent/test"]); + git(&env, &project(&env), &["checkout", "source"]); + git(&env, &project(&env), &["branch", "-D", "published"]); + git(&env, &project(&env), &["fetch", "origin"]); + fetched + }); + 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", + ); + std::fs::set_permissions(hook, std::fs::Permissions::from_mode(0o755)).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, + vec![ScriptTurn::text("nothing")], + &["work", "../tasks.json"], + Some(path), + |command| { + command.envs([ + ("OXA_TEST_ISOLATION", "0"), + ("GH_TOKEN", "SYNTH_AMBIENT_CREDENTIAL"), + ("GITHUB_TOKEN", "SYNTH_AMBIENT_CREDENTIAL"), + ]); + }, + ); + assert_eq!(record["outcome"], "done", "{record}"); + if let Some(fetched) = normalized_base { + assert_eq!(record["base_sha"], fetched, "{record}"); + assert_eq!(git(&env, &project(&env), &["rev-parse", "main"]), fetched); + } + assert!(!tree(&record).join("adopted-hook-ran").exists(), "{record}"); + assert!( + !tree(&record).join("adopted-hook-credentials").exists(), + "checkout exposed credentials: {record}" + ); + 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(), + "checkout retained host networking" + ); +} + +#[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"], + ); + 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", "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"]); + // 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, + vec![ + ScriptTurn::tool( + "edit", + "write", + r#"{"path":"changed.txt","content":"synthetic change\n"}"#, + ), + ScriptTurn::text("done"), + ], + &["work", "../tasks.json"], + 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_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 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(); + 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 ordinary_branch_creation_keeps_required_reference_hook_policy() { + use std::os::unix::fs::PermissionsExt; + let env = TestEnv::new(); + 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); + 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(); + 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] fn divergent_branch_gets_normal_merge_without_losing_task_commit() { let env = TestEnv::new(); @@ -256,6 +633,10 @@ fn resumed_old_merge_is_told_to_integrate_the_newly_captured_base() { fn lagging_base(env: &TestEnv) -> (String, String) { setup(env, "[]"); + lag_existing_base(env) +} + +fn lag_existing_base(env: &TestEnv) -> (String, String) { // The source checkout pulled `main` while its local branch stayed behind. let stale = git(env, &project(env), &["rev-parse", "main"]); commit_file(env, "fetched.txt", "fetched base\n"); @@ -520,10 +901,23 @@ 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, + vec![ScriptTurn::text("nothing")], + &["work", "../tasks.json"], + Some(synthetic_github_path(&env)), + |command| { + command.envs([ + ("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!( @@ -531,6 +925,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] diff --git a/oxa/oxa-work/src/committed.rs b/oxa/oxa-work/src/committed.rs index 207d2226..3d2deabb 100644 --- a/oxa/oxa-work/src/committed.rs +++ b/oxa/oxa-work/src/committed.rs @@ -121,6 +121,7 @@ pub(crate) fn verify_commit( operation: SupervisorOperation::Checkout { branch: saved.task.branch.clone(), create: false, + adopted: false, normalize: None, }, }, diff --git a/oxa/oxa-work/src/lib.rs b/oxa/oxa-work/src/lib.rs index 4655b380..00b143e1 100644 --- a/oxa/oxa-work/src/lib.rs +++ b/oxa/oxa-work/src/lib.rs @@ -733,6 +733,8 @@ pub enum SupervisorOperation { Checkout { branch: String, create: bool, + #[serde(default)] + adopted: bool, #[serde(default, skip_serializing_if = "Option::is_none")] normalize: Option, }, diff --git a/oxa/oxa-work/src/tree.rs b/oxa/oxa-work/src/tree.rs index 4f9cbff2..7c6c659f 100644 --- a/oxa/oxa-work/src/tree.rs +++ b/oxa/oxa-work/src/tree.rs @@ -271,6 +271,63 @@ 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. Selection is read-only; the sandboxed checkout materializes +/// this commit using the adopted-tip execution 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(None), + out => String::from_utf8_lossy(&out.stdout).trim().to_owned(), + }; + 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(); + heads.push(tip); + } + heads.sort(); + heads.dedup(); + let [tip] = heads.as_slice() else { + return Ok(None); + }; + 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())) +} + /// Preserve an earlier, finished round in place while releasing its branch for this round. fn release_review_branch( repo: &Path, @@ -381,6 +438,11 @@ pub(crate) fn prepare( Some(1) => true, _ => return Err(String::from_utf8_lossy(&exists.stderr).into()), }; + 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", @@ -389,11 +451,17 @@ pub(crate) fn prepare( "add", "--no-checkout", ]; + // 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 { 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))?; @@ -406,6 +474,7 @@ pub(crate) fn prepare( operation: SupervisorOperation::Checkout { branch: task.branch.clone(), create, + adopted: published.is_some(), normalize: holder.as_ref().map(|(_, update)| update.clone()), }, },