Skip to content

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.md
index 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 branch
Usage: <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.md
index 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 branch
Usage: <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.rs
index 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 the
branch: 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.rs
index 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 last
let 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 them
if 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 worktrees
if !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(&current, &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.rs
index 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)" path
diff --git a/tests/snapshots/integration__integration_tests__help__help_step_long.snap b/tests/snapshots/integration__integration_tests__help__help_step_long.snap
index 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: wt step [OPTIONS] <COMMAND>
copy-ignored Copy gitignored files to another worktree
for-each [experimental] Run command in each worktree
promote [experimental] Put a branch into the main worktree
- prune Remove worktrees merged into the default branch
+ prune [experimental] Remove worktrees merged into the default branch
relocate [experimental] Move worktrees to expected paths
Options:
diff --git a/tests/snapshots/integration__integration_tests__help__help_step_short.snap b/tests/snapshots/integration__integration_tests__help__help_step_short.snap
index 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: wt step [OPTIONS] <COMMAND>
copy-ignored Copy gitignored files to another worktree
for-each [experimental] Run command in each worktree
promote [experimental] Put a branch into the main worktree
- prune Remove worktrees merged into the default branch
+ prune [experimental] Remove worktrees merged into the default branch
relocate [experimental] Move worktrees to expected paths
Options:
diff --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.snap
index 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 -----
○ merged-a — same commit as main
○ merged-b — same commit as main
-○ orphan-integrated — same commit as main
+○ orphan-integrated (branch only) — same commit as main
↳ 2 worktrees (with branches), 1 branch would be removed (dry run)
diff --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.snap
index 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 -----
-○ No merged worktrees to remove (skipped young-branch, younger than 1h)
+○ 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.snap
index 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 -----
-○ No merged worktrees to remove (skipped orphan-integrated, younger than 1h)
+○ 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.snap
index 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: 246
info:
program: wt
args:
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.snap
new file mode 100644
index 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 -----
+◎ Removing clean-merged worktree & branch in background (same commit as main, _)
+▲ Skipping dirty-merged: ✗ Cannot remove worktree: dirty-merged has uncommitted changes
+↳ Commit or stash changes first, or to lose uncommitted changes, run wt remove --force dirty-merged
+✓ Pruned 1 worktree (with branch)
diff --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.snap
index 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 -----
+○ stale-branch (stale) — same commit as main
○ Skipped young-branch (younger than 1h)
-○ stale-branch — same commit as main
↳ 1 branch would be removed (dry run)
diff --git a/tests/snapshots/integration__integration_tests__step_prune__prune_stale_worktree.snap b/tests/snapshots/integration__integration_tests__step_prune__prune_stale_worktree.snap
index 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: 301
info:
program: wt
args: