Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix(step): gate every staging path on an unmerged index (#3588)
Maximilian Roos321ffe838c49
diff --git a/src/commands/commit.rs b/src/commands/commit.rsindex eabd793be..021d5b2d9 100644--- a/src/commands/commit.rs+++ b/src/commands/commit.rs@@ -266,22 +266,10 @@ impl CommitOptions<'_> {warn_about_untracked_files(&status)?;}- // Stage changes based on mode- match self.stage_mode {- StageMode::All => {- // Stage everything: tracked modifications + untracked files- wt.run_command(&["add", "-A"])- .context("Failed to stage changes")?;- }- StageMode::Tracked => {- // Stage tracked modifications only (no untracked files)- wt.run_command(&["add", "-u"])- .context("Failed to stage tracked changes")?;- }- StageMode::None => {- // Stage nothing - commit only what's already in the index- }- }+ // Stage changes based on mode. Re-gated inside `stage`: the refusal+ // above ran before the pre-commit hooks, and a hook is free to leave+ // unmerged paths behind.+ wt.stage(self.stage_mode, "commit")?;let effective_config = self.ctx.commit_generation();// Skip the approval gate when the LLM isn't configured — the fallbackdiff --git a/src/commands/relocate.rs b/src/commands/relocate.rsindex b0ca537a9..af9090405 100644--- a/src/commands/relocate.rs+++ b/src/commands/relocate.rs@@ -92,7 +92,7 @@ pub struct RelocatedEntry {/// A worktree that was skipped during validation or execution. `reason` is a/// short stable identifier suitable for JSON / scripting (e.g. `"locked"`,-/// `"uncommitted"`, `"target_blocked"`).+/// `"uncommitted"`, `"unmerged"`, `"target_blocked"`).pub struct SkippedEntry {pub branch: String,pub reason: &'static str,@@ -274,14 +274,38 @@ pub fn validate_candidates(let worktree = repo.worktree_at(&candidate.wt.path);if worktree.is_dirty()? && (auto_commit || is_main) {if auto_commit {+ // An unresolved conflict can't be committed by anyone until+ // the user resolves it by hand — the same class of blocker as+ // a locked worktree, so skip this one and carry on with the+ // rest rather than failing the whole run. Checked before the+ // progress line so nothing announces a commit that won't+ // happen. `worktree.stage` below refuses the same state; this+ // is the policy choice of skip over abort, not the guard.+ let unmerged = worktree.unmerged_paths()?;+ if !unmerged.is_empty() {+ let count = unmerged.len();+ let paths = if count == 1 { "path" } else { "paths" };+ eprintln!(+ "{}",+ warning_message(cformat!(+ "Skipping <bold>{branch}</> ({count} {paths} with unresolved conflicts)"+ ))+ );+ eprintln!("{}", format_with_gutter(&unmerged.join("\n"), None));+ skipped.push(SkippedEntry {+ branch: branch.to_string(),+ reason: "unmerged",+ });+ continue;+ }eprintln!("{}",progress_message(cformat!("Committing changes in <bold>{branch}</>...")));- // Stage all changes- worktree- .run_command(&["add", "-A"])- .context("Failed to stage changes")?;+ // Stage all changes. `stage` refuses an unmerged index first —+ // `git add -A` over an unresolved conflict would otherwise+ // commit the `<<<<<<<` markers.+ worktree.stage(StageMode::All, "relocate")?;// Commit using shared pipelinelet project_id = repo.project_identifier().ok();let commit_config = config.commit_generation(project_id.as_deref());diff --git a/src/commands/step/squash.rs b/src/commands/step/squash.rsindex b4b1a06d1..c8f8780a4 100644--- a/src/commands/step/squash.rs+++ b/src/commands/step/squash.rs@@ -90,9 +90,9 @@ pub fn handle_squash(// Squash auto-stages, and `git add -A` would resolve an unmerged path to// whatever is on disk — conflict markers included. Refuse ahead of the// hooks and the LLM call, neither of which is worth running for a squash- // that cannot happen.- repo.worktree_at(&env.worktree_path)- .ensure_no_unmerged_paths("squash")?;+ // that cannot happen. `wt.stage` re-checks with nothing in between.+ let wt = repo.worktree_at(&env.worktree_path);+ wt.ensure_no_unmerged_paths("squash")?;// Squash requires being on a branch (can't squash in detached HEAD)let current_branch = env.require_branch("squash")?.to_string();let ctx = env.context(yes);@@ -159,20 +159,10 @@ pub fn handle_squash(let template_vars = TemplateVars::new().with_target(&integration_target);// Auto-stage changes before running pre-commit hooks so both beta and merge paths behave identically- match stage_mode {- StageMode::All => {- repo.warn_if_auto_staging_untracked()?;- repo.run_command(&["add", "-A"])- .context("Failed to stage changes")?;- }- StageMode::Tracked => {- repo.run_command(&["add", "-u"])- .context("Failed to stage tracked changes")?;- }- StageMode::None => {- // Stage nothing - use what's already staged- }+ if stage_mode == StageMode::All {+ repo.warn_if_auto_staging_untracked()?;}+ wt.stage(stage_mode, "squash")?;// Run pre-commit hooks (user first, then project).if hooks.run() {@@ -193,7 +183,6 @@ pub fn handle_squash(let commit_count = repo.count_commits(&merge_base, "HEAD")?;// Check if there are staged changes in addition to commits- let wt = repo.current_worktree();let has_staged = wt.has_staged_changes()?;// Handle different scenariosdiff --git a/src/git/repository/working_tree.rs b/src/git/repository/working_tree.rsindex 97fba0c21..1b9c88232 100644--- a/src/git/repository/working_tree.rs+++ b/src/git/repository/working_tree.rs@@ -512,7 +512,8 @@ impl<'a> WorkingTree<'a> {/// Fail when the index still holds unresolved conflicts.////// A precondition for the commands that stage on the user's behalf- /// (`wt step commit`, `wt step squash`, `wt merge`). `git add -A` collapses+ /// (`wt step commit`, `wt step squash`, `wt merge`,+ /// `wt step relocate --commit`). `git add -A` collapses/// an unmerged path's three stages into one entry, so it resolves the/// conflict as far as the index is concerned while the file on disk still/// holds `<<<<<<<` markers — and it takes git's own refusal to commit@@ -521,6 +522,12 @@ impl<'a> WorkingTree<'a> {////// `action` names the command the user typed, so each entry point gates in/// its own name rather than in the name of a step it delegates to.+ ///+ /// Every one of those gates refuses *early* — ahead of hooks, approval+ /// prompts, and the LLM call, none of which is worth running for a commit+ /// that cannot happen. The staging itself is guarded by+ /// [`stage`](Self::stage), which runs the same check with nothing between+ /// it and the `git add`.pub fn ensure_no_unmerged_paths(&self, action: &str) -> anyhow::Result<()> {let files = self.unmerged_paths()?;if files.is_empty() {@@ -533,6 +540,51 @@ impl<'a> WorkingTree<'a> {.into())}+ /// Stage the working tree on the user's behalf, refusing an unmerged index.+ ///+ /// **The only path to `git add` against a worktree's real index** — the+ /// other `git add` calls all write a throwaway index via+ /// [`temp_index`](Self::temp_index), which commits nothing. Staging+ /// for the user is what turns an unresolved conflict into a commit full of+ /// `<<<<<<<` markers (see+ /// [`ensure_no_unmerged_paths`](Self::ensure_no_unmerged_paths)), so the+ /// check and the `git add` live in one call rather than as a convention+ /// every caller re-applies. A command that stages through here cannot+ /// forget the gate, and cannot order it after the staging that destroys+ /// the evidence — `git add` collapses the index stages, so a check run+ /// afterwards passes vacuously.+ ///+ /// This is *in addition to* the callers' early refusals, not a replacement+ /// for them: the two guard different windows. `wt step commit` gates+ /// before its `pre-commit` hooks so a doomed commit runs no project+ /// commands — and those hooks are arbitrary project code, free to leave+ /// unmerged paths behind after that gate has passed.+ ///+ /// [`StageMode::None`] stages nothing but is still gated: the caller is+ /// about to commit whatever the index already holds.+ ///+ /// [`StageMode::None`]: crate::config::StageMode::None+ pub fn stage(&self, mode: crate::config::StageMode, action: &str) -> anyhow::Result<()> {+ use crate::config::StageMode;++ self.ensure_no_unmerged_paths(action)?;+ match mode {+ // Stage everything: tracked modifications + untracked files+ StageMode::All => {+ self.run_command(&["add", "-A"])+ .context("Failed to stage changes")?;+ }+ // Stage tracked modifications only (no untracked files)+ StageMode::Tracked => {+ self.run_command(&["add", "-u"])+ .context("Failed to stage tracked changes")?;+ }+ // Commit only what is already in the index+ StageMode::None => {}+ }+ Ok(())+ }+/// Check if this is a linked worktree (vs the main worktree).////// Returns `true` for linked worktrees (created via `git worktree add`),diff --git a/tests/integration_tests/merge.rs b/tests/integration_tests/merge.rsindex 1a4335158..295a24b6d 100644--- a/tests/integration_tests/merge.rs+++ b/tests/integration_tests/merge.rs@@ -3663,6 +3663,70 @@ fn test_step_push_refuses_mid_rebase(mut repo: TestRepo) {);}+/// The early refusal runs *before* the pre-commit hooks, so that a doomed+/// commit runs no project commands — which leaves a window the early refusal+/// structurally cannot see: a hook is arbitrary project code, free to leave an+/// unmerged index behind after that check has passed. `git add -A` would then+/// collapse it and commit the markers. Only the check inside+/// `WorkingTree::stage`, with nothing between it and the `git add`, catches+/// this.+#[rstest]+fn test_step_commit_refuses_hook_created_conflict(mut repo: TestRepo) {+ // A pre-commit hook that conflicts the index. `|| true` so the hook+ // succeeds and the commit proceeds to staging; output suppressed to keep+ // git's own wording out of the snapshot.+ repo.write_project_config(r#"pre-commit = "git merge side >/dev/null 2>&1 || true""#);+ repo.run_git(&["add", ".config/wt.toml"]);+ repo.run_git(&["commit", "-m", "Add project config"]);++ fs::write(repo.root_path().join("conflict.txt"), "base\n").unwrap();+ repo.run_git(&["add", "conflict.txt"]);+ repo.run_git(&["commit", "-m", "Base edit"]);+ repo.run_git(&["checkout", "-b", "side"]);+ fs::write(repo.root_path().join("conflict.txt"), "side\n").unwrap();+ repo.run_git(&["commit", "-am", "Conflicting edit on side"]);+ repo.run_git(&["checkout", "main"]);++ let feature_wt = repo.add_worktree("feature");+ repo.commit_in_worktree(&feature_wt, "conflict.txt", "theirs\n", "Conflicting edit");+ // Something for the commit to do, so it reaches the staging step.+ fs::write(feature_wt.join("other.txt"), "new\n").unwrap();++ let head_before = repo.head_sha_in(&feature_wt);+ let unmerged_before = repo+ .git_command()+ .args(["diff", "--name-only", "--diff-filter=U"])+ .current_dir(&feature_wt)+ .run()+ .unwrap();+ assert!(+ String::from_utf8_lossy(&unmerged_before.stdout)+ .trim()+ .is_empty(),+ "the index must be clean when the early refusal runs — the hook is what conflicts it"+ );++ assert_cmd_snapshot!(+ "step_commit_refuses_hook_created_conflict",+ make_snapshot_cmd(&repo, "step", &["commit", "--yes"], Some(&feature_wt))+ );+ assert_eq!(+ repo.head_sha_in(&feature_wt),+ head_before,+ "the refusal must leave HEAD alone; committing here would commit the conflict markers"+ );+ let committed = repo+ .git_command()+ .args(["show", "HEAD:conflict.txt"])+ .current_dir(&feature_wt)+ .run()+ .unwrap();+ assert!(+ !String::from_utf8_lossy(&committed.stdout).contains("<<<<<<<"),+ "no commit may carry conflict markers"+ );+}+// =============================================================================// JSON output tests// =============================================================================diff --git a/tests/integration_tests/step_relocate.rs b/tests/integration_tests/step_relocate.rsindex ea9bb5835..a3d0df57a 100644--- a/tests/integration_tests/step_relocate.rs+++ b/tests/integration_tests/step_relocate.rs@@ -335,6 +335,141 @@ command = "cat >/dev/null && echo 'chore: auto-commit before relocate'");}+/// Create a worktree for `branch` at `path`, stopped on an unresolved+/// conflict: `git merge side` leaves the index at stages 1–3 with `<<<<<<<` on+/// disk — the state `git add -A` would silently resolve.+fn add_conflicted_worktree(repo: &TestRepo, branch: &str, path: &Path) {+ // A `side` branch that edits the same line, to conflict against.+ fs::write(repo.root_path().join("conflict.txt"), "base\n").unwrap();+ repo.run_git(&["add", "conflict.txt"]);+ repo.run_git(&["commit", "-m", "Base edit"]);+ repo.run_git(&["checkout", "-b", "side"]);+ fs::write(repo.root_path().join("conflict.txt"), "side\n").unwrap();+ repo.run_git(&["commit", "-am", "Conflicting edit on side"]);+ repo.run_git(&["checkout", "main"]);++ repo.run_git(&["worktree", "add", "-b", branch, path.to_str().unwrap()]);+ let git = |args: &[&str]| {+ repo.git_command()+ .current_dir(path)+ .args(args.iter().copied())+ .run()+ .unwrap()+ };+ fs::write(path.join("conflict.txt"), "theirs\n").unwrap();+ git(&["commit", "-am", "Conflicting edit on branch"]);+ // Conflicts: both sides changed the same line.+ git(&["merge", "side"]);++ let unmerged = git(&["diff", "--name-only", "--diff-filter=U"]);+ assert_eq!(+ String::from_utf8_lossy(&unmerged.stdout).trim(),+ "conflict.txt",+ "setup must leave an unresolved conflict in the index"+ );+}++/// Regression: `--commit` stages with `git add -A` before committing, and+/// `git add -A` collapses an unmerged path's index stages — resolving the+/// conflict as far as the index is concerned while `<<<<<<<` is still on disk,+/// and taking git's own refusal to commit with it. So relocate would commit+/// the markers and leave a broken merge looking finished.+#[rstest]+fn test_relocate_refuses_unmerged_paths(repo: TestRepo) {+ let parent = worktree_parent(&repo);+ let wrong_path = parent.join("wrong-location");+ add_conflicted_worktree(&repo, "feature", &wrong_path);+ let head_before = repo.head_sha_in(&wrong_path);++ assert_cmd_snapshot!(make_snapshot_cmd(+ &repo,+ "step",+ &["relocate", "--commit"],+ None+ ));++ assert_eq!(+ repo.head_sha_in(&wrong_path),+ head_before,+ "the refusal must leave HEAD alone; committing here would commit the conflict markers"+ );+ assert!(+ wrong_path.exists() && !parent.join("repo.feature").exists(),+ "the conflicted worktree must stay put rather than move on an uncommitted conflict"+ );+ assert!(+ fs::read_to_string(wrong_path.join("conflict.txt"))+ .unwrap()+ .contains("<<<<<<<"),+ "the conflict must be left for the user to resolve, markers intact"+ );+}++/// An unresolved conflict is a per-worktree blocker the user must fix by hand,+/// like a locked worktree — so it skips that worktree with a stable JSON+/// `reason` and relocates the rest, rather than failing the whole run.+#[rstest]+fn test_relocate_unmerged_skips_only_that_worktree(repo: TestRepo) {+ let parent = worktree_parent(&repo);++ // One worktree stopped on a conflict, one merely dirty (index clean).+ let conflicted_path = parent.join("wrong-conflicted");+ add_conflicted_worktree(&repo, "conflicted", &conflicted_path);+ let clean_path = parent.join("wrong-clean");+ repo.run_git(&[+ "worktree",+ "add",+ "-b",+ "clean",+ clean_path.to_str().unwrap(),+ ]);+ fs::write(clean_path.join("dirty.txt"), "uncommitted").unwrap();++ fs::write(+ repo.test_config_path(),+ r#"+[commit.generation]+command = "cat >/dev/null && echo 'chore: auto-commit before relocate'"+"#,+ )+ .unwrap();++ let output = repo+ .wt_command()+ .args(["step", "relocate", "--commit", "--format=json"])+ .output()+ .unwrap();+ assert!(+ output.status.success(),+ "one conflicted worktree must not fail the whole run; stderr:\n{}",+ String::from_utf8_lossy(&output.stderr)+ );+ let parsed: serde_json::Value = serde_json::from_slice(&output.stdout).expect("valid JSON");++ let skipped = parsed["skipped"].as_array().expect("skipped array");+ assert!(+ skipped+ .iter()+ .any(|s| s["branch"] == "conflicted" && s["reason"] == "unmerged"),+ "conflicted worktree should be skipped with reason \"unmerged\": {parsed}"+ );+ let entries = parsed["entries"].as_array().expect("entries array");+ assert!(+ entries.iter().any(|e| e["branch"] == "clean"),+ "the dirty-but-committable sibling should still relocate: {parsed}"+ );++ // The conflicted worktree stayed put with its conflict; the sibling moved.+ assert!(+ conflicted_path.exists(),+ "conflicted worktree should not move"+ );+ assert!(+ parent.join("repo.clean").exists() && !clean_path.exists(),+ "clean worktree should have relocated"+ );+}+/// Test that --clobber backs up non-worktree paths at target locations#[rstest]fn test_relocate_clobber_backs_up(repo: TestRepo) {diff --git a/tests/snapshots/integration__integration_tests__merge__step_commit_refuses_hook_created_conflict.snap b/tests/snapshots/integration__integration_tests__merge__step_commit_refuses_hook_created_conflict.snapnew file mode 100644index 000000000..3eca92a5a--- /dev/null+++ b/tests/snapshots/integration__integration_tests__merge__step_commit_refuses_hook_created_conflict.snap@@ -0,0 +1,57 @@+---+source: tests/integration_tests/merge.rs+info:+ program: wt+ args:+ - step+ - commit+ - "--yes"+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "500"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"+ PATH: "[PATH]"+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"+ WORKTRUNK_TEST_BASH_INSTALLED: "0"+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"+ WORKTRUNK_TEST_CODEX_INSTALLED: "0"+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"+ WORKTRUNK_TEST_EPOCH: "1735776000"+ WORKTRUNK_TEST_FISH_INSTALLED: "0"+ WORKTRUNK_TEST_GEMINI_INSTALLED: "0"+ WORKTRUNK_TEST_NUSHELL_ENV: "0"+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"+ WORKTRUNK_TEST_PARENT_SHELL: ""+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"+ WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ WORKTRUNK_TEST_ZSH_INSTALLED: "0"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: false+exit_code: 1+----- stdout -----++----- stderr -----+[36m◎[39m [36mRunning pre-commit project hook[39m+[107m [0m [2m[0m[2m[34mgit[0m[2m merge side [0m[2m[36m>[0m[2m/dev/null [0m[2m[33m2[0m[2m>&1 || [0m[2m[34mtrue[0m+[0m[33m▲[39m [33mAuto-staging 1 untracked path:[39m+[107m [0m other.txt+[31m✗[39m [31mCannot commit: 1 path with unresolved conflicts[39m+[107m [0m conflict.txtdiff --git a/tests/snapshots/integration__integration_tests__step_relocate__relocate_refuses_unmerged_paths.snap b/tests/snapshots/integration__integration_tests__step_relocate__relocate_refuses_unmerged_paths.snapnew file mode 100644index 000000000..692e7506b--- /dev/null+++ b/tests/snapshots/integration__integration_tests__step_relocate__relocate_refuses_unmerged_paths.snap@@ -0,0 +1,55 @@+---+source: tests/integration_tests/step_relocate.rs+info:+ program: wt+ args:+ - step+ - relocate+ - "--commit"+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "500"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"+ PATH: "[PATH]"+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"+ WORKTRUNK_TEST_BASH_INSTALLED: "0"+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"+ WORKTRUNK_TEST_CODEX_INSTALLED: "0"+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"+ WORKTRUNK_TEST_EPOCH: "1735776000"+ WORKTRUNK_TEST_FISH_INSTALLED: "0"+ WORKTRUNK_TEST_GEMINI_INSTALLED: "0"+ WORKTRUNK_TEST_NUSHELL_ENV: "0"+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"+ WORKTRUNK_TEST_PARENT_SHELL: ""+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"+ WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ WORKTRUNK_TEST_ZSH_INSTALLED: "0"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: true+exit_code: 0+----- stdout -----++----- stderr -----+[33m▲[39m [33mSkipping [1mfeature[22m (1 path with unresolved conflicts)[39m+[107m [0m conflict.txt++[2m○[22m Skipped 1 worktree