Skip to content

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

fix: data-safety fixes across the worktree merge/remove/prune lifecycle (#2870)

Maximilian Roos43e1592503ca
diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rs
index dfd590cec..183304efa 100644
--- a/src/commands/picker/mod.rs
+++ b/src/commands/picker/mod.rs
@@ -119,7 +119,7 @@ use super::list::progressive::RenderTarget;
use super::repository_ext::{RemoveTarget, RepositoryCliExt};
use super::worktree::{RemoveResult, SwitchPipeline};
use crate::cli::SwitchFormat;
-use crate::output::handle_remove_output;
+use crate::output::{BackgroundFallbackMode, handle_remove_output};
use worktrunk::git::{BranchDeletionMode, delete_branch_if_safe};
use items::{PreviewCache, WORKTREE_OUTPUT_PREFIX};
@@ -298,6 +298,7 @@ impl PickerCollector {
/* quiet */ true,
/* silent */ true,
&mut announcer,
+ BackgroundFallbackMode::Detached,
)?;
announcer.flush()?;
}
@@ -1078,7 +1079,6 @@ pub mod tests {
branch_name: Some("feature".to_string()),
deletion_mode: BranchDeletionMode::SafeDelete,
target_branch: Some("main".to_string()),
- integration_reason: None,
force_worktree: false,
expected_path: None,
removed_commit: None,
@@ -1174,7 +1174,6 @@ pub mod tests {
branch_name: None,
deletion_mode: BranchDeletionMode::SafeDelete,
target_branch: Some("main".to_string()),
- integration_reason: None,
force_worktree: false,
expected_path: None,
removed_commit: None,
@@ -1278,7 +1277,6 @@ pub mod tests {
branch_name: Some("feature".to_string()),
deletion_mode: BranchDeletionMode::SafeDelete,
target_branch: Some("main".to_string()),
- integration_reason: None,
force_worktree: false,
expected_path: None,
removed_commit: None,
diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rs
index f051fcf5b..4de2b51a5 100644
--- a/src/commands/repository_ext.rs
+++ b/src/commands/repository_ext.rs
@@ -106,8 +106,8 @@ impl RepositoryCliExt for Repository {
// worktree, then repo base for bare repos with no worktrees.
let primary_path = self.home_path()?;
- // Reuse caller's snapshot when present; otherwise capture once for the
- // two `compute_integration_reason` calls below.
+ // Reuse caller's snapshot when present; otherwise capture once for
+ // branch-only integration checks below.
let owned_snapshot;
let snapshot = match snapshot {
Some(s) => s,
@@ -238,8 +238,8 @@ impl RepositoryCliExt for Repository {
}
// Phase 4: Return BranchOnly early (after validation), or continue to
- // worktree-level checks. Compute integration here (same as Phase 5 does
- // for RemovedWorktree) so the output handler doesn't re-derive it.
+ // worktree-level checks. Branch-only removals have no pre-remove hook,
+ // so their integration decision can be computed here.
let (worktree_path, branch_name, is_current) = match resolved {
Resolved::BranchOnly { branch, pruned } => {
let default_branch = self.default_branch();
@@ -293,18 +293,6 @@ impl RepositoryCliExt for Repository {
_ => default_branch,
};
- // Pre-compute integration reason to avoid race conditions when removing
- // multiple worktrees in background mode. Use the effective target for
- // display (e.g., origin/main when upstream is ahead).
- let (integration_reason, effective_target) = compute_integration_reason(
- self,
- snapshot,
- branch_name.as_deref(),
- target_branch.as_deref(),
- deletion_mode,
- );
- let target_branch = effective_target.or(target_branch);
-
// Compute expected_path for path mismatch detection
// Only set if actual path differs from expected (path mismatch)
let expected_path = branch_name
@@ -329,7 +317,6 @@ impl RepositoryCliExt for Repository {
branch_name,
deletion_mode,
target_branch,
- integration_reason,
force_worktree,
expected_path,
removed_commit,
diff --git a/src/commands/step/prune.rs b/src/commands/step/prune.rs
index 737f13f20..9a93fe5a2 100644
--- a/src/commands/step/prune.rs
+++ b/src/commands/step/prune.rs
@@ -18,9 +18,10 @@ use worktrunk::styling::{eprintln, hint_message, info_message, println, success_
use super::super::hook_plan::{ApprovedHookPlan, HookPlanBuilder};
use super::super::hooks::HookAnnouncer;
use super::super::repository_ext::{RemoveTarget, RepositoryCliExt};
-use crate::output::handle_remove_output;
+use crate::output::{BackgroundFallbackMode, handle_remove_output};
/// A candidate worktree or branch selected for removal.
+#[derive(Clone)]
struct Candidate {
/// Original index in `check_items` (for deterministic output ordering)
check_idx: usize,
@@ -28,18 +29,41 @@ struct Candidate {
branch: Option<String>,
/// Display label: branch name or abbreviated commit SHA
label: String,
- /// Worktree path (for Path-based removal of detached worktrees)
+ /// Worktree path (for detached worktrees and stale metadata)
path: Option<PathBuf>,
- /// Current worktree, other worktree, or branch-only (no worktree)
+ /// Current worktree, other worktree, branch-only, or stale detached metadata
kind: CandidateKind,
}
impl Candidate {
+ fn remove_target(&self) -> anyhow::Result<RemoveTarget<'_>> {
+ match self.kind {
+ CandidateKind::Current => Ok(RemoveTarget::Current),
+ CandidateKind::BranchOnly => Ok(RemoveTarget::Branch(
+ self.branch
+ .as_ref()
+ .context("BranchOnly candidate missing branch")?,
+ )),
+ CandidateKind::StaleDetached => Err(anyhow::anyhow!(
+ "stale detached candidate has no remove target"
+ )),
+ CandidateKind::Other => match &self.branch {
+ Some(branch) => Ok(RemoveTarget::Branch(branch)),
+ None => Ok(RemoveTarget::Path(
+ self.path
+ .as_ref()
+ .context("detached candidate missing path")?,
+ )),
+ },
+ }
+ }
+
/// Error context for `try_remove` failures: distinguishes branch-only
/// removals (no worktree exists) from worktree removals.
fn removal_context(&self) -> String {
match self.kind {
CandidateKind::BranchOnly => format!("removing branch {}", self.label),
+ CandidateKind::StaleDetached => format!("pruning stale worktree for {}", self.label),
CandidateKind::Current | CandidateKind::Other => {
format!("removing worktree for {}", self.label)
}
@@ -47,10 +71,12 @@ impl Candidate {
}
}
+#[derive(Clone, Copy)]
enum CandidateKind {
Current,
Other,
BranchOnly,
+ StaleDetached,
}
impl CandidateKind {
@@ -59,6 +85,7 @@ impl CandidateKind {
CandidateKind::Current => "current",
CandidateKind::Other => "worktree",
CandidateKind::BranchOnly => "branch_only",
+ CandidateKind::StaleDetached => "stale_worktree",
}
}
}
@@ -66,7 +93,7 @@ impl CandidateKind {
/// Where a candidate originated, used to drive integration checks and dry-run labels.
enum CheckSource {
/// Worktree with directory gone (prunable)
- Prunable { branch: String },
+ Prunable { wt_idx: usize },
/// Linked worktree
Linked { wt_idx: usize },
/// Local branch without a worktree entry
@@ -85,6 +112,11 @@ struct DryRunInfo {
suffix: &'static str,
}
+enum PruneEvent {
+ Candidate(usize),
+ SkippedYoung(String),
+}
+
/// Build a human-readable count like "3 worktrees & branches".
///
/// Worktree + branch is the default pair (matching progress messages'
@@ -94,13 +126,16 @@ fn prune_summary(candidates: &[Candidate]) -> String {
let mut detached_worktree = 0usize;
let mut branch_only = 0usize;
for c in candidates {
- match (&c.kind, &c.branch) {
- (CandidateKind::BranchOnly, _) => branch_only += 1,
- (CandidateKind::Current | CandidateKind::Other, Some(_)) => {
- worktree_with_branch += 1;
- }
- (CandidateKind::Current | CandidateKind::Other, None) => {
- detached_worktree += 1;
+ match &c.kind {
+ CandidateKind::BranchOnly => branch_only += 1,
+ // A stale detached worktree never has a branch.
+ CandidateKind::StaleDetached => detached_worktree += 1,
+ CandidateKind::Current | CandidateKind::Other => {
+ if c.branch.is_some() {
+ worktree_with_branch += 1;
+ } else {
+ detached_worktree += 1;
+ }
}
}
}
@@ -152,15 +187,11 @@ struct RemovalContext<'a> {
/// 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, ctx: &RemovalContext<'_>) -> anyhow::Result<bool> {
- // Exclude all in-flight integration readers for the duration of the
- // removal: the write guard blocks until every outstanding read guard
- // (i.e. every running `integration_reason` git process) has dropped, and
- // blocks new ones until removal completes — so no `.git/config` reader is
- // alive while `git branch -D` rewrites it. Held over the whole body
- // (rather than just the deep `branch -D` call site) keeps the lock
- // confined to this file; the extra reader-exclusion during the fast
- // rename/prune is harmless. See the `check_lock` rationale at the
- // par_iter spawn for the Windows mechanism and its fast-path scope.
+ // Take the same write guard used by integration-check readers. The current
+ // phase ordering drains those readers before removal so approval can be
+ // exact; keeping the guard here preserves the Windows `.git/config`
+ // serialization if this flow is refactored back to overlap checks and
+ // removals. Held over the whole body keeps the lock confined to this file.
//
// The guard protects `()` — there is no shared state to corrupt, so a
// poisoned lock is meaningless here. Recover the guard rather than
@@ -168,24 +199,12 @@ fn try_remove(candidate: &Candidate, ctx: &RemovalContext<'_>) -> anyhow::Result
// cascade of secondary poison panics on every later removal/reader.
let _write = ctx.check_lock.write().unwrap_or_else(|e| e.into_inner());
- 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")?,
- ),
- },
- };
+ if matches!(candidate.kind, CandidateKind::StaleDetached) {
+ ctx.repo.prune_worktrees()?;
+ return Ok(true);
+ }
+
+ let target = candidate.remove_target()?;
let plan = match ctx.repo.prepare_worktree_removal(
target,
BranchDeletionMode::SafeDelete,
@@ -203,15 +222,49 @@ fn try_remove(candidate: &Candidate, ctx: &RemovalContext<'_>) -> anyhow::Result
}
};
let mut announcer = HookAnnouncer::new(ctx.repo, ctx.config, true);
- // Read the Copy fields into locals so the call stays on one line (rustfmt
- // breaks it past `ctx.`-prefixed args), keeping it identical to its form
- // before the context-struct refactor.
- let (foreground, hook_plan) = (ctx.foreground, ctx.hook_plan);
- handle_remove_output(&plan, foreground, hook_plan, true, false, &mut announcer)?;
+ // `SynchronousForNonCurrent`: prune keeps the rename-failure fallback's
+ // `.git/config` rewrite serialized with its integration-check readers.
+ handle_remove_output(
+ &plan,
+ ctx.foreground,
+ ctx.hook_plan,
+ true,
+ false,
+ &mut announcer,
+ BackgroundFallbackMode::SynchronousForNonCurrent,
+ )?;
announcer.flush()?;
Ok(true)
}
+fn can_attempt_candidate_removal(
+ candidate: &Candidate,
+ repo: &Repository,
+ config: &UserConfig,
+ worktrees: &[WorktreeInfo],
+ snapshot: &RefSnapshot,
+) -> anyhow::Result<bool> {
+ if matches!(
+ candidate.kind,
+ CandidateKind::BranchOnly | CandidateKind::StaleDetached
+ ) {
+ return Ok(true);
+ }
+
+ let target = candidate.remove_target()?;
+ Ok(repo
+ .prepare_worktree_removal(
+ target,
+ BranchDeletionMode::SafeDelete,
+ false,
+ config,
+ None,
+ Some(worktrees),
+ Some(snapshot),
+ )
+ .is_ok())
+}
+
/// Walk the worktree list and the local branch list to build the set of
/// candidates whose integration status needs checking.
///
@@ -243,14 +296,11 @@ fn gather_check_items(
}
if wt.is_prunable() {
- if let Some(branch) = &wt.branch {
- check_items.push(CheckItem {
- integration_ref: branch.clone(),
- source: CheckSource::Prunable {
- branch: branch.clone(),
- },
- });
- }
+ let integration_ref = wt.branch.clone().unwrap_or_else(|| wt.head.clone());
+ check_items.push(CheckItem {
+ integration_ref,
+ source: CheckSource::Prunable { wt_idx: idx },
+ });
continue;
}
@@ -415,23 +465,20 @@ fn render_dry_run(
///
/// `pre-remove` runs only when a *live linked* worktree is removed (stale-
/// metadata and orphan-branch removals delete just the branch — no
-/// `pre-remove`/`post-remove`/`post-switch`). The integration checks haven't
-/// run yet, so every linked worktree is fed to the plan — its `pre-remove`
-/// selection is a superset of what executes (extra anchors are simply never
-/// looked up). `post-switch` is anchored at the primary worktree: a prune
-/// candidate is never the primary, so each removal's
-/// `RemoveResult::destination_path()` is `home_path()`. Every hook is selected
-/// from the invoking worktree's `.config/wt.toml`, whatever its anchor.
+/// `pre-remove`/`post-remove`/`post-switch`). Approval is built after
+/// integration, age, and removability checks have selected the exact live
+/// worktrees prune will attempt to remove. `post-switch` is anchored at the
+/// primary worktree only when the current worktree is in that removal set.
+/// Every hook is selected from the invoking worktree's `.config/wt.toml`,
+/// whatever its anchor.
///
/// A declined prompt yields an empty plan — every executor runs no hooks.
fn approve_prune_hooks(
repo: &Repository,
config: &UserConfig,
- worktrees: &[WorktreeInfo],
- check_items: &[CheckItem],
+ candidates: &[Candidate],
yes: bool,
) -> anyhow::Result<ApprovedHookPlan> {
- let primary_path = repo.home_path()?;
// Non-fatal: prune candidates with no project hooks must still prune even
// when the project identifier can't be resolved (the plan ends up empty
// and `approve` never needs it).
@@ -441,11 +488,11 @@ fn approve_prune_hooks(
// `.config/wt.toml` — the worktree `wt step prune` ran in.
let project_config = repo.load_project_config()?;
- let removed_worktree_paths: Vec<&Path> = check_items
+ let removed_worktree_paths: Vec<&Path> = candidates
.iter()
- .filter_map(|item| match &item.source {
- CheckSource::Linked { wt_idx } => Some(worktrees[*wt_idx].path.as_path()),
- _ => None,
+ .filter_map(|candidate| match candidate.kind {
+ CandidateKind::Current | CandidateKind::Other => candidate.path.as_deref(),
+ CandidateKind::BranchOnly | CandidateKind::StaleDetached => None,
})
.collect();
@@ -459,13 +506,19 @@ fn approve_prune_hooks(
pid,
);
}
- builder.add(
- &primary_path,
- &[HookType::PostSwitch],
- project_config.as_ref(),
- config,
- pid,
- );
+ if candidates
+ .iter()
+ .any(|candidate| matches!(candidate.kind, CandidateKind::Current))
+ {
+ let primary_path = repo.home_path()?;
+ builder.add(
+ &primary_path,
+ &[HookType::PostSwitch],
+ project_config.as_ref(),
+ config,
+ pid,
+ );
+ }
match builder.finish().approve(pid, yes)? {
Some(plan) => Ok(plan),
@@ -521,57 +574,30 @@ pub fn step_prune(
let default_branch = repo.default_branch();
- // Build the candidate set before approval: `approve_prune_hooks` needs the
- // linked worktrees prune might remove (each `pre-remove` is approved against
- // that worktree's own config). The integration checks below narrow this to
- // the actually-pruned set.
+ // Build the broad integration-check set first. Hook approval happens after
+ // these checks, age filtering, and a live-worktree removability preflight
+ // have selected the exact worktrees prune will attempt to remove.
let check_items = gather_check_items(&repo, worktrees, default_branch.as_deref())?;
- // For non-dry-run, build & approve the frozen hook plan upfront so we can
- // remove inline. Dry-run runs no hooks → empty plan.
- let hook_plan = if dry_run {
- ApprovedHookPlan::empty()
- } else {
- approve_prune_hooks(&repo, &config, worktrees, &check_items, yes)?
- };
-
- let mut removed: Vec<Candidate> = Vec::new();
- let mut deferred_current: Option<Candidate> = None;
let mut skipped_young: Vec<String> = Vec::new();
+ let mut candidates: Vec<Candidate> = Vec::new();
+ let mut events: Vec<PruneEvent> = Vec::new();
- // Parallel integration checks with inline removals.
+ // Parallel integration checks.
//
// Spawn integration checks on a background thread via rayon par_iter,
// sending each result through a channel as it completes. The main thread
// processes results as they arrive: age-filtering, printing "Skipped"
- // messages, and removing candidates immediately. This overlaps integration
- // checking with removal — output appears as soon as the first check
- // completes instead of waiting for all checks to finish.
+ // messages, and collecting removal candidates. The hook approval gate runs
+ // only after this has narrowed the broad check set.
//
- // `check_lock` serializes the parallel `integration_reason` readers
- // against the removal writer. Each `integration_reason` call (which fans
- // out git subprocesses that *read* `.git/config`) is held under a read
- // guard; `try_remove` is held under the write guard. On Windows the
- // config rewrite in `git branch -D` (lockfile+rename) briefly holds
- // `.git/config` with delete access, and a concurrent reader's `fopen` —
- // which does not pass `FILE_SHARE_DELETE` and is not retried — fails with
- // "Permission denied". The RwLock keeps no integration reader in flight
- // while a removal runs, without serializing the (parallel) checks
- // themselves. POSIX is unaffected but takes the same path.
- //
- // Scope of the guarantee: this closes the race on the instant-removal
- // fast path, where `git branch -D` runs *synchronously* inside
- // `try_remove` (after the worktree is renamed into trash) and is thus
- // under the write guard — that is the path the observed Windows failure
- // took. On the cross-filesystem / `.gitmodules` / Windows-file-lock
- // fallback, `execute_instant_removal_or_fallback` *must* defer branch
- // deletion into the detached `git worktree remove && git branch -D`
- // command (the worktree still references the branch until it is removed,
- // so an in-process `branch -D` would fail) — that deferred write runs
- // after the guard drops and is NOT covered here. The fallback is rare for
- // prune targets (integrated worktrees the user is done with; the
- // lock-prone current worktree is deferred last, after the check thread
- // has drained), so the residual exposure is small but non-zero.
+ // `check_lock` marks the Windows `.git/config` critical section. Each
+ // `integration_reason` call (which fans out git subprocesses that read
+ // `.git/config`) is held under a read guard. Later removals take the write
+ // guard around the branch-deleting paths that rewrite `.git/config` via
+ // lockfile+rename. The exact-approval phase ordering drains this thread
+ // before removals begin, but the explicit guard keeps the serialization
+ // local to prune if checks/removals are overlapped again.
let check_lock = Arc::new(RwLock::new(()));
let (tx, rx) = chan::unbounded();
let integration_refs: Vec<String> = check_items
@@ -606,17 +632,6 @@ pub fn step_prune(
});
});
- // Loop-invariant context shared by every `try_remove` call below.
- let removal_ctx = RemovalContext {
- repo: &repo,
- config: &config,
- foreground,
- hook_plan: &hook_plan,
- worktrees,
- snapshot: &snapshot_arc,
- check_lock: &check_lock,
- };
-
// Collect integration context alongside candidates for dry-run display.
let mut dry_run_info: Vec<(Candidate, DryRunInfo)> = Vec::new();
@@ -645,12 +660,7 @@ pub fn step_prune(
&& age < min_age_duration
{
if !dry_run {
- eprintln!(
- "{}",
- info_message(cformat!(
- "Skipped <bold>{label}</> (younger than {min_age})"
- ))
- );
+ events.push(PruneEvent::SkippedYoung(label.clone()));
}
skipped_young.push(label);
continue;
@@ -676,36 +686,59 @@ pub fn step_prune(
suffix: "",
};
dry_run_info.push((candidate, info));
- } else if is_current {
- deferred_current = Some(candidate);
- } else if try_remove(&candidate, &removal_ctx)
- .with_context(|| candidate.removal_context())?
- {
- removed.push(candidate);
+ } else {
+ let candidate_idx = candidates.len();
+ candidates.push(candidate);
+ events.push(PruneEvent::Candidate(candidate_idx));
}
continue;
}
- // Branch-only candidates: prunable (stale worktree) and orphan branches
- let (branch, suffix) = match &item.source {
- CheckSource::Prunable { branch } => (branch, " (stale)"),
- CheckSource::Orphan => (&item.integration_ref, " (branch only)"),
+ // Stale detached metadata and branch-only candidates: prunable
+ // branch worktrees and orphan branches.
+ let (branch, label, path, kind, suffix) = match &item.source {
+ CheckSource::Prunable { wt_idx } => {
+ let wt = &worktrees[*wt_idx];
+ let label = wt.branch.clone().unwrap_or_else(|| {
+ let short = repo.short_sha(&wt.head).unwrap_or_else(|_| wt.head.clone());
+ format!("(detached {short})")
+ });
+ match &wt.branch {
+ Some(branch) => (
+ Some(branch.clone()),
+ label,
+ None,
+ CandidateKind::BranchOnly,
+ " (stale)",
+ ),
+ None => (
+ None,
+ label,
+ Some(wt.path.clone()),
+ CandidateKind::StaleDetached,
+ " (stale)",
+ ),
+ }
+ }
+ CheckSource::Orphan => (
+ Some(item.integration_ref.clone()),
+ item.integration_ref.clone(),
+ None,
+ CandidateKind::BranchOnly,
+ " (branch only)",
+ ),
CheckSource::Linked { .. } => unreachable!(),
};
// Age check for orphan branches via reflog creation timestamp
if matches!(&item.source, CheckSource::Orphan)
&& min_age_duration > Duration::ZERO
+ && let Some(branch) = &branch
&& let Some(age) = orphan_branch_age(&repo, branch, now_secs)
&& age < min_age_duration
{
if !dry_run {
- eprintln!(
- "{}",
- info_message(cformat!(
- "Skipped <bold>{branch}</> (younger than {min_age})"
- ))
- );
+ events.push(PruneEvent::SkippedYoung(branch.clone()));
}
skipped_young.push(branch.clone());
continue;
@@ -713,10 +746,10 @@ pub fn step_prune(
let candidate = Candidate {
check_idx: idx,
- label: branch.clone(),
- branch: Some(branch.clone()),
- path: None,
- kind: CandidateKind::BranchOnly,
+ label,
+ branch,
+ path,
+ kind,
};
if dry_run {
let info = DryRunInfo {
@@ -725,10 +758,10 @@ pub fn step_prune(
suffix,
};
dry_run_info.push((candidate, info));
- } else if try_remove(&candidate, &removal_ctx)
- .with_context(|| candidate.removal_context())?
- {
- removed.push(candidate);
+ } else {
+ let candidate_idx = candidates.len();
+ candidates.push(candidate);
+ events.push(PruneEvent::Candidate(candidate_idx));
}
}
@@ -736,6 +769,63 @@ pub fn step_prune(
return render_dry_run(dry_run_info, skipped_young, min_age, format);
}
+ let mut removable = Vec::with_capacity(candidates.len());
+ let mut approval_candidates = Vec::new();
+ for candidate in &candidates {
+ let can_remove = can_attempt_candidate_removal(
+ candidate,
+ &repo,
+ &config,
+ worktrees,
+ snapshot_arc.as_ref(),
+ )?;
+ removable.push(can_remove);
+ if can_remove {
+ approval_candidates.push(candidate.clone());
+ }
+ }
+
+ let hook_plan = approve_prune_hooks(&repo, &config, &approval_candidates, yes)?;
+
+ // Loop-invariant context shared by every `try_remove` call below.
+ let removal_ctx = RemovalContext {
+ repo: &repo,
+ config: &config,
+ foreground,
+ hook_plan: &hook_plan,
+ worktrees,
+ snapshot: &snapshot_arc,
+ check_lock: &check_lock,
+ };
+
+ let mut removed: Vec<Candidate> = Vec::new();
+ let mut deferred_current: Option<Candidate> = None;
+ for event in events {
+ match event {
+ PruneEvent::SkippedYoung(label) => {
+ eprintln!(
+ "{}",
+ info_message(cformat!(
+ "Skipped <bold>{label}</> (younger than {min_age})"
+ ))
+ );
+ }
+ PruneEvent::Candidate(candidate_idx) => {
+ if !removable[candidate_idx] {
+ continue;
+ }
+ let candidate = candidates[candidate_idx].clone();
+ if matches!(candidate.kind, CandidateKind::Current) {
+ deferred_current = Some(candidate);
+ } else if try_remove(&candidate, &removal_ctx)
+ .with_context(|| candidate.removal_context())?
+ {
+ removed.push(candidate);
+ }
+ }
+ }
+ }
+
// Remove deferred current worktree last (cd-to-primary happens here)
if let Some(current) = deferred_current
&& try_remove(&current, &removal_ctx).with_context(|| current.removal_context())?
@@ -797,5 +887,38 @@ mod tests {
candidate(CandidateKind::Current, "feature").removal_context(),
"removing worktree for feature"
);
+ assert_eq!(
+ candidate(CandidateKind::StaleDetached, "gone").removal_context(),
+ "pruning stale worktree for gone"
+ );
+ }
+
+ #[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 prune_summary_counts_each_candidate_kind() {
+ let mut detached = candidate(CandidateKind::Other, "det");
+ detached.branch = None;
+ let candidates = [
+ candidate(CandidateKind::Other, "feat-a"),
+ candidate(CandidateKind::Other, "feat-b"),
+ detached,
+ candidate(CandidateKind::StaleDetached, "gone"),
+ candidate(CandidateKind::BranchOnly, "orphan"),
+ ];
+ // 2 worktree+branch, 2 detached (one live + one stale), 1 branch-only.
+ assert_eq!(
+ prune_summary(&candidates),
+ "2 worktrees & branches, 2 worktrees, 1 branch"
+ );
}
}
diff --git a/src/commands/worktree/finish.rs b/src/commands/worktree/finish.rs
index 236e98ffe..1ea09c218 100644
--- a/src/commands/worktree/finish.rs
+++ b/src/commands/worktree/finish.rs
@@ -33,11 +33,11 @@ use crate::commands::command_executor::CommandContext;
use crate::commands::context::CommandEnv;
use crate::commands::hook_plan::{ApprovedHookPlan, register_planned};
use crate::commands::hooks::HookAnnouncer;
-use crate::commands::repository_ext::{
- check_not_default_branch, compute_integration_reason, is_primary_worktree,
-};
+use crate::commands::repository_ext::{check_not_default_branch, is_primary_worktree};
use crate::commands::template_vars::TemplateVars;
-use crate::output::{handle_remove_output, post_hook_display_path, pre_hook_display_path};
+use crate::output::{
+ BackgroundFallbackMode, handle_remove_output, post_hook_display_path, pre_hook_display_path,
+};
/// Inputs to [`finish_after_merge`]. Owned by the caller; this struct just
/// bundles them so the function signature stays readable.
@@ -129,20 +129,6 @@ pub fn finish_after_merge(
current_wt.ensure_clean("remove worktree after merge", Some(current_branch), false)?;
let worktree_root = current_wt.root()?;
- // Capture a fresh snapshot AFTER the merge has updated the local
- // target ref (`update-ref` ran inside `handle_no_ff_merge` /
- // `handle_push`). Without this, `integration_reason` would observe
- // pre-merge state and misclassify the just-merged branch as
- // unmerged — the bug class PR #2507 worked around with
- // `ref_is_ancestor`.
- let snapshot = repo.capture_refs()?;
- let (integration_reason, _) = compute_integration_reason(
- repo,
- &snapshot,
- Some(current_branch),
- Some(target_branch),
- BranchDeletionMode::SafeDelete,
- );
let expected_path = path_mismatch(repo, current_branch, &worktree_root, config);
// No config snapshot: `pre-remove` / `post-remove` were selected and
@@ -155,12 +141,19 @@ pub fn finish_after_merge(
branch_name: Some(current_branch.to_string()),
deletion_mode: BranchDeletionMode::SafeDelete,
target_branch: Some(target_branch.to_string()),
- integration_reason,
force_worktree: false,
expected_path,
removed_commit: feature_commit.clone(),
};
- handle_remove_output(&remove_result, false, plan, false, false, announcer)?;
+ handle_remove_output(
+ &remove_result,
+ false,
+ plan,
+ false,
+ false,
+ announcer,
+ BackgroundFallbackMode::Detached,
+ )?;
true
};
diff --git a/src/commands/worktree/types.rs b/src/commands/worktree/types.rs
index ef0cf75e1..30b74c1ae 100644
--- a/src/commands/worktree/types.rs
+++ b/src/commands/worktree/types.rs
@@ -161,11 +161,6 @@ pub enum RemoveResult {
branch_name: Option<String>,
deletion_mode: BranchDeletionMode,
target_branch: Option<String>,
- /// Pre-computed integration reason (if branch is integrated with target).
- /// Computed upfront to avoid race conditions when removing multiple worktrees
- /// in background mode (background git operations can hold locks that cause
- /// subsequent integration checks to fail).
- integration_reason: Option<worktrunk::git::IntegrationReason>,
/// Force git worktree removal even with untracked files.
force_worktree: bool,
/// Expected path based on config template. `Some` when actual path differs
@@ -189,9 +184,9 @@ pub enum RemoveResult {
/// `origin/main` when upstream is ahead) or the local default branch.
/// `None` when no default branch is configured.
target_branch: Option<String>,
- /// Pre-computed integration reason, same as `RemovedWorktree`.
- /// Computed in `prepare_worktree_removal` so the output handler
- /// doesn't need to re-derive a `Repository` for the check.
+ /// Pre-computed integration reason. Branch-only removal has no
+ /// worktree-local `pre-remove` hook, so the integration decision can
+ /// be made during preparation.
integration_reason: Option<worktrunk::git::IntegrationReason>,
},
}
@@ -357,7 +352,6 @@ mod tests {
branch_name: Some("feature".to_string()),
deletion_mode: BranchDeletionMode::SafeDelete,
target_branch: Some("main".to_string()),
- integration_reason: Some(worktrunk::git::IntegrationReason::SameCommit),
force_worktree: false,
expected_path: None,
removed_commit: Some("abc1234567890".to_string()),
@@ -370,7 +364,6 @@ mod tests {
branch_name,
deletion_mode,
target_branch,
- integration_reason,
force_worktree,
expected_path,
removed_commit,
@@ -382,7 +375,6 @@ mod tests {
assert!(!deletion_mode.should_keep());
assert!(!deletion_mode.is_force());
assert_eq!(target_branch.as_deref(), Some("main"));
- assert!(integration_reason.is_some());
assert!(!force_worktree);
assert!(expected_path.is_none());
assert_eq!(removed_commit.as_deref(), Some("abc1234567890"));
@@ -455,7 +447,6 @@ mod tests {
branch_name: None, // Detached HEAD
deletion_mode: BranchDeletionMode::ForceDelete,
target_branch: None,
- integration_reason: None, // Force delete skips integration check
force_worktree: true,
expected_path: None,
removed_commit: None, // Detached HEAD may not have meaningful commit
diff --git a/src/main.rs b/src/main.rs
index 80950f694..d1593f6ec 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -62,7 +62,7 @@ use commands::{
handle_vars_list, handle_vars_set, resolve_worktree_arg, run_hook, run_switch, step_commit,
step_copy_ignored, step_diff, step_eval, step_for_each, step_prune, step_relocate, step_tether,
};
-use output::handle_remove_output;
+use output::{BackgroundFallbackMode, handle_remove_output};
use worktrunk::git::BranchDeletionMode;
use cli::{
@@ -1002,6 +1002,7 @@ fn handle_remove_command(args: RemoveArgs, yes: bool) -> anyhow::Result<()> {
false,
false,
&mut announcer,
+ BackgroundFallbackMode::Detached,
)?;
announcer.flush()?;
if json_mode {
@@ -1064,6 +1065,7 @@ fn handle_remove_command(args: RemoveArgs, yes: bool) -> anyhow::Result<()> {
false,
false,
&mut announcer,
+ BackgroundFallbackMode::Detached,
)?;
announcer.flush()
};
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index 7335ad771..b63bed230 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -16,6 +16,7 @@ use crate::commands::hooks::HookAnnouncer;
use crate::commands::process::{
HookLog, InternalOp, build_remove_command, build_remove_command_staged, spawn_detached,
};
+use crate::commands::repository_ext::compute_integration_reason;
use crate::commands::worktree::hooks::PostRemoveContext;
use crate::commands::worktree::{RemoveResult, SwitchBranchInfo, SwitchResult};
use worktrunk::config::UserConfig;
@@ -26,7 +27,8 @@ use worktrunk::git::Repository;
use worktrunk::git::path_dir_name;
use worktrunk::git::{
BranchDeletionMode, BranchDeletionOutcome, BranchDeletionResult, RemoveOptions,
- remove_worktree_with_cleanup, stage_worktree_removal, stop_fsmonitor_daemon,
+ delete_branch_if_safe, remove_worktree_with_cleanup, stage_worktree_removal,
+ stop_fsmonitor_daemon,
};
use worktrunk::path::format_path_for_display;
use worktrunk::progress::{Progress, format_stats_paren};
@@ -71,6 +73,36 @@ fn cleanup_staged_with_progress(staged: &Path) -> (usize, u64) {
// Background Removal Helpers
// ============================================================================
+/// The removal parameters shared by [`spawn_background_removal`] and
+/// [`execute_instant_removal_or_fallback`]. `branch_name` / `deletion_mode` /
+/// `target_branch` drive the freshly-recomputed branch deletion; the rest
+/// control the worktree removal itself.
+struct BackgroundRemoval<'a> {
+ worktree_path: &'a Path,
+ branch_name: Option<&'a str>,
+ deletion_mode: BranchDeletionMode,
+ target_branch: Option<&'a str>,
+ force_worktree: bool,
+ changed_directory: bool,
+}
+
+/// How a background removal behaves when the rename-into-trash fast path fails.
+#[derive(Clone, Copy)]
+pub enum BackgroundFallbackMode {
+ /// Spawn the legacy detached `git worktree remove` — the default for
+ /// `wt remove`, `wt merge`, and the picker.
+ Detached,
+ /// Run the fallback removal and branch deletion synchronously for a
+ /// non-current worktree. `wt step prune` uses this to keep the fallback's
+ /// `.git/config` rewrite serialized with its integration-check readers.
+ SynchronousForNonCurrent,
+}
+
+enum BackgroundRemovalPlan {
+ Detached(String),
+ CompletedSynchronously,
+}
+
/// Spawn background worktree removal: stop fsmonitor, rename-then-prune, spawn detached rm.
///
/// Shared sequence for both detached HEAD and branch background removal paths.
@@ -78,61 +110,77 @@ fn cleanup_staged_with_progress(staged: &Path) -> (usize, u64) {
fn spawn_background_removal(
repo: &Repository,
main_path: &Path,
- worktree_path: &Path,
- branch_to_delete: Option<&str>,
- force_worktree: bool,
+ removal: &BackgroundRemoval<'_>,
log_label: &str,
- changed_directory: bool,
+ fallback_mode: BackgroundFallbackMode,
) -> anyhow::Result<()> {
// Stop the fsmonitor daemon BEFORE rename (must happen while the path
// still exists — the IPC socket lives under its git dir). Force-kills a
// wedged daemon so it can't leak once the worktree is gone.
- stop_fsmonitor_daemon(&repo.worktree_at(worktree_path));
+ stop_fsmonitor_daemon(&repo.worktree_at(removal.worktree_path));
- let remove_command = execute_instant_removal_or_fallback(
- repo,
- worktree_path,
- branch_to_delete,
- force_worktree,
- changed_directory,
- );
+ let remove_plan = execute_instant_removal_or_fallback(repo, removal, fallback_mode)?;
- spawn_detached(
- repo,
- main_path,
- &remove_command,
- log_label,
- &HookLog::internal(InternalOp::Remove),
- None,
- )?;
+ if let BackgroundRemovalPlan::Detached(remove_command) = remove_plan {
+ spawn_detached(
+ repo,
+ main_path,
+ &remove_command,
+ log_label,
+ &HookLog::internal(InternalOp::Remove),
+ None,
+ )?;
+ }
Ok(())
}
-/// Execute instant worktree removal via rename-then-prune, returning the background command.
+/// Execute instant worktree removal via rename-then-prune.
///
/// This function has side effects: it renames the worktree directory and prunes git metadata.
/// On the fast path, the branch is also deleted synchronously (since after prune, the branch
/// is no longer checked out in any worktree), and the background command is just `rm -rf`.
-/// If rename fails (cross-filesystem, permissions, Windows file locking), returns the legacy
-/// `git worktree remove` command with branch deletion deferred to the background.
+/// If rename fails (cross-filesystem, permissions, Windows file locking), either returns the
+/// legacy `git worktree remove` command with branch deletion deferred to the background, or
+/// runs that fallback synchronously for non-current worktrees when the caller needs to keep
+/// the fallback's `.git/config` rewrite serialized with other git readers.
///
-/// The caller is responsible for spawning the returned command in the background.
+/// The caller is responsible for spawning detached plans in the background.
fn execute_instant_removal_or_fallback(
repo: &Repository,
- worktree_path: &Path,
- branch_to_delete: Option<&str>,
- force_worktree: bool,
- changed_directory: bool,
-) -> String {
+ removal: &BackgroundRemoval<'_>,
+ fallback_mode: BackgroundFallbackMode,
+) -> anyhow::Result<BackgroundRemovalPlan> {
+ let BackgroundRemoval {
+ worktree_path,
+ branch_name,
+ deletion_mode,
+ target_branch,
+ force_worktree,
+ changed_directory,
+ } = *removal;
+
+ if !force_worktree {
+ repo.worktree_at(worktree_path)
+ .ensure_clean("remove worktree", branch_name, true)?;
+ }
+
// Fast path: rename worktree into .git/wt/trash/ (instant on same filesystem),
// prune git metadata, then background process just does `rm -rf`.
if let Some(staged_path) = stage_worktree_removal(repo, worktree_path) {
// Delete branch synchronously now that prune has removed the worktree metadata.
- // The branch is no longer checked out, so `git branch -D` will succeed.
- // This avoids a race where the user creates a new worktree with the same branch
- // name before the background `rm -rf` completes.
- if let Some(branch) = branch_to_delete
- && let Err(e) = repo.run_command(&["branch", "-D", branch])
+ // Re-capture refs here rather than trusting the pre-hook planning
+ // decision: hooks or concurrent processes may have advanced the branch.
+ if let Some(branch) = branch_name
+ && !deletion_mode.should_keep()
+ && let Err(e) = repo.capture_refs().and_then(|snapshot| {
+ delete_branch_if_safe(
+ repo,
+ &snapshot,
+ branch,
+ target_branch.unwrap_or("HEAD"),
+ deletion_mode.is_force(),
+ )
+ })
{
log::debug!("Failed to delete branch {} synchronously: {}", branch, e);
}
@@ -145,27 +193,88 @@ fn execute_instant_removal_or_fallback(
// is that Nushell may still emit PWD errors — not a correctness issue.
let _ = std::fs::create_dir(worktree_path);
}
- build_remove_command_staged(&staged_path, worktree_path, changed_directory)
+ Ok(BackgroundRemovalPlan::Detached(
+ build_remove_command_staged(&staged_path, worktree_path, changed_directory),
+ ))
} else {
+ if matches!(
+ fallback_mode,
+ BackgroundFallbackMode::SynchronousForNonCurrent
+ ) && !changed_directory
+ {
+ repo.remove_worktree(worktree_path, force_worktree)?;
+ if let Some(branch) = branch_name
+ && !deletion_mode.should_keep()
+ {
+ delete_branch_in_synchronous_fallback(repo, branch, target_branch, deletion_mode);
+ }
+ return Ok(BackgroundRemovalPlan::CompletedSynchronously);
+ }
+
// Fallback: cross-filesystem, permissions, Windows file locking, etc.
- // Use legacy git worktree remove which handles these cases.
- // Branch deletion stays in the background command since the worktree
- // still references the branch until `git worktree remove` runs.
- //
- // Git refuses to remove worktrees with initialized submodules without
- // --force. We preemptively set --force when .gitmodules exists — broader
- // than checking initialization, but harmless for clean worktrees.
- //
- // TOCTOU note: the clean check runs during planning in
- // prepare_worktree_removal(). In this fallback path, we may add --force
- // later (at execution time) when .gitmodules is present. That creates a
- // small check-vs-use window where newly introduced changes could be
- // removed. See remove_worktree() docs for the detailed safety analysis.
- let force = force_worktree || worktree_path.join(".gitmodules").exists();
- build_remove_command(worktree_path, branch_to_delete, force, changed_directory)
+ // Use legacy git worktree remove which handles these cases. Safe-delete
+ // uses Git's non-forcing branch deletion in the detached command; if
+ // the branch gained unmerged commits after the hook, Git retains it.
+ let command = match (branch_name, deletion_mode) {
+ (Some(branch), BranchDeletionMode::ForceDelete) => build_remove_command(
+ worktree_path,
+ Some(branch),
+ force_worktree,
+ changed_directory,
+ ),
+ (Some(branch), BranchDeletionMode::SafeDelete) => build_remove_command_safe_delete(
+ worktree_path,
+ branch,
+ force_worktree,
+ changed_directory,
+ ),
+ _ => build_remove_command(worktree_path, None, force_worktree, changed_directory),
+ };
+ Ok(BackgroundRemovalPlan::Detached(command))
}
}
+/// Delete the just-removed worktree's branch in the synchronous fallback path.
+///
+/// Only `wt step prune` reaches this (via `SynchronousForNonCurrent`). Mirrors
+/// the fast path above by re-capturing refs and calling `delete_branch_if_safe`,
+/// so squash-merged / patch-id-matched branches that prune accepted as candidates
+/// are deleted here too — a plain `git branch -d` would refuse them on
+/// reachability from HEAD alone and leave the branch behind while the worktree
+/// was already removed. The caller filters out `None` branches and `Keep` modes.
+fn delete_branch_in_synchronous_fallback(
+ repo: &Repository,
+ branch: &str,
+ target_branch: Option<&str>,
+ deletion_mode: BranchDeletionMode,
+) {
+ if let Err(e) = repo.capture_refs().and_then(|snapshot| {
+ delete_branch_if_safe(
+ repo,
+ &snapshot,
+ branch,
+ target_branch.unwrap_or("HEAD"),
+ deletion_mode.is_force(),
+ )
+ }) {
+ log::debug!("Failed to delete branch {branch} in synchronous fallback: {e}");
+ }
+}
+
+fn build_remove_command_safe_delete(
+ worktree_path: &Path,
+ branch_name: &str,
+ force_worktree: bool,
+ changed_directory: bool,
+) -> String {
+ use shell_escape::unix::escape;
+
+ let remove_command =
+ build_remove_command(worktree_path, None, force_worktree, changed_directory);
+ let branch_escaped = escape(branch_name.into());
+ format!("{remove_command} && git branch -d {branch_escaped}")
+}
+
/// List top-level entries remaining in a directory after a failed removal.
///
/// Returns None if the directory doesn't exist, can't be read, or is empty.
@@ -746,6 +855,13 @@ pub fn execute_user_command(command: &str, display_path: Option<&Path>) -> anyho
/// regardless of `foreground` (there's no detached `rm` to background to).
/// `silent` has no effect on `BranchOnly` results — the picker handles that
/// arm itself.
+///
+/// `background_fallback_mode` selects how a background removal whose
+/// rename-into-trash fast path fails behaves: every caller but `wt step prune`
+/// passes [`BackgroundFallbackMode::Detached`] (spawn the legacy `git worktree
+/// remove`); prune passes [`BackgroundFallbackMode::SynchronousForNonCurrent`]
+/// to keep the fallback's `.git/config` rewrite serialized with its parallel
+/// integration-check readers.
pub fn handle_remove_output(
result: &RemoveResult,
foreground: bool,
@@ -753,6 +869,7 @@ pub fn handle_remove_output(
quiet: bool,
silent: bool,
announcer: &mut HookAnnouncer<'_>,
+ background_fallback_mode: BackgroundFallbackMode,
) -> anyhow::Result<()> {
match result {
RemoveResult::RemovedWorktree {
@@ -762,7 +879,6 @@ pub fn handle_remove_output(
branch_name,
deletion_mode,
target_branch,
- integration_reason,
force_worktree,
expected_path,
removed_commit,
@@ -774,13 +890,13 @@ pub fn handle_remove_output(
branch_name: branch_name.as_deref(),
deletion_mode: *deletion_mode,
target_branch: target_branch.as_deref(),
- pre_computed_integration: *integration_reason,
force_worktree: *force_worktree,
expected_path: expected_path.as_deref(),
removed_commit: removed_commit.as_deref(),
plan,
foreground,
silent,
+ background_fallback_mode,
},
announcer,
),
@@ -973,9 +1089,9 @@ fn spawn_hooks_after_remove(
/// Information needed to display removal messages and hints.
///
-/// This struct captures the outcome of a branch deletion decision (whether
-/// pre-computed for background mode or actual for foreground mode) so that
-/// message formatting can be shared between both modes.
+/// This struct captures the outcome of a branch deletion decision (freshly
+/// computed for background mode or actual for foreground mode) so that message
+/// formatting can be shared between both modes.
struct RemovalDisplayInfo {
/// The deletion outcome (NotDeleted, ForceDeleted, or Integrated)
outcome: BranchDeletionOutcome,
@@ -990,10 +1106,10 @@ struct RemovalDisplayInfo {
}
impl RemovalDisplayInfo {
- /// Build display info from pre-computed integration (background mode).
+ /// Build display info from the refreshed integration check (background mode).
///
- /// Uses the pre-computed integration reason to avoid race conditions when
- /// removing multiple worktrees (background processes can hold git locks).
+ /// The caller refreshes this after `pre-remove` hooks and immediately
+ /// before staging/removing the worktree.
fn from_precomputed(
deletion_mode: BranchDeletionMode,
pre_computed_integration: Option<IntegrationReason>,
@@ -1185,7 +1301,6 @@ struct RemovedWorktreeOutputContext<'a> {
branch_name: Option<&'a str>,
deletion_mode: BranchDeletionMode,
target_branch: Option<&'a str>,
- pre_computed_integration: Option<IntegrationReason>,
force_worktree: bool,
expected_path: Option<&'a Path>,
removed_commit: Option<&'a str>,
@@ -1198,6 +1313,18 @@ struct RemovedWorktreeOutputContext<'a> {
/// progress/success messages, no trash-cleanup spinner, and no `cd`
/// directive — see [`handle_remove_output`].
silent: bool,
+ background_fallback_mode: BackgroundFallbackMode,
+}
+
+struct RefreshedRemovalSafety {
+ integration_reason: Option<IntegrationReason>,
+ target_branch: Option<String>,
+}
+
+impl RefreshedRemovalSafety {
+ fn target_branch(&self) -> Option<&str> {
+ self.target_branch.as_deref()
+ }
}
fn execute_pre_remove_hooks_if_needed(
@@ -1248,6 +1375,44 @@ fn execute_pre_remove_hooks_if_needed(
)
}
+fn refresh_removal_safety_after_pre_remove(
+ repo: &Repository,
+ ctx: &RemovedWorktreeOutputContext<'_>,
+) -> anyhow::Result<RefreshedRemovalSafety> {
+ // `pre-remove` hooks run arbitrary approved commands in the worktree being
+ // removed. Re-check before the rename/branch-delete cleanup uses this state.
+ if !ctx.force_worktree {
+ repo.worktree_at(ctx.worktree_path).ensure_clean(
+ "remove worktree",
+ ctx.branch_name,
+ true,
+ )?;
+ }
+
+ let mut target_branch = ctx.target_branch.map(String::from);
+ let integration_reason = if ctx.branch_name.is_some() && ctx.target_branch.is_some() {
+ let snapshot = repo.capture_refs()?;
+ let (reason, effective_target) = compute_integration_reason(
+ repo,
+ &snapshot,
+ ctx.branch_name,
+ ctx.target_branch,
+ ctx.deletion_mode,
+ );
+ if let Some(target) = effective_target {
+ target_branch = Some(target);
+ }
+ reason
+ } else {
+ None
+ };
+
+ Ok(RefreshedRemovalSafety {
+ integration_reason,
+ target_branch,
+ })
+}
+
fn prepare_remove_directory_change(
main_path: &Path,
changed_directory: bool,
@@ -1320,11 +1485,16 @@ fn handle_detached_removed_worktree_output(
spawn_background_removal(
repo,
ctx.main_path,
- ctx.worktree_path,
- None,
- ctx.force_worktree,
+ &BackgroundRemoval {
+ worktree_path: ctx.worktree_path,
+ branch_name: None,
+ deletion_mode: ctx.deletion_mode,
+ target_branch: ctx.target_branch,
+ force_worktree: ctx.force_worktree,
+ changed_directory: ctx.changed_directory,
+ },
"detached",
- ctx.changed_directory,
+ ctx.background_fallback_mode,
)?;
}
@@ -1337,6 +1507,7 @@ fn handle_detached_removed_worktree_output(
fn handle_named_removed_worktree_foreground(
repo: &Repository,
ctx: &RemovedWorktreeOutputContext<'_>,
+ safety: &RefreshedRemovalSafety,
branch_name: &str,
announcer: &mut HookAnnouncer<'_>,
) -> anyhow::Result<()> {
@@ -1360,7 +1531,7 @@ fn handle_named_removed_worktree_foreground(
RemoveOptions {
branch: Some(branch_name.to_string()),
deletion_mode: ctx.deletion_mode,
- target_branch: ctx.target_branch.map(String::from),
+ target_branch: safety.target_branch.clone(),
force_worktree: ctx.force_worktree,
},
)
@@ -1379,13 +1550,13 @@ fn handle_named_removed_worktree_foreground(
let display_info = RemovalDisplayInfo::from_branch_result(
output.branch_result,
branch_name,
- ctx.pre_computed_integration,
- ctx.target_branch,
+ safety.integration_reason,
+ safety.target_branch(),
ctx.force_worktree,
)?;
display_info.print_message(branch_name, true, Some(stats))?;
- display_info.print_hints(branch_name, ctx.deletion_mode, ctx.pre_computed_integration)?;
+ display_info.print_hints(branch_name, ctx.deletion_mode, safety.integration_reason)?;
print_switch_message_if_changed(ctx.changed_directory, ctx.main_path)?;
spawn_hooks_after_remove(repo, ctx, branch_name, announcer)?;
@@ -1396,6 +1567,7 @@ fn handle_named_removed_worktree_foreground(
fn handle_named_removed_worktree_background(
repo: &Repository,
ctx: &RemovedWorktreeOutputContext<'_>,
+ safety: &RefreshedRemovalSafety,
branch_name: &str,
announcer: &mut HookAnnouncer<'_>,
) -> anyhow::Result<()> {
@@ -1408,23 +1580,28 @@ fn handle_named_removed_worktree_background(
let display_info = RemovalDisplayInfo::from_precomputed(
ctx.deletion_mode,
- ctx.pre_computed_integration,
- ctx.target_branch,
+ safety.integration_reason,
+ safety.target_branch(),
ctx.force_worktree,
);
display_info.print_message(branch_name, false, None)?;
- display_info.print_hints(branch_name, ctx.deletion_mode, ctx.pre_computed_integration)?;
+ display_info.print_hints(branch_name, ctx.deletion_mode, safety.integration_reason)?;
print_switch_message_if_changed(ctx.changed_directory, ctx.main_path)?;
spawn_background_removal(
repo,
ctx.main_path,
- ctx.worktree_path,
- display_info.branch_deleted().then_some(branch_name),
- ctx.force_worktree,
+ &BackgroundRemoval {
+ worktree_path: ctx.worktree_path,
+ branch_name: Some(branch_name),
+ deletion_mode: ctx.deletion_mode,
+ target_branch: safety.target_branch(),
+ force_worktree: ctx.force_worktree,
+ changed_directory: ctx.changed_directory,
+ },
branch_name,
- ctx.changed_directory,
+ ctx.background_fallback_mode,
)?;
spawn_hooks_after_remove(repo, ctx, branch_name, announcer)?;
@@ -1442,13 +1619,14 @@ fn handle_removed_worktree_output(
let repo = worktrunk::git::Repository::at(ctx.main_path)?;
execute_pre_remove_hooks_if_needed(&repo, &ctx)?;
+ let safety = refresh_removal_safety_after_pre_remove(&repo, &ctx)?;
// TUI (picker) path: the removal runs in a background thread while skim
// owns the terminal, so no messages, no spinner, no `cd` directive (the
// picker manages its own cwd). The git removal runs inline — same as the
// foreground path, minus the chrome.
if ctx.silent {
- return remove_removed_worktree_silently(&repo, &ctx, announcer);
+ return remove_removed_worktree_silently(&repo, &ctx, &safety, announcer);
}
prepare_remove_directory_change(ctx.main_path, ctx.changed_directory)?;
@@ -1459,9 +1637,9 @@ fn handle_removed_worktree_output(
};
if ctx.foreground {
- handle_named_removed_worktree_foreground(&repo, &ctx, branch_name, announcer)
+ handle_named_removed_worktree_foreground(&repo, &ctx, &safety, branch_name, announcer)
} else {
- handle_named_removed_worktree_background(&repo, &ctx, branch_name, announcer)
+ handle_named_removed_worktree_background(&repo, &ctx, &safety, branch_name, announcer)
}
}
@@ -1479,13 +1657,14 @@ fn handle_removed_worktree_output(
fn remove_removed_worktree_silently(
repo: &Repository,
ctx: &RemovedWorktreeOutputContext<'_>,
+ safety: &RefreshedRemovalSafety,
announcer: &mut HookAnnouncer<'_>,
) -> anyhow::Result<()> {
let snapshot = repo.capture_refs()?;
let options = RemoveOptions {
branch: ctx.branch_name.map(String::from),
deletion_mode: ctx.deletion_mode,
- target_branch: ctx.target_branch.map(String::from),
+ target_branch: safety.target_branch.clone(),
force_worktree: ctx.force_worktree,
};
let output = remove_worktree_with_cleanup(repo, &snapshot, ctx.worktree_path, options)?;
diff --git a/src/output/mod.rs b/src/output/mod.rs
index bdfa06a04..b751e522e 100644
--- a/src/output/mod.rs
+++ b/src/output/mod.rs
@@ -47,8 +47,8 @@ pub(crate) use global::{
};
// Re-export output handlers
pub(crate) use handlers::{
- DirectivePassthrough, execute_shell_command, execute_user_command, handle_remove_output,
- handle_switch_output,
+ BackgroundFallbackMode, DirectivePassthrough, execute_shell_command, execute_user_command,
+ handle_remove_output, handle_switch_output,
};
// Re-export shell integration functions
pub(crate) use shell_integration::{
diff --git a/tests/integration_tests/merge.rs b/tests/integration_tests/merge.rs
index 0aca5aecd..a4dd63b96 100644
--- a/tests/integration_tests/merge.rs
+++ b/tests/integration_tests/merge.rs
@@ -3,7 +3,7 @@ use crate::common::{
mock_commands::{create_mock_cargo, create_mock_llm_auth},
repo, repo_with_alternate_primary, repo_with_feature_worktree, repo_with_main_worktree,
repo_with_multi_commit_feature, repo_with_remote, setup_snapshot_settings, wait_for_file,
- wait_for_file_content,
+ wait_for_file_content, wait_for_worktree_removed,
};
use insta::assert_snapshot;
use insta_cmd::assert_cmd_snapshot;
@@ -1802,6 +1802,75 @@ sync = "echo 'merged {{{{ branch }}}}' > {}"
);
}
+#[rstest]
+fn test_merge_pre_remove_dirty_mutation_aborts_cleanup(mut repo: TestRepo) {
+ repo.write_project_config(r#"pre-remove = "echo late > late.txt""#);
+ repo.commit("Add pre-remove hook");
+
+ let branch = "feature-pre-remove-dirty";
+ let feature_wt = repo.add_worktree_with_commit(branch, "feature.txt", "x", "feat: x");
+
+ let output = repo
+ .wt_command()
+ .current_dir(&feature_wt)
+ .args(["merge", "--yes"])
+ .output()
+ .unwrap();
+
+ assert!(
+ !output.status.success(),
+ "wt merge should fail cleanup after pre-remove dirties the worktree"
+ );
+ assert!(
+ feature_wt.join("late.txt").exists(),
+ "dirty file from pre-remove hook should be preserved"
+ );
+ assert!(
+ feature_wt.exists(),
+ "dirty feature worktree should not be removed"
+ );
+ repo.run_git(&["rev-parse", "--verify", &format!("refs/heads/{branch}")]);
+
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ stderr.contains("Cannot remove worktree") && stderr.contains("late.txt"),
+ "expected dirty-worktree cleanup failure, got:\n{stderr}"
+ );
+}
+
+#[rstest]
+fn test_merge_pre_remove_new_commit_keeps_branch(mut repo: TestRepo) {
+ repo.write_project_config(
+ r#"pre-remove = "sh -c 'printf late > late-commit.txt && git add late-commit.txt && git commit -m late-pre-remove'""#,
+ );
+ repo.commit("Add pre-remove hook");
+
+ let branch = "feature-pre-remove-commit";
+ let feature_wt = repo.add_worktree_with_commit(branch, "feature.txt", "x", "feat: x");
+
+ let output = repo
+ .wt_command()
+ .current_dir(&feature_wt)
+ .args(["merge", "--yes"])
+ .output()
+ .unwrap();
+
+ assert!(
+ output.status.success(),
+ "wt merge failed: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ wait_for_worktree_removed(&feature_wt);
+
+ let branch_ref = format!("refs/heads/{branch}");
+ repo.run_git(&["rev-parse", "--verify", &branch_ref]);
+ let late_file = repo.git_output(&["show", "--format=", "--name-only", &branch_ref]);
+ assert!(
+ late_file.lines().any(|line| line == "late-commit.txt"),
+ "branch should retain the pre-remove hook commit"
+ );
+}
+
#[rstest]
fn test_merge_race_condition_commit_after_push(mut repo_with_feature_worktree: TestRepo) {
let repo = &mut repo_with_feature_worktree;
diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rs
index 03f502ced..1e10a8a6b 100644
--- a/tests/integration_tests/remove.rs
+++ b/tests/integration_tests/remove.rs
@@ -1710,6 +1710,82 @@ approved-commands = ["echo 'hook ran' > {}"]
);
}
+#[rstest]
+fn test_pre_remove_hook_dirtying_worktree_blocks_foreground_remove(mut repo: TestRepo) {
+ let hook = "echo dirty > hook-created.txt";
+ repo.write_project_config(&format!(r#"pre-remove = "{hook}""#));
+ repo.commit("Add config");
+ repo.write_test_approvals(&format!(
+ r#"[projects."../origin"]
+approved-commands = ["{hook}"]
+"#
+ ));
+
+ let worktree_path = repo.add_worktree("feature-hook-dirties");
+ let output = repo
+ .wt_command()
+ .args(["remove", "--foreground", "feature-hook-dirties"])
+ .output()
+ .unwrap();
+
+ assert!(
+ !output.status.success(),
+ "remove should fail after pre-remove dirties the worktree; stderr:\n{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ assert!(
+ worktree_path.exists(),
+ "worktree must be preserved when the post-hook clean check fails"
+ );
+ assert!(
+ worktree_path.join("hook-created.txt").exists(),
+ "hook-created file should remain recoverable in the worktree"
+ );
+}
+
+#[rstest]
+fn test_pre_remove_hook_new_commit_retains_branch_in_background_remove(mut repo: TestRepo) {
+ use crate::common::wait_for_worktree_removed;
+
+ let hook = "echo hook > late-commit.txt && git add late-commit.txt && git commit -m late-hook";
+ repo.write_project_config(&format!(r#"pre-remove = "{hook}""#));
+ repo.commit("Add config");
+ repo.write_test_approvals(&format!(
+ r#"[projects."../origin"]
+approved-commands = ["{hook}"]
+"#
+ ));
+
+ let worktree_path = repo.add_worktree("feature-hook-commit");
+ let output = repo
+ .wt_command()
+ .args(["remove", "feature-hook-commit"])
+ .output()
+ .unwrap();
+
+ assert!(
+ output.status.success(),
+ "remove should keep the worktree cleanup path successful; stderr:\n{}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+ wait_for_worktree_removed(&worktree_path);
+
+ let branch = repo
+ .git_command()
+ .args([
+ "show-ref",
+ "--verify",
+ "--quiet",
+ "refs/heads/feature-hook-commit",
+ ])
+ .run()
+ .unwrap();
+ assert!(
+ branch.status.success(),
+ "branch must be retained after a pre-remove hook adds an unintegrated commit"
+ );
+}
+
/// `pre-remove` resolves `.config/wt.toml` from the invoking worktree — the one
/// `wt remove` ran in — while its template context (`{{ branch }}` etc.) is the
/// removed worktree's. The removed worktree's own config is not consulted.
@@ -2809,6 +2885,87 @@ fn test_remove_background_fallback_on_rename_failure(mut repo: TestRepo) {
let _ = std::fs::remove_file(&staged_path);
}
+/// Block the rename-into-trash fast path for `worktree_path` by pre-creating a
+/// regular file at its deterministic staged path. Returns that path so the
+/// caller can clean it up. (On POSIX a directory cannot be renamed onto an
+/// existing file, so `stage_worktree_removal` falls back to legacy removal.)
+fn block_staged_rename(repo: &TestRepo, worktree_path: &std::path::Path) -> std::path::PathBuf {
+ let trash_dir = crate::common::resolve_git_common_dir(repo.root_path()).join("wt/trash");
+ std::fs::create_dir_all(&trash_dir).unwrap();
+ let staged_path = trash_dir.join(format!(
+ "{}-{}",
+ worktree_path.file_name().unwrap().to_string_lossy(),
+ crate::common::TEST_EPOCH
+ ));
+ std::fs::write(&staged_path, "blocking file").unwrap();
+ staged_path
+}
+
+/// The rename-failure fallback honors `-D`: an unmerged branch is force-deleted
+/// in the legacy `git worktree remove && git branch -D` command.
+#[rstest]
+fn test_remove_background_fallback_force_delete_branch(mut repo: TestRepo) {
+ repo.commit("initial");
+ // Unmerged branch: a plain `-d` would refuse it, so this exercises the
+ // `BranchDeletionMode::ForceDelete` arm of the fallback command builder.
+ let worktree_path =
+ repo.add_worktree_with_commit("feature-force", "f.txt", "content", "unmerged commit");
+ let staged_path = block_staged_rename(&repo, &worktree_path);
+
+ let output = repo
+ .wt_command()
+ .args(["remove", "--force", "-D", "feature-force"])
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "wt remove --force -D should succeed via the legacy fallback: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ crate::common::wait_for("worktree removed by legacy fallback", || {
+ !worktree_path.exists()
+ });
+ crate::common::wait_for("unmerged branch force-deleted by legacy fallback", || {
+ let branches = repo
+ .git_command()
+ .args(["branch", "--list", "feature-force"])
+ .run()
+ .unwrap();
+ String::from_utf8_lossy(&branches.stdout).trim().is_empty()
+ });
+
+ let _ = std::fs::remove_file(&staged_path);
+}
+
+/// The rename-failure fallback removes a detached-HEAD worktree with no branch
+/// to delete — the `_` arm of the fallback command builder. `wt remove` resolves
+/// the detached worktree by path.
+#[rstest]
+fn test_remove_background_fallback_detached_worktree(mut repo: TestRepo) {
+ repo.commit("initial");
+ let worktree_path = repo.add_worktree("feature-detached");
+ repo.detach_head_in_worktree("feature-detached");
+ let staged_path = block_staged_rename(&repo, &worktree_path);
+
+ let output = repo
+ .wt_command()
+ .args(["remove", worktree_path.to_str().unwrap()])
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "wt remove of a detached worktree should succeed via the legacy fallback: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ crate::common::wait_for("detached worktree removed by legacy fallback", || {
+ !worktree_path.exists()
+ });
+
+ let _ = std::fs::remove_file(&staged_path);
+}
+
/// Stale staging directories from crashed removals are contained in `.git/wt/trash/`.
///
/// If `wt remove` is killed after `fs::rename()` succeeds but before the background
diff --git a/tests/integration_tests/step_prune.rs b/tests/integration_tests/step_prune.rs
index 24a9aeefe..473fb6250 100644
--- a/tests/integration_tests/step_prune.rs
+++ b/tests/integration_tests/step_prune.rs
@@ -239,6 +239,46 @@ fn test_prune_removes_multiple_detached(mut repo: TestRepo) {
);
}
+/// Prune removes an integrated detached-HEAD worktree through the synchronous
+/// fallback when the rename-into-trash fast path is blocked.
+///
+/// A detached worktree has no branch, so the fallback's branch deletion is a
+/// no-op — this covers that arm of `delete_branch_in_synchronous_fallback`.
+#[rstest]
+fn test_prune_detached_worktree_rename_fallback(mut repo: TestRepo) {
+ repo.commit("initial");
+ let wt_path = repo.add_worktree("detached-fallback");
+ repo.detach_head_in_worktree("detached-fallback");
+
+ // Pre-create a file at the computed staged path so `std::fs::rename`
+ // fails and prune takes the synchronous non-current fallback.
+ let trash_dir = crate::common::resolve_git_common_dir(repo.root_path()).join("wt/trash");
+ std::fs::create_dir_all(&trash_dir).unwrap();
+ let staged_path = trash_dir.join(format!(
+ "{}-{}",
+ wt_path.file_name().unwrap().to_string_lossy(),
+ crate::common::TEST_EPOCH
+ ));
+ std::fs::write(&staged_path, "blocking file to force fallback").unwrap();
+
+ let output = repo
+ .wt_command()
+ .args(["step", "prune", "--yes", "--min-age=0s"])
+ .output()
+ .unwrap();
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ output.status.success(),
+ "prune should remove a detached worktree via the fallback; stderr:\n{stderr}"
+ );
+ assert!(
+ !wt_path.exists(),
+ "the detached worktree should be removed before prune exits"
+ );
+
+ let _ = std::fs::remove_file(&staged_path);
+}
+
/// Prune skips locked worktrees
#[rstest]
fn test_prune_skips_locked(mut repo: TestRepo) {
@@ -375,6 +415,94 @@ fn test_prune_stale_worktree(mut repo: TestRepo) {
));
}
+/// Extract the `worktree <path>` line for the entry whose path ends with
+/// `dir_name` from `git worktree list --porcelain` output.
+///
+/// Returns git's own path string verbatim — the exact form `wt` emits in its
+/// JSON `path` field, since `WorktreeInfo::path` is `PathBuf::from(this)`.
+/// Deriving the expected value this way avoids the Windows mismatch where
+/// `std::fs::canonicalize` yields a `\\?\` verbatim, backslash-separated path
+/// while git reports a forward-slash one.
+fn porcelain_worktree_path<'a>(porcelain: &'a str, dir_name: &str) -> &'a str {
+ porcelain
+ .lines()
+ .filter_map(|line| line.strip_prefix("worktree "))
+ .find(|path| {
+ std::path::Path::new(path)
+ .file_name()
+ .is_some_and(|name| name == dir_name)
+ })
+ .unwrap_or_else(|| panic!("no worktree ending in {dir_name} in:\n{porcelain}"))
+}
+
+/// Prune handles stale detached metadata without deleting any branch.
+#[rstest]
+fn test_prune_stale_detached_worktree(repo: TestRepo) {
+ repo.commit("initial");
+
+ let wt_path = repo
+ .root_path()
+ .parent()
+ .unwrap()
+ .join("repo.stale-detached");
+ repo.run_git(&[
+ "worktree",
+ "add",
+ "--detach",
+ wt_path.to_str().unwrap(),
+ "HEAD",
+ ]);
+ let branches_before = repo.git_output(&["branch", "--format=%(refname:short)"]);
+
+ std::fs::remove_dir_all(&wt_path).unwrap();
+ let list_before = repo.git_output(&["worktree", "list", "--porcelain"]);
+ assert!(
+ list_before.contains("prunable"),
+ "Git should report stale detached worktree metadata before prune"
+ );
+ // Use git's own path string for the expectation — `wt`'s JSON `path` is
+ // `PathBuf::from` of exactly this, with no re-canonicalization.
+ let wt_path_str = porcelain_worktree_path(&list_before, "repo.stale-detached");
+
+ let output = repo
+ .wt_command()
+ .args([
+ "step",
+ "prune",
+ "--yes",
+ "--min-age=0s",
+ "--format=json",
+ "--foreground",
+ ])
+ .output()
+ .unwrap();
+ let stderr = String::from_utf8_lossy(&output.stderr)
+ .ansi_strip()
+ .into_owned();
+ assert!(output.status.success(), "prune failed\nstderr:\n{stderr}");
+
+ let items: Vec<serde_json::Value> = serde_json::from_slice(&output.stdout).unwrap();
+ assert_eq!(
+ items.len(),
+ 1,
+ "expected one pruned item\nstderr:\n{stderr}"
+ );
+ assert!(items[0]["branch"].is_null());
+ assert_eq!(items[0]["kind"].as_str(), Some("stale_worktree"));
+ assert_eq!(items[0]["path"].as_str(), Some(wt_path_str));
+
+ let list_after = repo.git_output(&["worktree", "list", "--porcelain"]);
+ assert!(
+ !list_after.contains(wt_path_str),
+ "Stale detached worktree metadata should be pruned"
+ );
+ let branches_after = repo.git_output(&["branch", "--format=%(refname:short)"]);
+ assert_eq!(
+ branches_after, branches_before,
+ "Pruning stale detached metadata should not delete branches"
+ );
+}
+
/// Min-age check passes when worktrees are old enough.
///
/// Uses a far-future epoch (2030) so real worktrees (created Feb 2026) appear
@@ -1037,6 +1165,70 @@ fn test_prune_pre_remove_needs_approval(mut repo: TestRepo) {
);
}
+/// An unmerged worktree is outside prune's removal set, so the `pre-remove` it
+/// would run is never part of the approval gate.
+#[rstest]
+fn test_prune_unmerged_pre_remove_is_not_approved(mut repo: TestRepo) {
+ repo.write_project_config(r#"pre-remove = "echo unmerged pre-remove""#);
+ repo.commit("Add pre-remove hook");
+ let wt_path = repo.add_worktree_with_commit(
+ "unmerged-with-hook",
+ "unmerged.txt",
+ "content",
+ "unmerged commit",
+ );
+
+ let output = repo
+ .wt_command()
+ .args(["step", "prune", "--foreground", "--min-age=0s"])
+ .output()
+ .unwrap();
+ let stderr = String::from_utf8_lossy(&output.stderr);
+
+ assert!(
+ output.status.success(),
+ "prune should not gate on an unmerged worktree's pre-remove; stderr:\n{stderr}"
+ );
+ assert!(
+ stderr.contains("No merged worktrees to remove"),
+ "prune should report no removable worktrees; stderr:\n{stderr}"
+ );
+ assert!(
+ !stderr.contains("needs approval"),
+ "unmerged pre-remove must not be requested for approval; stderr:\n{stderr}"
+ );
+ assert!(wt_path.exists(), "unmerged worktree should remain");
+}
+
+/// Removing only non-current worktrees does not switch directories, so the
+/// primary worktree's `post-switch` is outside prune's approval gate.
+#[rstest]
+fn test_prune_non_current_removal_does_not_approve_post_switch(mut repo: TestRepo) {
+ repo.write_project_config(r#"post-switch = "echo primary post-switch""#);
+ repo.commit("Add post-switch hook");
+ let wt_path = repo.add_worktree("merged-no-current");
+
+ let output = repo
+ .wt_command()
+ .args(["step", "prune", "--foreground", "--min-age=0s"])
+ .output()
+ .unwrap();
+ let stderr = String::from_utf8_lossy(&output.stderr);
+
+ assert!(
+ output.status.success(),
+ "prune should not gate on post-switch for non-current removals; stderr:\n{stderr}"
+ );
+ assert!(
+ !stderr.contains("needs approval"),
+ "primary post-switch must not be requested for approval; stderr:\n{stderr}"
+ );
+ assert!(
+ !wt_path.exists(),
+ "the merged non-current worktree should be removed"
+ );
+}
+
/// With `--yes`, `wt step prune` runs the `pre-remove` hook from the invoking
/// worktree's `.config/wt.toml` for each pruned worktree.
#[rstest]
@@ -1061,33 +1253,35 @@ fn test_prune_runs_pre_remove_hook(mut repo: TestRepo) {
assert!(!wt_path.exists(), "the merged worktree should be removed");
}
-/// Windows residual-race canary for the `wt step prune` fallback path.
+/// Regression test for serialized `wt step prune` fallback removals.
///
/// B-prime (the `check_lock` RwLock in `src/commands/step/prune.rs`)
/// serializes the parallel `integration_reason` `.git/config` readers against
-/// the *synchronous* fast-path `git branch -D` writer. The cross-filesystem /
-/// `.gitmodules` / Windows-file-lock fallback, however, defers branch
-/// deletion into a detached `git worktree remove && git branch -D` that runs
-/// *outside* the write guard (see the `check_lock` rationale comment for why
-/// it cannot be guarded there — the worktree still references the branch). A
-/// `git branch -D` of a branch with a `[branch "<name>"]` section rewrites
-/// `.git/config` via lockfile+rename.
+/// the config-rewriting branch deletion writer. That includes the
+/// cross-filesystem / `.gitmodules` / Windows-file-lock fallback: prune runs
+/// the non-current fallback removal and branch deletion synchronously under
+/// the write guard instead of spawning a detached `git worktree remove && git
+/// branch -d`. A branch with a `[branch "<name>"]` section makes deletion
+/// rewrite `.git/config` via lockfile+rename.
///
/// This forces that fallback for one non-current integrated worktree (by
/// pre-blocking its staged path, like
/// `test_remove_background_fallback_on_rename_failure`) while several other
/// integrated worktrees keep the parallel integration-check fan-out running,
-/// so the deferred config-rewriting `git branch -D` overlaps live
-/// `.git/config` readers.
+/// so the config-rewriting branch deletion overlaps live `.git/config`
+/// readers. After the fix, removal and deletion run synchronously inside
+/// `try_remove`, so `wt step prune` cannot exit before both finish — the
+/// regression assertion (`blocked` worktree and branch gone the instant prune
+/// returns) holds on every platform.
///
-/// On POSIX this is a deterministic fallback-path smoke test: a concurrent
-/// `.git/config` read and rename never collide, so it always passes. On
-/// Windows the same overlap can hit the documented residual gap — `git`
-/// failing with `unable to access '.git/config': Permission denied`,
-/// panicking prune. It is left in the normal suite (not a dedicated stress
-/// lane) deliberately: a Windows flake here is empirical proof the fallback
-/// path needs closing rather than the structurally-estimated "small" gap
-/// (issue #2801).
+/// On Unix a `git` shim on `PATH` additionally stalls the fallback's `git
+/// branch -d` for two seconds and records that it ran: proof prune *waits*
+/// for it rather than racing ahead. The shim is Unix-only because Rust's
+/// `Command` resolves a bare program name through `CreateProcess`, which
+/// appends only `.exe` and never finds a `git.cmd`/`git.bat` — the same
+/// reason `mock_commands` ships a real `mock-stub.exe` on Windows. Windows
+/// still exercises the fallback (the pre-blocked staged path) and the
+/// synchronous-completion assertion.
#[rstest]
fn test_prune_fallback_config_race_canary(mut repo: TestRepo) {
repo.commit("initial");
@@ -1095,8 +1289,8 @@ fn test_prune_fallback_config_race_canary(mut repo: TestRepo) {
// Several integrated worktrees → a real parallel integration-check
// fan-out. `add_worktree` puts each branch at `main` HEAD, so all are
// same-commit integrated and will be pruned. Each branch gets a
- // `[branch "<name>"]` section so its `git branch -D` rewrites
- // `.git/config` — the racing write. (No remote needed: `git branch -D`
+ // `[branch "<name>"]` section so its `git branch -d` rewrites
+ // `.git/config` — the racing write. (No remote needed: `git branch -d`
// removes the section regardless of whether `origin` resolves, and the
// same-commit local check yields "integrated" before upstream is
// consulted.)
@@ -1113,8 +1307,8 @@ fn test_prune_fallback_config_race_canary(mut repo: TestRepo) {
// Force the fallback for one *non-current* worktree by pre-creating a
// file at its computed staged path so `std::fs::rename(worktree → trash)`
- // fails. Pick one in the middle so integration checks for later refs are
- // still in flight when its deferred `git branch -D` fires.
+ // fails. Pick one in the middle so integration checks for later refs would
+ // still be in flight if fallback branch deletion escaped the write guard.
let blocked = names[3].clone();
let blocked_wt_path = repo.worktree_path(&blocked).to_path_buf();
let trash_dir = crate::common::resolve_git_common_dir(repo.root_path()).join("wt/trash");
@@ -1127,8 +1321,25 @@ fn test_prune_fallback_config_race_canary(mut repo: TestRepo) {
std::fs::write(&staged_path, "blocking file to force fallback").unwrap();
// Parallel fan-out is the point — do NOT pin RAYON_NUM_THREADS=1.
- let output = repo
- .wt_command()
+ let mut cmd = repo.wt_command();
+
+ // Unix only: a `git` shim that delays the fallback's branch deletion of
+ // `<blocked>` by two seconds and records that it ran. Before the fix that
+ // deletion ran in a detached shell, so prune could exit while the branch
+ // still existed; the shim proves the fixed path waits for it.
+ #[cfg(unix)]
+ let branch_delete_marker = repo.home_path().join("fallback-branch-delete-started");
+ #[cfg(unix)]
+ {
+ let git_wrapper_dir = repo.home_path().join("git-wrapper");
+ std::fs::create_dir_all(&git_wrapper_dir).unwrap();
+ write_delaying_git_wrapper(&git_wrapper_dir, &which::which("git").unwrap());
+ prepend_path(&mut cmd, &git_wrapper_dir);
+ cmd.env("WT_PRUNE_DELAY_BRANCH", &blocked);
+ cmd.env("WT_PRUNE_BRANCH_DELETE_STARTED", &branch_delete_marker);
+ }
+
+ let output = cmd
.args(["step", "prune", "--yes", "--min-age=0s"])
.output()
.unwrap();
@@ -1136,23 +1347,69 @@ fn test_prune_fallback_config_race_canary(mut repo: TestRepo) {
assert!(
output.status.success(),
- "prune should succeed; the documented Windows fallback-path race \
- would fail it here with a `.git/config` permission error \
+ "prune should succeed; the old Windows fallback-path race \
+ failed it here with a `.git/config` permission error \
(issue #2801).\nstderr:\n{stderr}"
);
assert!(
!stderr.contains("unable to access '.git/config'"),
- "residual fallback-path `.git/config` race fired — the fallback's \
- deferred `git branch -D` collided with a live integration-check \
+ "fallback-path `.git/config` race fired — the fallback's \
+ branch deletion collided with a live integration-check \
reader (issue #2801).\nstderr:\n{stderr}"
);
+ #[cfg(unix)]
+ assert!(
+ branch_delete_marker.exists(),
+ "delayed fallback branch deletion did not run"
+ );
+ assert!(
+ !blocked_wt_path.exists(),
+ "fallback worktree removal should finish before prune exits"
+ );
+ let branches = repo.git_output(&["branch", "--format=%(refname:short)"]);
+ assert!(
+ !branches.lines().any(|branch| branch == blocked),
+ "fallback branch deletion should finish before prune exits; branches:\n{branches}"
+ );
- // Removal-completion is intentionally NOT polled here. The race signal is
- // the prune exit + stderr above (immediate, deterministic on POSIX).
- // Detached background cleanup completing is load-sensitive and already
- // covered by `test_prune_multiple` and
- // `test_remove_background_fallback_on_rename_failure`; re-polling it under
- // this test's deliberately heavy fan-out would only add load-induced
- // flakiness with no canary value.
let _ = std::fs::remove_file(&staged_path);
}
+
+#[cfg(unix)]
+fn prepend_path(cmd: &mut std::process::Command, dir: &std::path::Path) {
+ let (path_var_name, current_path) = std::env::vars_os()
+ .find(|(key, _)| key.eq_ignore_ascii_case("PATH"))
+ .map(|(key, value)| (key, Some(value)))
+ .unwrap_or_else(|| ("PATH".into(), None));
+ let mut paths: Vec<std::path::PathBuf> = current_path
+ .as_deref()
+ .map(std::env::split_paths)
+ .into_iter()
+ .flatten()
+ .collect();
+ paths.insert(0, dir.to_path_buf());
+ cmd.env(path_var_name, std::env::join_paths(paths).unwrap());
+}
+
+#[cfg(unix)]
+fn write_delaying_git_wrapper(dir: &std::path::Path, real_git: &std::path::Path) {
+ use std::os::unix::fs::PermissionsExt;
+
+ let real_git = shell_escape::unix::escape(real_git.to_string_lossy());
+ // Match both `branch -d` and `branch -D` — `delete_branch_if_safe` uses
+ // `-D` for branches it has classified as integrated.
+ let script = format!(
+ r#"#!/bin/sh
+if [ "$1" = "branch" ] && {{ [ "$2" = "-d" ] || [ "$2" = "-D" ]; }} && [ "$3" = "$WT_PRUNE_DELAY_BRANCH" ]; then
+ : > "$WT_PRUNE_BRANCH_DELETE_STARTED"
+ sleep 2
+fi
+exec {real_git} "$@"
+"#
+ );
+ let path = dir.join("git");
+ std::fs::write(&path, script).unwrap();
+ let mut permissions = std::fs::metadata(&path).unwrap().permissions();
+ permissions.set_mode(0o755);
+ std::fs::set_permissions(&path, permissions).unwrap();
+}