Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix: improve wt step prune reliability and UX (#1234)
Maximilian Roos44ce42e4a8be
diff --git a/docs/content/step.md b/docs/content/step.mdindex d9cc85d3d..95d15d703 100644--- a/docs/content/step.md+++ b/docs/content/step.md@@ -65,7 +65,7 @@ Usage: <b><span class=c>wt step</span></b> <span class=c>[OPTIONS]</span> <span<b><span class=c>copy-ignored</span></b> Copy gitignored files to another worktree<b><span class=c>for-each</span></b> [experimental] Run command in each worktree<b><span class=c>promote</span></b> [experimental] Put a branch into the main worktree- <b><span class=c>prune</span></b> Remove worktrees merged into the default branch+ <b><span class=c>prune</span></b> [experimental] Remove worktrees merged into the default branch<b><span class=c>relocate</span></b> [experimental] Move worktrees to expected paths<b><span class=g>Options:</span></b>@@ -451,7 +451,7 @@ Usage: <b><span class=c>wt step for-each</span></b> <span class=c>[OPTIONS]</spa## wt step prune-Remove worktrees merged into the default branch.+[experimental] Remove worktrees merged into the default branch.Bulk-removes worktrees and branches that are integrated into the default branch, using the same criteria as `wt remove`'s branch cleanup. Stale worktree entries are cleaned up too.@@ -485,7 +485,7 @@ wt step prune### Command reference{% terminal() %}-wt step prune - Remove worktrees merged into the default branch+wt step prune - [experimental] Remove worktrees merged into the default branchUsage: <b><span class=c>wt step prune</span></b> <span class=c>[OPTIONS]</span>diff --git a/skills/worktrunk/reference/step.md b/skills/worktrunk/reference/step.mdindex 0fbd596f8..a21aaccce 100644--- a/skills/worktrunk/reference/step.md+++ b/skills/worktrunk/reference/step.md@@ -50,7 +50,7 @@ Usage: <b><span class=c>wt step</span></b> <span class=c>[OPTIONS]</span> <span<b><span class=c>copy-ignored</span></b> Copy gitignored files to another worktree<b><span class=c>for-each</span></b> [experimental] Run command in each worktree<b><span class=c>promote</span></b> [experimental] Put a branch into the main worktree- <b><span class=c>prune</span></b> Remove worktrees merged into the default branch+ <b><span class=c>prune</span></b> [experimental] Remove worktrees merged into the default branch<b><span class=c>relocate</span></b> [experimental] Move worktrees to expected paths<b><span class=g>Options:</span></b>@@ -427,7 +427,7 @@ Usage: <b><span class=c>wt step for-each</span></b> <span class=c>[OPTIONS]</spa## wt step prune-Remove worktrees merged into the default branch.+[experimental] Remove worktrees merged into the default branch.Bulk-removes worktrees and branches that are integrated into the default branch, using the same criteria as `wt remove`'s branch cleanup. Stale worktree entries are cleaned up too.@@ -460,7 +460,7 @@ wt step prune### Command reference-wt step prune - Remove worktrees merged into the default branch+wt step prune - [experimental] Remove worktrees merged into the default branchUsage: <b><span class=c>wt step prune</span></b> <span class=c>[OPTIONS]</span>diff --git a/src/cli/step.rs b/src/cli/step.rsindex f65022ed0..71b1d41a7 100644--- a/src/cli/step.rs+++ b/src/cli/step.rs@@ -423,7 +423,7 @@ Gitignored files are swapped along with the branches so each worktree keeps thebranch: Option<String>,},- /// Remove worktrees merged into the default branch+ /// \[experimental\] Remove worktrees merged into the default branch#[command(after_long_help = r#"Bulk-removes worktrees and branches that are integrated into the default branch, using the same criteria as `wt remove`'s branch cleanup. Stale worktree entries are cleaned up too.diff --git a/src/commands/step_commands.rs b/src/commands/step_commands.rsindex e06166848..d39598df1 100644--- a/src/commands/step_commands.rs+++ b/src/commands/step_commands.rs@@ -1304,7 +1304,6 @@ pub fn step_prune(dry_run: bool, yes: bool, min_age: &str, foreground: bool) ->path: Option<PathBuf>,/// Current worktree, other worktree, or branch-only (no worktree)kind: CandidateKind,- reason_desc: String,}enum CandidateKind {Current,@@ -1356,7 +1355,29 @@ pub fn step_prune(dry_run: bool, yes: bool, min_age: &str, foreground: bool) ->parts.join(", ")}- let mut candidates: Vec<Candidate> = Vec::new();+ // For non-dry-run, approve hooks upfront so we can remove inline.+ let run_hooks = if dry_run {+ false // unused in dry-run path+ } else {+ let env = CommandEnv::for_action_branchless()?;+ let ctx = env.context(yes);+ let approved = approve_hooks(+ &ctx,+ &[+ HookType::PreRemove,+ HookType::PostRemove,+ HookType::PostSwitch,+ ],+ )?;+ if !approved {+ eprintln!("{}", info_message("Commands declined, continuing removal"));+ }+ approved+ };++ let mut candidates: Vec<Candidate> = Vec::new(); // dry-run collects here+ let mut removed: Vec<Candidate> = Vec::new(); // non-dry-run tracks removals+ let mut deferred_current: Option<Candidate> = None; // current worktree removed lastlet mut skipped_young: Vec<String> = Vec::new();// Track branches seen via worktree entries so we don't double-count.// Pre-seed with the default branch to prevent it from being pruned@@ -1364,6 +1385,52 @@ pub fn step_prune(dry_run: bool, yes: bool, min_age: &str, foreground: bool) ->let mut seen_branches: std::collections::HashSet<String> =default_branch.iter().cloned().collect();+ /// Try to remove a candidate immediately. Returns Ok(true) if removed,+ /// Ok(false) if skipped (preparation error), Err on execution error.+ fn try_remove(+ candidate: &Candidate,+ repo: &Repository,+ config: &UserConfig,+ foreground: bool,+ run_hooks: bool,+ ) -> anyhow::Result<bool> {+ let target = match candidate.kind {+ CandidateKind::Current => RemoveTarget::Current,+ CandidateKind::BranchOnly => RemoveTarget::Branch(+ candidate+ .branch+ .as_ref()+ .context("BranchOnly candidate missing branch")?,+ ),+ CandidateKind::Other => match &candidate.branch {+ Some(branch) => RemoveTarget::Branch(branch),+ None => RemoveTarget::Path(+ candidate+ .path+ .as_ref()+ .context("detached candidate missing path")?,+ ),+ },+ };+ let plan = match repo.prepare_worktree_removal(+ target,+ BranchDeletionMode::SafeDelete,+ false,+ config,+ ) {+ Ok(plan) => plan,+ Err(e) => {+ eprintln!(+ "{}",+ warning_message(format!("Skipping {}: {e:#}", candidate.label))+ );+ return Ok(false);+ }+ };+ handle_remove_output(&plan, !foreground, run_hooks)?;+ Ok(true)+ }+for wt in &worktrees {// Track branches so the orphan scan doesn't re-discover themif let Some(branch) = &wt.branch {@@ -1388,13 +1455,26 @@ pub fn step_prune(dry_run: bool, yes: bool, min_age: &str, foreground: bool) ->let (effective_target, reason) =repo.integration_reason(branch, &integration_target)?;if let Some(reason) = reason {- candidates.push(Candidate {+ let candidate = Candidate {label: branch.clone(),branch: Some(branch.clone()),path: None,kind: CandidateKind::BranchOnly,- reason_desc: format!("{} {}", reason.description(), effective_target),- });+ };+ if dry_run {+ eprintln!(+ "{}",+ info_message(cformat!(+ "<bold>{}</> (stale) — {} {}",+ branch,+ reason.description(),+ effective_target+ ))+ );+ candidates.push(candidate);+ } else if try_remove(&candidate, &repo, &config, foreground, run_hooks)? {+ removed.push(candidate);+ }}}continue;@@ -1447,7 +1527,7 @@ pub fn step_prune(dry_run: bool, yes: bool, min_age: &str, foreground: bool) ->let wt_path = dunce::canonicalize(&wt.path).unwrap_or(wt.path.clone());let is_current = wt_path == current_root;- candidates.push(Candidate {+ let candidate = Candidate {branch: if wt.detached { None } else { wt.branch.clone() },label,path: Some(wt.path.clone()),@@ -1456,8 +1536,23 @@ pub fn step_prune(dry_run: bool, yes: bool, min_age: &str, foreground: bool) ->} else {CandidateKind::Other},- reason_desc: format!("{} {}", reason.description(), effective_target),- });+ };+ if dry_run {+ eprintln!(+ "{}",+ info_message(cformat!(+ "<bold>{}</> — {} {}",+ candidate.label,+ reason.description(),+ effective_target+ ))+ );+ candidates.push(candidate);+ } else if is_current {+ deferred_current = Some(candidate);+ } else if try_remove(&candidate, &repo, &config, foreground, run_hooks)? {+ removed.push(candidate);+ }}// Also scan local branches that don't have a worktree entry@@ -1487,27 +1582,30 @@ pub fn step_prune(dry_run: bool, yes: bool, min_age: &str, foreground: bool) ->}}}- candidates.push(Candidate {+ let candidate = Candidate {label: branch.clone(),branch: Some(branch),path: None,kind: CandidateKind::BranchOnly,- reason_desc: format!("{} {}", reason.description(), effective_target),- });+ };+ if dry_run {+ eprintln!(+ "{}",+ info_message(cformat!(+ "<bold>{}</> (branch only) — {} {}",+ candidate.label,+ reason.description(),+ effective_target+ ))+ );+ candidates.push(candidate);+ } else if try_remove(&candidate, &repo, &config, foreground, run_hooks)? {+ removed.push(candidate);+ }}}- if candidates.is_empty() {- let msg = if skipped_young.is_empty() {- "No merged worktrees to remove".to_string()- } else {- let names = skipped_young.join(", ");- format!("No merged worktrees to remove (skipped {names}, younger than {min_age})")- };- eprintln!("{}", info_message(msg));- return Ok(());- }-+ // Report skipped worktreesif !skipped_young.is_empty() {let names = skipped_young.join(", ");eprintln!(@@ -1517,11 +1615,11 @@ pub fn step_prune(dry_run: bool, yes: bool, min_age: &str, foreground: bool) ->}if dry_run {- for c in &candidates {- eprintln!(- "{}",- info_message(cformat!("<bold>{}</> — {}", c.label, c.reason_desc,))- );+ if candidates.is_empty() {+ if skipped_young.is_empty() {+ eprintln!("{}", info_message("No merged worktrees to remove"));+ }+ return Ok(());}eprintln!("{}",@@ -1533,56 +1631,24 @@ pub fn step_prune(dry_run: bool, yes: bool, min_age: &str, foreground: bool) ->return Ok(());}- // Approve hooks- let env = CommandEnv::for_action_branchless()?;- let ctx = env.context(yes);- let run_hooks = approve_hooks(- &ctx,- &[- HookType::PreRemove,- HookType::PostRemove,- HookType::PostSwitch,- ],- )?;- if !run_hooks {- eprintln!("{}", info_message("Commands declined, continuing removal"));- }-- // Sort: current worktree last so cd-to-primary happens after other removals- candidates.sort_by_key(|c| matches!(c.kind, CandidateKind::Current));-- // Prepare removal plans- let mut plans: Vec<super::worktree::RemoveResult> = Vec::new();- for c in &candidates {- let target = match c.kind {- CandidateKind::Current => RemoveTarget::Current,- CandidateKind::BranchOnly => RemoveTarget::Branch(- c.branch- .as_ref()- .context("BranchOnly candidate missing branch")?,- ),- CandidateKind::Other => match &c.branch {- Some(branch) => RemoveTarget::Branch(branch),- None => {- RemoveTarget::Path(c.path.as_ref().context("detached candidate missing path")?)- }- },- };- let plan =- repo.prepare_worktree_removal(target, BranchDeletionMode::SafeDelete, false, &config)?;- plans.push(plan);+ // Remove deferred current worktree last (cd-to-primary happens here)+ if let Some(current) = deferred_current+ && try_remove(¤t, &repo, &config, foreground, run_hooks)?+ {+ removed.push(current);}- // Execute removals (current worktree is last due to sort above)- for result in &plans {- handle_remove_output(result, !foreground, run_hooks)?;+ if removed.is_empty() {+ if skipped_young.is_empty() {+ eprintln!("{}", info_message("No merged worktrees to remove"));+ }+ } else {+ eprintln!(+ "{}",+ success_message(format!("Pruned {}", prune_summary(&removed)))+ );}- eprintln!(- "{}",- success_message(format!("Pruned {}", prune_summary(&candidates)))- );-Ok(())}diff --git a/tests/integration_tests/step_prune.rs b/tests/integration_tests/step_prune.rsindex aad0981b9..2f71f22d6 100644--- a/tests/integration_tests/step_prune.rs+++ b/tests/integration_tests/step_prune.rs@@ -329,6 +329,36 @@ fn test_prune_min_age_passes(mut repo: TestRepo) {assert_cmd_snapshot!(cmd);}+/// Prune skips worktrees with uncommitted changes+#[rstest]+fn test_prune_skips_dirty(mut repo: TestRepo) {+ repo.commit("initial");++ // Merged worktree with uncommitted changes — should be skipped+ let wt_path = repo.add_worktree("dirty-merged");+ std::fs::write(wt_path.join("scratch.txt"), "wip").unwrap();++ // Clean merged worktree — should be pruned+ repo.add_worktree("clean-merged");++ assert_cmd_snapshot!(make_snapshot_cmd(+ &repo,+ "step",+ &["prune", "--yes", "--min-age=0s"],+ None+ ));++ // Dirty worktree still exists+ assert!(wt_path.exists(), "Dirty worktree should be skipped");++ // Clean worktree removed+ let clean_path = repo.root_path().parent().unwrap().join("repo.clean-merged");+ assert!(+ !clean_path.exists(),+ "Clean merged worktree should be removed"+ );+}+/// Dry-run with mixed worktrees + orphan branches shows both counts.////// Exercises the "N worktrees, M branches would be removed (dry run)" pathdiff --git a/tests/snapshots/integration__integration_tests__help__help_step_long.snap b/tests/snapshots/integration__integration_tests__help__help_step_long.snapindex 45211261e..a1f6242ed 100644--- a/tests/snapshots/integration__integration_tests__help__help_step_long.snap+++ b/tests/snapshots/integration__integration_tests__help__help_step_long.snap@@ -45,7 +45,7 @@ Usage: [1m[36mwt step[0m [36m[OPTIONS][0m [36m<COMMAND>[0m[1m[36mcopy-ignored[0m Copy gitignored files to another worktree[1m[36mfor-each[0m [experimental] Run command in each worktree[1m[36mpromote[0m [experimental] Put a branch into the main worktree- [1m[36mprune[0m Remove worktrees merged into the default branch+ [1m[36mprune[0m [experimental] Remove worktrees merged into the default branch[1m[36mrelocate[0m [experimental] Move worktrees to expected paths[1m[32mOptions:[0mdiff --git a/tests/snapshots/integration__integration_tests__help__help_step_short.snap b/tests/snapshots/integration__integration_tests__help__help_step_short.snapindex 72db40629..7cfa3bbb9 100644--- a/tests/snapshots/integration__integration_tests__help__help_step_short.snap+++ b/tests/snapshots/integration__integration_tests__help__help_step_short.snap@@ -43,7 +43,7 @@ Usage: [1m[36mwt step[0m [36m[OPTIONS][0m [36m<COMMAND>[0m[1m[36mcopy-ignored[0m Copy gitignored files to another worktree[1m[36mfor-each[0m [experimental] Run command in each worktree[1m[36mpromote[0m [experimental] Put a branch into the main worktree- [1m[36mprune[0m Remove worktrees merged into the default branch+ [1m[36mprune[0m [experimental] Remove worktrees merged into the default branch[1m[36mrelocate[0m [experimental] Move worktrees to expected paths[1m[32mOptions:[0mdiff --git a/tests/snapshots/integration__integration_tests__step_prune__prune_dry_run_mixed_worktrees_and_branches.snap b/tests/snapshots/integration__integration_tests__step_prune__prune_dry_run_mixed_worktrees_and_branches.snapindex f83c36632..16997ca58 100644--- a/tests/snapshots/integration__integration_tests__step_prune__prune_dry_run_mixed_worktrees_and_branches.snap+++ b/tests/snapshots/integration__integration_tests__step_prune__prune_dry_run_mixed_worktrees_and_branches.snap@@ -44,5 +44,5 @@ exit_code: 0----- stderr -----[2m○[22m [1mmerged-a[22m — same commit as main[2m○[22m [1mmerged-b[22m — same commit as main-[2m○[22m [1morphan-integrated[22m — same commit as main+[2m○[22m [1morphan-integrated[22m (branch only) — same commit as main[2m↳[22m [2m2 worktrees (with branches), 1 branch would be removed (dry run)[22mdiff --git a/tests/snapshots/integration__integration_tests__step_prune__prune_min_age_skips_young.snap b/tests/snapshots/integration__integration_tests__step_prune__prune_min_age_skips_young.snapindex 2ed0e5c2f..0f83b75a3 100644--- a/tests/snapshots/integration__integration_tests__step_prune__prune_min_age_skips_young.snap+++ b/tests/snapshots/integration__integration_tests__step_prune__prune_min_age_skips_young.snap@@ -42,4 +42,4 @@ exit_code: 0----- stdout ---------- stderr ------[2m○[22m No merged worktrees to remove (skipped young-branch, younger than 1h)+[2m○[22m Skipped young-branch (younger than 1h)diff --git a/tests/snapshots/integration__integration_tests__step_prune__prune_orphan_branch_min_age.snap b/tests/snapshots/integration__integration_tests__step_prune__prune_orphan_branch_min_age.snapindex adb9a17b4..8a55e932c 100644--- a/tests/snapshots/integration__integration_tests__step_prune__prune_orphan_branch_min_age.snap+++ b/tests/snapshots/integration__integration_tests__step_prune__prune_orphan_branch_min_age.snap@@ -42,4 +42,4 @@ exit_code: 0----- stdout ---------- stderr ------[2m○[22m No merged worktrees to remove (skipped orphan-integrated, younger than 1h)+[2m○[22m Skipped orphan-integrated (younger than 1h)diff --git a/tests/snapshots/integration__integration_tests__step_prune__prune_orphan_branches.snap b/tests/snapshots/integration__integration_tests__step_prune__prune_orphan_branches.snapindex e1195c2e3..93df5af9f 100644--- a/tests/snapshots/integration__integration_tests__step_prune__prune_orphan_branches.snap+++ b/tests/snapshots/integration__integration_tests__step_prune__prune_orphan_branches.snap@@ -1,6 +1,5 @@---source: tests/integration_tests/step_prune.rs-assertion_line: 246info:program: wtargs:diff --git a/tests/snapshots/integration__integration_tests__step_prune__prune_skips_dirty.snap b/tests/snapshots/integration__integration_tests__step_prune__prune_skips_dirty.snapnew file mode 100644index 000000000..28356057b--- /dev/null+++ b/tests/snapshots/integration__integration_tests__step_prune__prune_skips_dirty.snap@@ -0,0 +1,49 @@+---+source: tests/integration_tests/step_prune.rs+info:+ program: wt+ args:+ - step+ - prune+ - "--yes"+ - "--min-age=0s"+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ 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_EDITOR: ""+ GIT_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"+ PATH: "[PATH]"+ PSModulePath: ""+ RUST_LOG: warn+ SHELL: ""+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"+ WORKTRUNK_TEST_EPOCH: "1735776000"+ WORKTRUNK_TEST_NUSHELL_ENV: "0"+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: true+exit_code: 0+----- stdout -----++----- stderr -----+[36m◎ Removing [1mclean-merged[22m worktree & branch in background (same commit as [1mmain[22m,[39m [2m_[22m[36m)[39m+[33m▲[39m [33mSkipping dirty-merged: [31m✗[39m [31mCannot remove worktree: [1mdirty-merged[22m has uncommitted changes[39m+[2m↳[22m [2mCommit or stash changes first, or to lose uncommitted changes, run [90mwt remove --force dirty-merged[39m[22m[39m+[32m✓[39m [32mPruned 1 worktree (with branch)[39mdiff --git a/tests/snapshots/integration__integration_tests__step_prune__prune_stale_plus_young.snap b/tests/snapshots/integration__integration_tests__step_prune__prune_stale_plus_young.snapindex 3fe23bb28..24a8fc7d2 100644--- a/tests/snapshots/integration__integration_tests__step_prune__prune_stale_plus_young.snap+++ b/tests/snapshots/integration__integration_tests__step_prune__prune_stale_plus_young.snap@@ -42,6 +42,6 @@ exit_code: 0----- stdout ---------- stderr -----+[2m○[22m [1mstale-branch[22m (stale) — same commit as main[2m○[22m Skipped young-branch (younger than 1h)-[2m○[22m [1mstale-branch[22m — same commit as main[2m↳[22m [2m1 branch would be removed (dry run)[22mdiff --git a/tests/snapshots/integration__integration_tests__step_prune__prune_stale_worktree.snap b/tests/snapshots/integration__integration_tests__step_prune__prune_stale_worktree.snapindex 6afd86ea3..39ccfcf33 100644--- a/tests/snapshots/integration__integration_tests__step_prune__prune_stale_worktree.snap+++ b/tests/snapshots/integration__integration_tests__step_prune__prune_stale_worktree.snap@@ -1,6 +1,5 @@---source: tests/integration_tests/step_prune.rs-assertion_line: 301info:program: wtargs: