Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

refactor(remove): move the stale-entry prune from planning to execution (#3658)

Maximilian Roos66810a311555
diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rs
index a9733a6c2..097b35681 100644
--- a/src/commands/picker/mod.rs
+++ b/src/commands/picker/mod.rs
@@ -2815,7 +2815,7 @@ pub mod tests {
let result = RemovalPlan::BranchOnly {
branch_name: "feature".to_string(),
deletion_mode: BranchDeletionMode::SafeDelete,
- pruned: false,
+ prune_entry: None,
target_branch: None,
integration_reason: None,
branch_checked_out_at: None,
@@ -2842,7 +2842,7 @@ pub mod tests {
let result = RemovalPlan::BranchOnly {
branch_name: "unmerged".to_string(),
deletion_mode: BranchDeletionMode::SafeDelete,
- pruned: false,
+ prune_entry: None,
target_branch: None,
integration_reason: None,
branch_checked_out_at: None,
@@ -3754,7 +3754,7 @@ pub mod tests {
let branch_only = RemovalPlan::BranchOnly {
branch_name: "orphan".to_string(),
deletion_mode: BranchDeletionMode::SafeDelete,
- pruned: false,
+ prune_entry: None,
target_branch: None,
integration_reason: None,
branch_checked_out_at: None,
@@ -4211,7 +4211,7 @@ pub mod tests {
let present_branch = RemovalPlan::BranchOnly {
branch_name: "live-branch".to_string(),
deletion_mode: BranchDeletionMode::SafeDelete,
- pruned: false,
+ prune_entry: None,
target_branch: None,
integration_reason: None,
branch_checked_out_at: None,
@@ -4221,7 +4221,7 @@ pub mod tests {
let gone_branch = RemovalPlan::BranchOnly {
branch_name: "no-such-branch".to_string(),
deletion_mode: BranchDeletionMode::SafeDelete,
- pruned: false,
+ prune_entry: None,
target_branch: None,
integration_reason: None,
branch_checked_out_at: None,
@@ -4242,7 +4242,7 @@ pub mod tests {
RemovalPlan::BranchOnly {
branch_name: "b".to_string(),
deletion_mode: mode,
- pruned: false,
+ prune_entry: None,
target_branch: None,
integration_reason: integration,
branch_checked_out_at: None,
@@ -4320,7 +4320,7 @@ pub mod tests {
!super::removal_targets_current_worktree(&RemovalPlan::BranchOnly {
branch_name: "feature".to_string(),
deletion_mode: BranchDeletionMode::SafeDelete,
- pruned: false,
+ prune_entry: None,
target_branch: None,
integration_reason: None,
branch_checked_out_at: None,
diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rs
index ce8e19362..0d22504f4 100644
--- a/src/commands/repository_ext.rs
+++ b/src/commands/repository_ext.rs
@@ -42,7 +42,11 @@ pub trait RepositoryCliExt {
/// names.
///
/// Returns a `RemovalPlan` describing what will be removed. The actual
- /// removal is performed by the output handler.
+ /// removal is performed by the output handler. Planning is a pure read —
+ /// every mutation, including unregistering a stale worktree entry
+ /// (`RemovalPlan::BranchOnly::prune_entry`), happens at execution — so
+ /// callers may plan speculatively: on a `--dry-run` scan, before an
+ /// approval prompt, or on the picker's event loop.
///
/// `current_path` overrides process-CWD discovery for determining which
/// worktree is "current". Pass `None` for normal CLI usage (discovers from
@@ -142,11 +146,12 @@ impl RepositoryCliExt for Repository {
is_current: bool,
},
BranchOnly {
- /// Path of the stale worktree entry this fell back from, when
- /// the fallback was a prune. `None` when the branch has no
- /// worktree entry at all, which is also the only case with no
- /// sibling to check — a branch that has one resolves to
- /// `Worktree` above, or, named as a `Branch` target, errors.
+ /// Path of the stale worktree entry this fell back from,
+ /// carried into the plan for execution-time pruning. `None`
+ /// when the branch has no worktree entry at all, which is also
+ /// the only case with no sibling to check — a branch that has
+ /// one resolves to `Worktree` above, or, named as a `Branch`
+ /// target, errors.
pruned_from: Option<PathBuf>,
branch: String,
},
@@ -224,22 +229,23 @@ impl RepositoryCliExt for Repository {
}
.into());
}
- // Directory missing (e.g. external `rm -rf`): prune the stale
- // metadata and fall back to branch-only deletion — the same
- // handling the branch-targeted path applies. A detached
+ // Directory missing (e.g. external `rm -rf`): fall back to
+ // branch-only deletion, recording the stale entry in the plan
+ // so execution unregisters it — planning stays a pure read
+ // (`wt step prune`'s scan doubles as `--dry-run`, and `wt
+ // remove` plans before its approval prompt). A detached
// worktree has no branch to fall back to, so it proceeds and
// surfaces the removal error.
//
- // The prune names this worktree rather than sweeping the repo,
- // so a sibling whose directory is merely absent right now keeps
- // its registration. `git worktree remove` refuses a locked
- // worktree where a repo-wide prune ignored one, which needs no
- // guard here: the lock check above already returned for every
- // locked entry in this arm.
+ // The recorded prune names this worktree rather than sweeping
+ // the repo, so a sibling whose directory is merely absent
+ // right now keeps its registration. `git worktree remove`
+ // refuses a locked worktree where a repo-wide prune ignored
+ // one, which needs no guard here: the lock check above already
+ // returned for every locked entry in this arm.
if let Some(branch) = wt.branch.as_deref()
&& !wt.path.exists()
{
- self.prune_worktree_entry(&wt.path)?;
Resolved::BranchOnly {
pruned_from: Some(wt.path.clone()),
branch: branch.to_string(),
@@ -291,7 +297,7 @@ impl RepositoryCliExt for Repository {
return Ok(RemovalPlan::BranchOnly {
branch_name: branch,
deletion_mode: BranchDeletionMode::Keep,
- pruned: true,
+ prune_entry: pruned_from,
target_branch: None,
integration_reason: None,
branch_checked_out_at: Some(shared),
@@ -309,7 +315,7 @@ impl RepositoryCliExt for Repository {
return Ok(RemovalPlan::BranchOnly {
branch_name: branch,
deletion_mode,
- pruned: pruned_from.is_some(),
+ prune_entry: pruned_from,
target_branch,
integration_reason,
branch_checked_out_at: None,
diff --git a/src/commands/step/prune.rs b/src/commands/step/prune.rs
index ab299b830..fed1b7d70 100644
--- a/src/commands/step/prune.rs
+++ b/src/commands/step/prune.rs
@@ -37,7 +37,7 @@ use worktrunk::trace::Span;
use super::super::hook_plan::{ApprovedHookPlan, HookPlan, HookPlanBuilder};
use super::super::hooks::HookAnnouncer;
-use super::super::repository_ext::{RemoveTarget, RepositoryCliExt, live_sibling_checkout};
+use super::super::repository_ext::{RemoveTarget, RepositoryCliExt};
use super::super::worktree::RemovalPlan;
use crate::output::{BackgroundFallbackMode, RemovalExecution, handle_remove_output};
@@ -68,30 +68,6 @@ struct Candidate {
}
impl Candidate {
- /// Always the path, because the scan already identified the exact worktree:
- /// naming it by branch instead re-resolves to git's first-listed checkout,
- /// which for a branch checked out twice is a different worktree — and for a
- /// stale entry is the live one. `RemoveTarget::Path` degrades to branch-only
- /// deletion when the directory is already gone, so a stale entry still
- /// prunes.
- ///
- /// Only a candidate that arrives without a scan-time plan reaches this, and
- /// `check_one` plans everything except `Prunable`, which always carries the
- /// stale worktree's path.
- fn remove_target(&self) -> anyhow::Result<RemoveTarget<'_>> {
- match self.kind {
- CandidateKind::Current => Ok(RemoveTarget::Current),
- CandidateKind::StaleDetached => Err(anyhow::anyhow!(
- "stale detached candidate has no remove target"
- )),
- CandidateKind::BranchOnly | CandidateKind::Other => Ok(RemoveTarget::Path(
- self.path
- .as_ref()
- .context("candidate has no worktree path")?,
- )),
- }
- }
-
/// Error context for `try_remove` failures: distinguishes branch-only
/// removals (no worktree exists) from worktree removals.
fn removal_context(&self) -> String {
@@ -239,8 +215,6 @@ struct RemovalContext<'a> {
repo: &'a Repository,
foreground: bool,
hook_plan: &'a ApprovedHookPlan,
- worktrees: &'a [WorktreeInfo],
- snapshot: &'a RefSnapshot,
/// Coordinates the parallel workers (scan checks and removals, both on
/// the read side) against the few removals that need exclusivity (write
/// side — see [`removal_needs_write`]).
@@ -266,65 +240,57 @@ struct RemovalContext<'a> {
/// Which removals must hold the write side of [`RemovalContext::check_lock`]
/// instead of joining the parallel (read-side) fan-out:
///
-/// - **Hook-bearing worktree candidates** — the `pre-remove` body runs
+/// - **Hook-bearing worktree removals** — the `pre-remove` body runs
/// foreground here, and hook bodies are arbitrary commands (`git branch
/// -D`, `git config`, anything), so it keeps the exclusion every removal
/// had before removals parallelized; the write side also keeps the hook
/// stream and announce lines from interleaving with other candidates'
/// output. (`post-remove`/`post-switch` pipelines spawn detached and
/// always ran outside the lock.)
-/// - **`--foreground` worktree candidates** — the foreground path runs a TTY
+/// - **`--foreground` worktree removals** — the foreground path runs a TTY
/// trash-cleanup spinner, and concurrent spinners would fight over the
/// cursor.
/// - **The current worktree** — deferred until after the fan-out drains and
/// run alone; write for uniformity with its post-switch hooks.
///
-/// Everything else fans out, including the two candidate shapes that
-/// unregister stale worktree metadata: `StaleDetached`, and the plan-less
-/// `Prunable` candidates whose `prepare_worktree_removal` prunes. Each call
-/// names its own entry, so concurrent prunes are safe against each other and
-/// against the scan — see the concurrency section on
+/// Called with the plan in hand, so it asks what the removal will do rather
+/// than predicting from the candidate's shape: a `BranchOnly` plan runs neither
+/// a hook body nor a spinner, whatever selected it. `StaleDetached` never
+/// reaches here — [`try_remove`] prunes its entry and returns.
+///
+/// Everything else fans out, including both mutations that unregister stale
+/// worktree metadata: `StaleDetached`'s prune, and the one a `BranchOnly`
+/// plan carries as `prune_entry`. Each names its own entry, so concurrent
+/// prunes are safe against each other and against the scan — see the
+/// concurrency section on
/// [`prune_worktree_entry`](Repository::prune_worktree_entry).
-fn removal_needs_write(
- candidate: &Candidate,
- plan: Option<&RemovalPlan>,
- ctx: &RemovalContext<'_>,
-) -> bool {
- // The worktree whose `pre-remove` body and trash-cleanup spinner this
- // removal would run, `None` when it runs neither.
- let hook_anchor = match candidate.kind {
- CandidateKind::Current => return true,
- // `try_remove` prunes the stale entry and returns before either runs.
- CandidateKind::StaleDetached => None,
- CandidateKind::Other | CandidateKind::BranchOnly => match plan {
- Some(RemovalPlan::Worktree { worktree_path, .. }) => Some(worktree_path.as_path()),
- Some(RemovalPlan::BranchOnly { .. }) => None,
- // A plan-less `Prunable` candidate plans inside `try_remove`, so
- // ask its own path what that plan will decide: an entry whose
- // directory turns out to still be there plans a full worktree
- // removal, hooks and spinner and all.
- None => candidate.path.as_deref(),
- },
- };
- hook_anchor.is_some_and(|anchor| {
- ctx.foreground
- || ctx
- .hook_plan
- .has_hooks_for(anchor, &[HookType::PreRemove, HookType::PostRemove])
- })
+fn removal_needs_write(kind: CandidateKind, plan: &RemovalPlan, ctx: &RemovalContext<'_>) -> bool {
+ if matches!(kind, CandidateKind::Current) {
+ return true;
+ }
+ match plan {
+ // The worktree whose `pre-remove` body and trash-cleanup spinner this
+ // removal runs.
+ RemovalPlan::Worktree { worktree_path, .. } => {
+ ctx.foreground
+ || ctx
+ .hook_plan
+ .has_hooks_for(worktree_path, &[HookType::PreRemove, HookType::PostRemove])
+ }
+ RemovalPlan::BranchOnly { .. } => false,
+ }
}
/// Try to remove a candidate immediately. Returns `Ok(Some(branch_deleted))`
-/// if removed — the executed outcome the summary counts — `Ok(None)` if
-/// skipped (preparation error), `Err` on execution error.
+/// if removed — the executed outcome the summary counts — `Ok(None)` if the
+/// removal turned out to be a no-op, `Err` on execution error.
///
/// `plan` is the scan-time `prepare_worktree_removal` result from
-/// [`check_one`]. `Prunable` candidates arrive plan-less and prepare here
-/// rather than on the scan, because preparing them prunes stale worktree
-/// metadata and the scan also backs `--dry-run`, which mutates nothing.
-/// Scan-time plans may be stale by execution; the pre-rename
-/// `ensure_clean` and the branch-delete CAS re-validate what matters — and the
-/// returned [`BranchFate`](crate::commands::worktree::BranchFate) is how a CAS
+/// [`check_one`]; only `StaleDetached` candidates arrive without one (their
+/// entry is pruned directly here — there is nothing to plan). Scan-time plans
+/// may be stale by execution; the pre-rename `ensure_clean` and the
+/// branch-delete CAS re-validate what matters — and the returned
+/// [`BranchFate`](crate::commands::worktree::BranchFate) is how a CAS
/// refusal reaches the summary.
fn try_remove(
candidate: &Candidate,
@@ -332,25 +298,11 @@ fn try_remove(
ctx: &RemovalContext<'_>,
) -> anyhow::Result<Option<bool>> {
let _span = Span::new(format!("prune-remove:{}", candidate.label));
- // Read side for the parallel default, write side for the exclusive cases
- // (see `removal_needs_write`). The guards protect `()` — there is no
- // shared state to corrupt, so a poisoned lock is meaningless here.
- // Recover the guard rather than `.expect()`-ing: a panic elsewhere should
- // surface as itself, not as a cascade of secondary poison panics on every
- // later removal/reader.
- let (_read, _write) = if removal_needs_write(candidate, plan.as_ref(), ctx) {
- (
- None,
- Some(ctx.check_lock.write().unwrap_or_else(|e| e.into_inner())),
- )
- } else {
- (
- Some(ctx.check_lock.read().unwrap_or_else(|e| e.into_inner())),
- None,
- )
- };
if matches!(candidate.kind, CandidateKind::StaleDetached) {
+ // The scoped metadata prune is read-side-safe (see
+ // `prune_worktree_entry`), so hold the parallel default.
+ let _read = ctx.check_lock.read().unwrap_or_else(|e| e.into_inner());
// Name the stale entry rather than sweeping the repository, so a
// sibling whose directory is merely absent right now (unmounted
// volume, half-finished `mv`) keeps its registration. `gather_check_items`
@@ -365,24 +317,25 @@ fn try_remove(
return Ok(Some(false));
}
- let plan = match plan {
- Some(plan) => plan,
- None => match ctx.repo.prepare_worktree_removal(
- candidate.remove_target()?,
- BranchDeletionMode::SafeDelete,
- false,
+ let plan = plan.context("candidate arrived without a removal plan")?;
+ // Read side for the parallel default, write side for the exclusive cases
+ // (see `removal_needs_write`). The guards protect `()` — there is no
+ // shared state to corrupt, so a poisoned lock is meaningless here.
+ // Recover the guard rather than `.expect()`-ing: a panic elsewhere should
+ // surface as itself, not as a cascade of secondary poison panics on every
+ // later removal/reader.
+ let (_read, _write) = if removal_needs_write(candidate.kind, &plan, ctx) {
+ (
None,
- Some(ctx.worktrees),
- Some(ctx.snapshot),
- ) {
- Ok(plan) => plan,
- Err(_) => {
- // prepare_worktree_removal is the gate: if the worktree can't
- // be removed (dirty, locked, etc.), it's simply not selected.
- return Ok(None);
- }
- },
+ Some(ctx.check_lock.write().unwrap_or_else(|e| e.into_inner())),
+ )
+ } else {
+ (
+ Some(ctx.check_lock.read().unwrap_or_else(|e| e.into_inner())),
+ None,
+ )
};
+
let mut announcer = HookAnnouncer::new(ctx.repo, true);
// `SynchronousForNonCurrent`: a rename-failure fallback completes inline,
// so the candidate counts as removed only once the worktree and branch
@@ -396,11 +349,15 @@ fn try_remove(
announcer.flush()?;
let branch_deleted = fate.deleted();
// A branch-only candidate that kept its branch removed nothing at all —
- // unless planning pruned a stale worktree entry, a removal worth counting.
- // Excluding the no-op keeps the summary and JSON honest when a concurrent
- // writer advanced an orphan branch between scan and delete (the per-item
- // retention warning has already told the user).
- if !branch_deleted && let RemovalPlan::BranchOnly { pruned: false, .. } = plan {
+ // unless the removal pruned a stale worktree entry, a removal worth
+ // counting. Excluding the no-op keeps the summary and JSON honest when a
+ // concurrent writer advanced an orphan branch between scan and delete
+ // (the per-item retention warning has already told the user).
+ if !branch_deleted
+ && let RemovalPlan::BranchOnly {
+ prune_entry: None, ..
+ } = plan
+ {
return Ok(None);
}
Ok(Some(branch_deleted))
@@ -412,8 +369,9 @@ fn try_remove(
/// `.config/wt.toml` differs from the invoking worktree's (so the user knows
/// `wt config approvals add` from current can't approve their hooks).
struct SkippedApproval {
- /// `Some` for `Linked` candidates (the only `(approval required)`
- /// source — branch-only and stale-detached don't run hooks).
+ /// `Some` for candidates whose plan removes a worktree (the only
+ /// `(approval required)` source — branch-only plans and stale-detached
+ /// entries run no hooks).
path: Option<PathBuf>,
/// True when the candidate's `.config/wt.toml` doesn't match the
/// invoking worktree's bytes — `wt config approvals add` from current
@@ -431,11 +389,12 @@ struct CheckOutcome {
/// Removal plan from `prepare_worktree_removal` — the same gate `wt
/// remove` uses, computed here on the parallel scan so `try_remove`
/// doesn't re-derive it (a `git status` per worktree) at removal time.
- /// `None` means not removable (dirty, locked, primary — filtered
- /// silently, never reported as "younger than") — except for `Prunable`
- /// items, which are always removable but plan in `try_remove`: preparing
- /// them calls `prune_worktree_entry()`, and this scan also backs
- /// `--dry-run`, which mutates nothing.
+ /// Planning is pure (a stale entry's prune rides the plan as
+ /// `prune_entry`; execution performs it), which is what lets this scan
+ /// double as `--dry-run` and plan every source. `None` means not
+ /// removable (dirty, locked, primary — filtered silently, never reported
+ /// as "younger than") — except detached stale entries, which need no
+ /// plan: `try_remove` prunes them directly.
plan: Option<RemovalPlan>,
/// Whether the item passed the removability gate (see `plan`).
removable: bool,
@@ -472,54 +431,47 @@ fn check_one(
age: None,
});
}
- let plan = match &item.source {
- CheckSource::Prunable { .. } => None,
- CheckSource::Orphan => repo
- .prepare_worktree_removal(
- RemoveTarget::Branch(&item.integration_ref),
- BranchDeletionMode::SafeDelete,
- false,
- None,
- Some(worktrees),
- Some(snapshot),
- )
- .ok(),
- CheckSource::Linked { wt_idx } => {
- let wt = &worktrees[*wt_idx];
- repo.prepare_worktree_removal(
- // The scan already knows which worktree this is; naming it by
- // branch would re-resolve to git's first-listed checkout, which
- // for a duplicated branch is a different worktree.
- RemoveTarget::Path(&wt.path),
- BranchDeletionMode::SafeDelete,
- false,
- None,
- Some(worktrees),
- Some(snapshot),
- )
- .ok()
- }
- };
- let removable = match &item.source {
- CheckSource::Prunable { .. } => true,
- CheckSource::Orphan | CheckSource::Linked { .. } => plan.is_some(),
- };
- let deletes_branch = match &plan {
- Some(plan) => plan.deletes_branch(),
- // A `Prunable` item has no plan until `try_remove` prunes its stale
- // entry, so ask the predicate that plan would: a live sibling
- // checkout of the same branch retains it. `Linked` and `Orphan`
- // arrive here only when the gate refused them, and nothing is
- // removed.
- None => match &item.source {
- CheckSource::Prunable { wt_idx } => {
+ // A detached stale entry can't be planned — `prepare_worktree_removal`'s
+ // missing-directory fallback needs a branch to fall back to — and needs
+ // no plan: `try_remove` prunes the entry directly.
+ let detached_stale = matches!(&item.source,
+ CheckSource::Prunable { wt_idx } if worktrees[*wt_idx].branch.is_none());
+ let plan = if detached_stale {
+ None
+ } else {
+ match &item.source {
+ CheckSource::Orphan => repo
+ .prepare_worktree_removal(
+ RemoveTarget::Branch(&item.integration_ref),
+ BranchDeletionMode::SafeDelete,
+ false,
+ None,
+ Some(worktrees),
+ Some(snapshot),
+ )
+ .ok(),
+ CheckSource::Linked { wt_idx } | CheckSource::Prunable { wt_idx } => {
let wt = &worktrees[*wt_idx];
- wt.branch.is_some()
- && live_sibling_checkout(worktrees, &item.integration_ref, &wt.path).is_none()
+ repo.prepare_worktree_removal(
+ // The scan already knows which worktree this is; naming it
+ // by branch would re-resolve to git's first-listed
+ // checkout, which for a duplicated branch is a different
+ // worktree — and for a stale entry is the live one. A
+ // `Path` target degrades to branch-only deletion when the
+ // directory is gone, so a stale entry plans its prune.
+ RemoveTarget::Path(&wt.path),
+ BranchDeletionMode::SafeDelete,
+ false,
+ None,
+ Some(worktrees),
+ Some(snapshot),
+ )
+ .ok()
}
- CheckSource::Linked { .. } | CheckSource::Orphan => false,
- },
+ }
};
+ let removable = detached_stale || plan.is_some();
+ let deletes_branch = plan.as_ref().is_some_and(RemovalPlan::deletes_branch);
let age = if min_age_duration > Duration::ZERO {
match &item.source {
CheckSource::Linked { wt_idx } => worktree_age(repo, &worktrees[*wt_idx], now_secs)?,
@@ -816,7 +768,7 @@ fn render_dry_run(
Ok(())
}
-/// Build the pessimistic hook plan up front — every linked worktree in
+/// Build the pessimistic hook plan up front — every worktree entry in
/// `check_items` × `pre-remove`/`post-remove`, plus the primary × `post-switch`
/// when the current worktree appears in `check_items`. The actual scan may
/// narrow this set; the pessimistic shape is what lets `try_remove` stream
@@ -824,9 +776,15 @@ fn render_dry_run(
/// resolve against (every hook is selected from the invoking worktree's
/// `.config/wt.toml`, whatever its anchor).
///
-/// `pre-remove`/`post-remove`/`post-switch` never run for `BranchOnly` /
-/// `StaleDetached` / `Orphan` candidates — those are pure branch deletions —
-/// so they contribute nothing to the plan.
+/// `Orphan` items name no worktree, so they contribute nothing. `Prunable` ones
+/// do, even though the stale entry they usually describe plans a pure branch
+/// deletion that runs no hooks: git calls an entry prunable when the `.git` file
+/// its metadata points at is gone, which leaves the worktree *directory* still
+/// there whenever only that file went (an interrupted `rm -rf`, a copy that
+/// skipped dotfiles), and the scan then plans a full worktree removal whose
+/// hooks anchor at that path and must resolve (`ApprovedHookPlan::lookup`
+/// matches the anchor exactly, by design). For the ordinary stale entry the
+/// plan resolves to `BranchOnly` and the registration goes unused.
fn build_pessimistic_plan(
repo: &Repository,
check_items: &[CheckItem],
@@ -839,7 +797,8 @@ fn build_pessimistic_plan(
let mut builder = HookPlanBuilder::new(project_config, user_config, project_id);
let mut has_current = false;
for item in check_items {
- let CheckSource::Linked { wt_idx } = &item.source else {
+ let (CheckSource::Linked { wt_idx } | CheckSource::Prunable { wt_idx }) = &item.source
+ else {
continue;
};
let wt = &worktrees[*wt_idx];
@@ -1091,8 +1050,6 @@ pub fn step_prune(
repo: &repo,
foreground,
hook_plan: &hook_plan,
- worktrees,
- snapshot: &snapshot,
check_lock: &check_lock,
};
// Flipped by the first failing removal: the rest of the queue drains
@@ -1219,17 +1176,19 @@ pub fn step_prune(
skipped_young.push(label);
continue;
}
- let needs_approval = match kind {
- CandidateKind::Other => {
- !pre_remove_unapproved.is_empty() || !post_remove_unapproved.is_empty()
- }
- CandidateKind::Current => {
+ // Keyed on the plan, not the candidate's shape: only a
+ // worktree removal runs `pre-remove`/`post-remove`, and a
+ // stale entry whose directory turned out to still exist plans
+ // one like any other (see `build_pessimistic_plan`). Branch-
+ // only plans and detached stale entries run no hooks.
+ let needs_approval = match &outcome.plan {
+ Some(RemovalPlan::Worktree { .. }) => {
!pre_remove_unapproved.is_empty()
|| !post_remove_unapproved.is_empty()
- || !post_switch_unapproved.is_empty()
+ || (matches!(kind, CandidateKind::Current)
+ && !post_switch_unapproved.is_empty())
}
- // Pure branch deletions don't run hooks.
- CandidateKind::BranchOnly | CandidateKind::StaleDetached => false,
+ Some(RemovalPlan::BranchOnly { .. }) | None => false,
};
if needs_approval {
let line =
@@ -1446,17 +1405,6 @@ mod tests {
);
}
- #[test]
- fn stale_detached_candidate_has_no_remove_target() {
- // `try_remove` and `can_attempt_candidate_removal` short-circuit
- // `StaleDetached` before calling `remove_target` — but assert the
- // guard arm so the contract is pinned if that ordering ever changes.
- let err = candidate(CandidateKind::StaleDetached, "gone")
- .remove_target()
- .unwrap_err();
- assert!(err.to_string().contains("no remove target"));
- }
-
#[test]
fn approval_hint_blocks_list_templates_and_per_worktree_paths() {
let skipped = vec![
diff --git a/src/commands/worktree/types.rs b/src/commands/worktree/types.rs
index 33bcc552d..5e569b829 100644
--- a/src/commands/worktree/types.rs
+++ b/src/commands/worktree/types.rs
@@ -265,15 +265,20 @@ pub enum RemovalPlan {
/// [`SharedBranchCheckout`].
branch_checked_out_at: Option<SharedBranchCheckout>,
},
- /// Branch exists but has no worktree - attempt branch deletion only.
- ///
- /// `pruned` indicates whether the worktree was pruned (directory was missing).
- /// When true, shows an info message instead of a warning.
+ /// Branch exists but has no worktree directory - attempt branch deletion
+ /// only, unregistering the stale worktree entry first when one remains.
BranchOnly {
branch_name: String,
deletion_mode: BranchDeletionMode,
- /// True if a stale worktree entry was pruned during planning.
- pruned: bool,
+ /// Stale worktree entry to unregister, recorded when the plan fell
+ /// back from a worktree whose directory was missing. Planning never
+ /// mutates — execution performs the prune (`git worktree remove`,
+ /// which validates before touching anything, so a directory that
+ /// reappears at this path between planning and execution is handled
+ /// by git: a clean reconnected worktree is removed, a dirty or
+ /// foreign one refuses loudly). `None` when the branch has no
+ /// worktree entry at all.
+ prune_entry: Option<PathBuf>,
/// Integration target for display. May be the effective target (e.g.,
/// `origin/main` when upstream is ahead) or the local default branch.
/// `None` when no default branch is configured.
@@ -369,13 +374,13 @@ impl RemovalPlan {
}),
RemovalPlan::BranchOnly {
branch_name,
- pruned,
+ prune_entry,
branch_checked_out_at,
..
} => serde_json::json!({
"kind": "branch_only",
"branch": branch_name,
- "pruned": pruned,
+ "pruned": prune_entry.is_some(),
"branch_deleted": branch_deleted,
"branch_checked_out_at": branch_checked_out_at.as_ref().map(|c| &c.path),
}),
@@ -414,7 +419,7 @@ mod tests {
let branch_only = RemovalPlan::BranchOnly {
branch_name: "solo".to_string(),
deletion_mode: BranchDeletionMode::default(),
- pruned: false,
+ prune_entry: None,
target_branch: None,
integration_reason: None,
branch_checked_out_at: None,
@@ -561,7 +566,7 @@ mod tests {
let result = RemovalPlan::BranchOnly {
branch_name: "stale-branch".to_string(),
deletion_mode: BranchDeletionMode::Keep,
- pruned: false,
+ prune_entry: None,
target_branch: None,
integration_reason: None,
branch_checked_out_at: None,
@@ -570,7 +575,7 @@ mod tests {
RemovalPlan::BranchOnly {
branch_name,
deletion_mode,
- pruned,
+ prune_entry,
target_branch,
integration_reason,
branch_checked_out_at,
@@ -578,7 +583,7 @@ mod tests {
assert_eq!(branch_name, "stale-branch");
assert!(deletion_mode.should_keep());
assert!(!deletion_mode.is_force());
- assert!(!pruned);
+ assert!(prune_entry.is_none());
assert!(target_branch.is_none());
assert!(integration_reason.is_none());
assert!(branch_checked_out_at.is_none());
@@ -592,7 +597,7 @@ mod tests {
let result = RemovalPlan::BranchOnly {
branch_name: "pruned-branch".to_string(),
deletion_mode: BranchDeletionMode::SafeDelete,
- pruned: true,
+ prune_entry: Some(PathBuf::from("/stale")),
target_branch: Some("main".to_string()),
integration_reason: None,
branch_checked_out_at: None,
@@ -601,14 +606,14 @@ mod tests {
RemovalPlan::BranchOnly {
branch_name,
deletion_mode,
- pruned,
+ prune_entry,
target_branch,
integration_reason,
branch_checked_out_at,
} => {
assert_eq!(branch_name, "pruned-branch");
assert!(!deletion_mode.should_keep());
- assert!(pruned);
+ assert_eq!(prune_entry.as_deref(), Some(Path::new("/stale")));
assert_eq!(target_branch.as_deref(), Some("main"));
assert!(integration_reason.is_none());
assert!(branch_checked_out_at.is_none());
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index 0a142c1cb..ad0847ae6 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -1127,14 +1127,14 @@ pub fn handle_remove_output(
RemovalPlan::BranchOnly {
branch_name,
deletion_mode,
- pruned,
+ prune_entry,
target_branch,
integration_reason,
branch_checked_out_at,
} => handle_branch_only_output(
branch_name,
*deletion_mode,
- *pruned,
+ prune_entry.as_deref(),
*integration_reason,
target_branch.as_deref(),
branch_checked_out_at.as_ref(),
@@ -1145,17 +1145,27 @@ pub fn handle_remove_output(
/// Handle output for BranchOnly removal (branch exists but no worktree)
///
+/// `prune_entry` is the stale worktree entry the plan fell back from, if any;
+/// it is unregistered here, first — unconditionally, unlike the branch
+/// deletion the `should_keep`/CAS logic below may decline.
+///
/// When `quiet` is true, suppresses the "No worktree found for branch X"
/// info line for non-pruned cases (noise in prune/batch context).
fn handle_branch_only_output(
branch_name: &str,
deletion_mode: BranchDeletionMode,
- pruned: bool,
+ prune_entry: Option<&Path>,
integration_reason: Option<IntegrationReason>,
target_branch: Option<&str>,
branch_checked_out_at: Option<&SharedBranchCheckout>,
quiet: bool,
) -> anyhow::Result<BranchFate> {
+ let pruned = if let Some(path) = prune_entry {
+ Repository::current()?.prune_worktree_entry(path)?;
+ true
+ } else {
+ false
+ };
let branch_info = if pruned {
cformat!("Worktree directory missing for <bold>{branch_name}</>; pruned")
} else {
diff --git a/tests/integration_tests/step_prune.rs b/tests/integration_tests/step_prune.rs
index 9048ea3ed..94df80268 100644
--- a/tests/integration_tests/step_prune.rs
+++ b/tests/integration_tests/step_prune.rs
@@ -1553,18 +1553,16 @@ fn test_prune_fallback_config_race_canary(mut repo: TestRepo) {
let _ = std::fs::remove_file(&staged_path);
}
-/// A `Prunable` candidate (stale worktree entry, integrated branch) whose
-/// preparation fails at removal time is skipped silently and the run
-/// continues: `try_remove` treats a preparation error as "not selected", not
-/// a command failure. Preparing a stale entry prunes its metadata — the
-/// mutation that keeps `Prunable` candidates planning in `try_remove` rather
-/// than on the `--dry-run`-shared scan — and it names the entry (`git worktree remove`)
-/// rather than sweeping the repo, so a `git` shim failing `worktree remove` is
-/// the deterministic trigger. Unix-only for the same `CreateProcess` reason as
+/// A stale worktree entry whose metadata prune fails at execution surfaces
+/// the failure rather than pretending the candidate was removed: the scan
+/// records the prune in the plan (`prune_entry`), execution runs it before
+/// the branch deletion, and its error fails the run — the branch and the
+/// entry both survive intact. A `git` shim failing `worktree remove` is the
+/// deterministic trigger. Unix-only for the same `CreateProcess` reason as
/// the canary shim above.
#[cfg(unix)]
#[rstest]
-fn test_prune_skips_prunable_candidate_whose_preparation_fails(mut repo: TestRepo) {
+fn test_prune_surfaces_failing_metadata_prune(mut repo: TestRepo) {
repo.commit("initial");
// Integrated branch whose worktree directory is deleted out-of-band → a
@@ -1587,18 +1585,62 @@ fn test_prune_skips_prunable_candidate_whose_preparation_fails(mut repo: TestRep
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
- output.status.success(),
- "a failing candidate preparation must skip the candidate, not fail \
- the run.\nstderr:\n{stderr}"
+ !output.status.success(),
+ "a failing metadata prune is a failed removal, not a silent skip.\nstderr:\n{stderr}"
+ );
+ assert!(
+ stderr.contains("stale-merged"),
+ "the error must name the failed candidate.\nstderr:\n{stderr}"
);
assert!(
prune_failed_marker.exists(),
- "the shim never fired — the candidate's preparation was not exercised"
+ "the shim never fired — the metadata prune was not exercised"
+ );
+ // Nothing half-done: the entry is still registered and the branch intact.
+ let list = repo.git_output(&["worktree", "list", "--porcelain"]);
+ assert!(
+ list.contains("prunable"),
+ "the failed prune must leave the entry registered; worktrees:\n{list}"
);
let branches = repo.git_output(&["branch", "--format=%(refname:short)"]);
assert!(
branches.lines().any(|branch| branch == "stale-merged"),
- "the skipped candidate's branch must survive; branches:\n{branches}"
+ "the failed candidate's branch must survive; branches:\n{branches}"
+ );
+}
+
+/// `--dry-run` mutates nothing, even though the scan now plans stale entries
+/// through `prepare_worktree_removal` like every other source: planning is
+/// pure — the metadata prune rides the plan and only execution performs it.
+/// A regression here (a mutation creeping back into planning) would make the
+/// preview destructive.
+#[rstest]
+fn test_prune_dry_run_leaves_stale_entry_registered(mut repo: TestRepo) {
+ repo.commit("initial");
+
+ repo.add_worktree("stale-branch");
+ std::fs::remove_dir_all(repo.worktree_path("stale-branch")).unwrap();
+
+ let output = repo
+ .wt_command()
+ .args(["step", "prune", "--dry-run", "--min-age=0s"])
+ .output()
+ .unwrap();
+ assert!(output.status.success());
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ assert!(
+ stdout.contains("would be removed"),
+ "the stale entry must be previewed as a candidate:\n{stdout}"
+ );
+ let list = repo.git_output(&["worktree", "list", "--porcelain"]);
+ assert!(
+ list.contains("prunable"),
+ "dry run must leave the stale entry registered; worktrees:\n{list}"
+ );
+ let branches = repo.git_output(&["branch", "--format=%(refname:short)"]);
+ assert!(
+ branches.lines().any(|branch| branch == "stale-branch"),
+ "dry run must leave the branch; branches:\n{branches}"
);
}
@@ -1672,17 +1714,25 @@ fn test_prune_removals_run_concurrently(repo: TestRepo) {
/// The removals that unregister stale worktree metadata are on the read side
/// too, not held back one at a time.
///
-/// Four stale entries: two carrying a branch (prune's plan-less `Prunable`
-/// candidates, which prune while planning) and two detached (`StaleDetached`,
-/// which prune in place of a removal). Each unregisters its own metadata with
+/// Four stale entries: two carrying a branch (`BranchOnly` plans whose
+/// `prune_entry` executes the prune) and two detached (`StaleDetached`, which
+/// prune in place of a removal). Each unregisters its own metadata with
/// `git worktree remove <path>`, and the shim makes every one of them wait for
/// all four to start before proceeding. Serialized, the first would wait out
/// the shim's 15 s timeout and drop a sentinel file, which the test asserts
/// absent. Unix-only for the same `CreateProcess` shim reason as the canary
/// above.
+///
+/// `--foreground` runs both ways too. It reserves the write side for the TTY
+/// trash-cleanup spinner, which only a worktree removal paints; every candidate
+/// here plans a pure branch deletion or a bare prune, so the flag has no
+/// spinner to protect and must not serialize them.
#[cfg(unix)]
#[rstest]
-fn test_prune_metadata_removals_run_concurrently(mut repo: TestRepo) {
+fn test_prune_metadata_removals_run_concurrently(
+ mut repo: TestRepo,
+ #[values(false, true)] foreground: bool,
+) {
repo.commit("initial");
// At main HEAD, so every entry is same-commit integrated.
@@ -1720,10 +1770,11 @@ fn test_prune_metadata_removals_run_concurrently(mut repo: TestRepo) {
cmd.env("WT_TEST_BARRIER_DIR", &barrier_dir);
cmd.env("WT_TEST_BARRIER_COUNT", stale.len().to_string());
- let output = cmd
- .args(["step", "prune", "--yes", "--min-age=0s"])
- .output()
- .unwrap();
+ cmd.args(["step", "prune", "--yes", "--min-age=0s"]);
+ if foreground {
+ cmd.arg("--foreground");
+ }
+ let output = cmd.output().unwrap();
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(output.status.success(), "prune should succeed:\n{stderr}");
diff --git a/tests/snapshots/integration__integration_tests__remove__remove_default_branch_branch_only_force_delete.snap b/tests/snapshots/integration__integration_tests__remove__remove_default_branch_branch_only_force_delete.snap
index af7a342e1..b16bd928e 100644
--- a/tests/snapshots/integration__integration_tests__remove__remove_default_branch_branch_only_force_delete.snap
+++ b/tests/snapshots/integration__integration_tests__remove__remove_default_branch_branch_only_force_delete.snap
@@ -8,6 +8,7 @@ info:
- main
env:
COLUMNS: "500"
+ GIT_ALLOW_PROTOCOL: file
GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
@@ -29,6 +30,7 @@ info:
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"
@@ -39,5 +41,4 @@ exit_code: 0
----- stdout -----
----- stderr -----
-○ No worktree found for branch main
-✓ Removed branch main (--force-delete)
+✓ Pruned stale worktree & removed branch main (--force-delete)