Skip to content

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

perf(remove, prune): one check per guarantee in the removal chain (#3617)

Maximilian Roos5ecdf2bb788a
diff --git a/benches/CLAUDE.md b/benches/CLAUDE.md
index 7538c77ce..6b8f019b7 100644
--- a/benches/CLAUDE.md
+++ b/benches/CLAUDE.md
@@ -215,9 +215,9 @@ because its ~15 GiB fixture must never build on a hosted CI runner):
| Variant | Expected | What it measures |
|---------|----------|------------------|
-| `prune_e2e/dry_run_probe_cold` | ~160 ms | full parallel scan, probes re-run (`.git/wt/cache/` cleared; git's own caches stay warm — the "first prune after fetching main" shape) |
-| `prune_e2e/dry_run_warm` | ~90 ms | steady-state re-scan, probes hit sha_cache |
-| `prune_e2e/live` | ~620 ms | probe-cold scan + serial removal of the 8 candidates (~60 ms each, under the scan write lock) |
+| `prune_e2e/dry_run_probe_cold` | ~150 ms | full parallel scan, probes re-run (`.git/wt/cache/` cleared; git's own caches stay warm — the "first prune after fetching main" shape) |
+| `prune_e2e/dry_run_warm` | ~60 ms | steady-state re-scan, probes hit sha_cache |
+| `prune_e2e/live` | ~600 ms | probe-cold scan + serial removal of the 8 candidates (worktree candidates ~100 ms each — mostly the fsmonitor-daemon stop — branch-only ~25 ms, under the scan write lock, reusing scan-time plans) |
| `prune_real_repo/dry_run_warm` | ~0.25–0.8 s | steady-state scan of 72 items (36 worktrees + 36 branches) at 331k-commit scale |
| `prune_real_repo/dry_run_probe_cold` | ~0.6–1 s | the same 72-item scan with probes re-running at real cost (statuses stay stat-warm) |
| `first_output/remove` | ~86 ms | single-target validation up to first output (`benches/time_to_first_output.rs`) |
@@ -232,10 +232,12 @@ alone; a live one consumes the candidates). Expected one-shots on the
`git status` at ~4.5 s per fresh worktree; the probes are `merge-base
--is-ancestor` ~40 ms and `merge-tree --write-tree` ~130 ms (vs 4–25 ms
synthetic, where shallow history walks bottom out at subprocess-spawn cost)
-- **live ~12 s wall** — all 24 removals serialize under the scan write lock
- inside the `prune-scan` window: each of the 12 worktree candidates takes
- ~0.5–1.7 s (pre-remove re-checks plus drain waits), branch-only candidates
- ~50 ms
+- **live ~12 s wall** (measured before the removal chain was trimmed to one
+ clean check + daemon stop + rename + CAS delete; re-measure on the next
+ fixture rebuild) — all 24 removals serialize under the scan write lock
+ inside the `prune-scan` window: each of the 12 worktree candidates took
+ ~0.5–1.7 s, dominated by re-validation statuses running after the fsmonitor
+ daemon stop, branch-only candidates ~50 ms
This is the "prune takes many seconds" experience users report: worktree
count × stat-cold statuses bounds the scan, and removals extend it serially.
diff --git a/benches/prune.rs b/benches/prune.rs
index 9a8873ad0..e46476c28 100644
--- a/benches/prune.rs
+++ b/benches/prune.rs
@@ -6,9 +6,10 @@
// parallel on the rayon pool. Dominated by the merge-tree/merge-base
// probes, whose results persist in `.git/wt/cache/` (sha_cache), so the
// first scan after new commits is cold and later scans are warm.
-// 2. The removals — each integrated candidate runs the full removal chain
-// (pre-remove re-checks, fsmonitor stop, rename-to-trash, branch CAS
-// delete) serially under the write side of the scan lock.
+// 2. The removals — each integrated candidate runs the removal chain
+// (final clean check, fsmonitor stop, rename-to-trash, branch CAS
+// delete) serially under the write side of the scan lock, reusing the
+// removal plan its scan check computed.
//
// The fixture is `wt_perf::create_prune_repo_at`: squash-merged candidates
// (integrated by content — the expensive probe path, the post-PR-squash shape
diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rs
index b5b4a93ee..e14fc8036 100644
--- a/src/commands/picker/mod.rs
+++ b/src/commands/picker/mod.rs
@@ -2800,6 +2800,7 @@ 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,
removed_commit: None,
};
@@ -2894,6 +2895,7 @@ pub mod tests {
branch_name: None,
deletion_mode: BranchDeletionMode::SafeDelete,
target_branch: Some("main".to_string()),
+ integration_reason: None,
force_worktree: false,
removed_commit: None,
};
@@ -2984,6 +2986,7 @@ 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,
removed_commit: None,
};
@@ -3670,6 +3673,7 @@ 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,
removed_commit: None,
};
@@ -3685,6 +3689,7 @@ pub mod tests {
branch_name: None,
deletion_mode: BranchDeletionMode::SafeDelete,
target_branch: Some("main".to_string()),
+ integration_reason: None,
force_worktree: false,
removed_commit: None,
};
@@ -4032,6 +4037,7 @@ pub mod tests {
branch_name: Some(branch.to_string()),
deletion_mode: mode,
target_branch: Some("main".to_string()),
+ integration_reason: None,
force_worktree: false,
removed_commit: None,
};
@@ -4129,6 +4135,7 @@ pub mod tests {
branch_name: Some("x".to_string()),
deletion_mode: BranchDeletionMode::SafeDelete,
target_branch: Some("main".to_string()),
+ integration_reason: None,
force_worktree: false,
removed_commit: None,
};
@@ -4187,6 +4194,7 @@ 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,
removed_commit: None,
};
@@ -4232,6 +4240,7 @@ 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,
removed_commit: None,
};
diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rs
index ace8377c7..74bbc6948 100644
--- a/src/commands/repository_ext.rs
+++ b/src/commands/repository_ext.rs
@@ -292,12 +292,24 @@ impl RepositoryCliExt for Repository {
primary_path
};
- // Resolve target branch for integration reason display
+ // Resolve target branch and integration verdict for display and
+ // retention prediction. The actual branch deletion re-decides against
+ // fresh refs (`delete_branch_if_safe`'s CAS), so this is display-only.
let default_branch = self.default_branch();
let target_branch = match (&default_branch, &branch_name) {
(Some(db), Some(bn)) if db == bn => None,
_ => default_branch,
};
+ let (integration_reason, target_branch) = match compute_integration_reason(
+ self,
+ snapshot,
+ branch_name.as_deref(),
+ target_branch.as_deref(),
+ deletion_mode,
+ ) {
+ (reason, Some(effective_target)) => (reason, Some(effective_target)),
+ (reason, None) => (reason, target_branch),
+ };
// Capture commit SHA before removal for post-remove hook template variables.
// This ensures {{ commit }} references the removed worktree's state.
@@ -317,6 +329,7 @@ impl RepositoryCliExt for Repository {
branch_name,
deletion_mode,
target_branch,
+ integration_reason,
force_worktree,
removed_commit,
})
diff --git a/src/commands/step/prune.rs b/src/commands/step/prune.rs
index e7fb3ea70..9e7272cdf 100644
--- a/src/commands/step/prune.rs
+++ b/src/commands/step/prune.rs
@@ -24,6 +24,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};
+use super::super::worktree::RemoveResult;
use crate::output::{BackgroundFallbackMode, handle_remove_output};
/// A candidate worktree or branch selected for removal.
@@ -77,6 +78,10 @@ impl Candidate {
}
}
+/// The current-worktree candidate held back until every other removal ran
+/// (its removal cd's the shell to the primary), with its scan-time plan.
+type DeferredCurrent = (Candidate, Option<RemoveResult>);
+
#[derive(Clone, Copy)]
enum CandidateKind {
Current,
@@ -188,7 +193,17 @@ 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> {
+///
+/// `plan` is the scan-time `prepare_worktree_removal` result from
+/// [`check_one`]. `Prunable` candidates arrive plan-less and prepare here,
+/// under the write lock, because preparing them prunes stale worktree
+/// metadata. Scan-time plans may be stale by execution; the pre-rename
+/// `ensure_clean` and the branch-delete CAS re-validate what matters.
+fn try_remove(
+ candidate: &Candidate,
+ plan: Option<RemoveResult>,
+ ctx: &RemovalContext<'_>,
+) -> anyhow::Result<bool> {
let _span = Span::new(format!("prune-remove:{}", candidate.label));
// The guard protects `()` — there is no shared state to corrupt, so a
// poisoned lock is meaningless here. Recover the guard rather than
@@ -201,21 +216,23 @@ fn try_remove(candidate: &Candidate, ctx: &RemovalContext<'_>) -> anyhow::Result
return Ok(true);
}
- let target = candidate.remove_target()?;
- let plan = match ctx.repo.prepare_worktree_removal(
- target,
- BranchDeletionMode::SafeDelete,
- false,
- 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(false);
- }
+ let plan = match plan {
+ Some(plan) => plan,
+ None => match ctx.repo.prepare_worktree_removal(
+ candidate.remove_target()?,
+ BranchDeletionMode::SafeDelete,
+ false,
+ 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(false);
+ }
+ },
};
let mut announcer = HookAnnouncer::new(ctx.repo, true);
// `SynchronousForNonCurrent`: prune keeps the rename-failure fallback's
@@ -255,9 +272,15 @@ struct SkippedApproval {
struct CheckOutcome {
effective_target: String,
reason: Option<IntegrationReason>,
- /// Result of `prepare_worktree_removal` — the same gate `wt remove` uses.
- /// Dirty, locked, and primary worktrees end up `false` and are filtered
- /// silently, never reported as "younger than" or processed downstream.
+ /// 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) under the write
+ /// lock. `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_worktrees()`, a mutation that must stay serialized.
+ plan: Option<RemoveResult>,
+ /// Whether the item passed the removability gate (see `plan`).
removable: bool,
/// `Some(_)` if `min_age` is set and the age could be resolved; the
/// caller compares against `min_age_duration` to decide on the skip.
@@ -284,12 +307,23 @@ fn check_one(
return Ok(CheckOutcome {
effective_target,
reason,
+ plan: None,
removable: false,
age: None,
});
}
- let removable = match &item.source {
- CheckSource::Prunable { .. } | CheckSource::Orphan => true,
+ 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];
let target = match &wt.branch {
@@ -304,9 +338,13 @@ fn check_one(
Some(worktrees),
Some(snapshot),
)
- .is_ok()
+ .ok()
}
};
+ let removable = match &item.source {
+ CheckSource::Prunable { .. } => true,
+ CheckSource::Orphan | CheckSource::Linked { .. } => plan.is_some(),
+ };
let age = if min_age_duration > Duration::ZERO {
match &item.source {
CheckSource::Linked { wt_idx } => worktree_age(repo, &worktrees[*wt_idx], now_secs)?,
@@ -319,6 +357,7 @@ fn check_one(
Ok(CheckOutcome {
effective_target,
reason,
+ plan,
removable,
age,
})
@@ -401,6 +440,7 @@ fn gather_check_items(
// Track branches seen via worktree entries so we don't double-count
// in the orphan branch scan below.
let mut seen_branches: HashSet<String> = HashSet::new();
+ let is_bare = repo.is_bare().context("checking whether repo is bare")?;
for (idx, wt) in worktrees.iter().enumerate() {
if let Some(branch) = &wt.branch {
@@ -435,13 +475,12 @@ fn gather_check_items(
continue;
}
- // Skip main worktree (non-linked); in bare repos all are linked,
- // so the default-branch check above is the primary guard.
- let wt_tree = repo.worktree_at(&wt.path);
- if !wt_tree
- .is_linked()
- .context("checking whether worktree is linked")?
- {
+ // Skip the main worktree: `git worktree list` puts it first (a
+ // documented guarantee), so no per-worktree `git rev-parse` probe is
+ // needed. Bare repos have no main worktree — `list_worktrees()`
+ // filters the bare entry, leaving only linked worktrees — so the
+ // default-branch check above is their primary guard.
+ if idx == 0 && !is_bare {
continue;
}
@@ -881,8 +920,8 @@ pub fn step_prune(
// `try_remove` immediately for positives. The current worktree is the one
// exception: its removal cd's to the primary, so defer it until last.
let scan_span = Span::new("prune-scan");
- let (removed, deferred_current) =
- std::thread::scope(|s| -> anyhow::Result<(Vec<Candidate>, Option<Candidate>)> {
+ let (removed, deferred_current) = std::thread::scope(
+ |s| -> anyhow::Result<(Vec<Candidate>, Option<DeferredCurrent>)> {
let (tx, rx) = chan::unbounded::<(usize, anyhow::Result<CheckOutcome>)>();
// Pre-shadow with references so `move` on s.spawn moves only `tx`
// (so it's dropped when the spawn ends and `rx` can terminate),
@@ -915,7 +954,7 @@ pub fn step_prune(
});
let mut removed: Vec<Candidate> = Vec::new();
- let mut deferred_current: Option<Candidate> = None;
+ let mut deferred_current: Option<DeferredCurrent> = None;
for (idx, outcome) in &rx {
let outcome = outcome.context("checking branch integration")?;
let Some(_reason) = outcome.reason else {
@@ -972,21 +1011,22 @@ pub fn step_prune(
kind,
};
if matches!(candidate.kind, CandidateKind::Current) {
- deferred_current = Some(candidate);
- } else if try_remove(&candidate, &removal_ctx)
+ deferred_current = Some((candidate, outcome.plan));
+ } else if try_remove(&candidate, outcome.plan, &removal_ctx)
.with_context(|| candidate.removal_context())?
{
removed.push(candidate);
}
}
Ok((removed, deferred_current))
- })?;
+ },
+ )?;
drop(scan_span);
let mut removed = removed;
// 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())?
+ if let Some((current, plan)) = deferred_current
+ && try_remove(&current, plan, &removal_ctx).with_context(|| current.removal_context())?
{
removed.push(current);
}
diff --git a/src/commands/worktree/finish.rs b/src/commands/worktree/finish.rs
index 7ead48b07..78acad5e2 100644
--- a/src/commands/worktree/finish.rs
+++ b/src/commands/worktree/finish.rs
@@ -32,7 +32,9 @@ 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, is_primary_worktree};
+use crate::commands::repository_ext::{
+ check_not_default_branch, compute_integration_reason, is_primary_worktree,
+};
use crate::commands::template_vars::TemplateVars;
use crate::output::{
BackgroundFallbackMode, handle_remove_output, post_hook_display_path, pre_hook_display_path,
@@ -132,13 +134,21 @@ pub fn finish_after_merge(
// No config snapshot: `pre-remove` / `post-remove` were selected and
// frozen into `plan` at the gate (anchored at `feature_path`), so the
// executor needs no config — it runs only the frozen `plan`.
+ let (integration_reason, effective_target) = compute_integration_reason(
+ repo,
+ &repo.capture_refs()?,
+ Some(current_branch),
+ Some(target_branch),
+ BranchDeletionMode::SafeDelete,
+ );
let remove_result = RemoveResult::RemovedWorktree {
main_path: destination_path.clone(),
worktree_path: worktree_root,
changed_directory: true,
branch_name: Some(current_branch.to_string()),
deletion_mode: BranchDeletionMode::SafeDelete,
- target_branch: Some(target_branch.to_string()),
+ target_branch: effective_target.or_else(|| Some(target_branch.to_string())),
+ integration_reason,
force_worktree: false,
removed_commit: feature_commit.clone(),
};
diff --git a/src/commands/worktree/types.rs b/src/commands/worktree/types.rs
index 20ea541ff..7ac638bc4 100644
--- a/src/commands/worktree/types.rs
+++ b/src/commands/worktree/types.rs
@@ -4,7 +4,7 @@
use std::path::{Path, PathBuf};
-use worktrunk::git::{BranchDeletionMode, RefType};
+use worktrunk::git::{BranchDeletionMode, IntegrationReason, RefType};
/// Flags indicating which merge operations occurred
#[derive(Debug, Clone, Copy)]
@@ -159,6 +159,10 @@ pub enum RemoveResult {
branch_name: Option<String>,
deletion_mode: BranchDeletionMode,
target_branch: Option<String>,
+ /// Integration verdict at planning time, for display and retention
+ /// prediction. The deletion itself re-decides against fresh refs via
+ /// `delete_branch_if_safe`'s atomic CAS, so this is never a safety input.
+ integration_reason: Option<IntegrationReason>,
/// Force git worktree removal even with untracked files.
force_worktree: bool,
/// Commit SHA of the removed worktree's HEAD, captured before removal.
@@ -273,6 +277,7 @@ mod tests {
branch_name: Some("feature".to_string()),
deletion_mode: BranchDeletionMode::default(),
target_branch: None,
+ integration_reason: None,
force_worktree: false,
removed_commit: None,
};
@@ -334,6 +339,7 @@ mod tests {
branch_name: Some("feature".to_string()),
deletion_mode: BranchDeletionMode::SafeDelete,
target_branch: Some("main".to_string()),
+ integration_reason: None,
force_worktree: false,
removed_commit: Some("abc1234567890".to_string()),
};
@@ -345,6 +351,7 @@ mod tests {
branch_name,
deletion_mode,
target_branch,
+ integration_reason: _,
force_worktree,
removed_commit,
} => {
@@ -426,6 +433,7 @@ mod tests {
branch_name: None, // Detached HEAD
deletion_mode: BranchDeletionMode::ForceDelete,
target_branch: None,
+ integration_reason: None,
force_worktree: true,
removed_commit: None, // Detached HEAD may not have meaningful commit
};
diff --git a/src/git/remove.rs b/src/git/remove.rs
index 8aadfbcae..cd080cefb 100644
--- a/src/git/remove.rs
+++ b/src/git/remove.rs
@@ -8,21 +8,25 @@
//!
//! # What happens during removal
//!
-//! 1. **fsmonitor daemon stopped** (best effort). [`stop_fsmonitor_daemon`]
+//! 1. **Clean check** (skipped with [`RemoveOptions::force_worktree`]). The
+//! final dirty-worktree gate, immediately before the mutation. It runs
+//! while the fsmonitor daemon is still up, so the daemon serves the status
+//! instead of the stop below forcing a full re-stat.
+//! 2. **fsmonitor daemon stopped** (best effort). [`stop_fsmonitor_daemon`]
//! runs against the target worktree before its path disappears: it sends
//! the graceful `git fsmonitor--daemon stop` IPC request, then verifies the
//! daemon is actually gone and force-kills it by PID if it has wedged.
//! Without this, a daemon that has stopped answering its socket leaks
//! forever once its worktree is removed.
-//! 2. **Fast-path trash staging.** The worktree directory is renamed into
+//! 3. **Fast-path trash staging.** The worktree directory is renamed into
//! `<git-common-dir>/wt/trash/<name>-<timestamp>/`. Same-filesystem renames
//! are instant metadata operations, so the user's workspace clears
//! immediately. The caller is responsible for eventually removing the
//! staged path — either synchronously or via a background process.
-//! 3. **Fallback removal.** If the rename fails (cross-filesystem, permission
+//! 4. **Fallback removal.** If the rename fails (cross-filesystem, permission
//! denied, Windows file locks), the code falls back to `git worktree remove`
//! (optionally with `--force`), which deletes files directly.
-//! 4. **Branch deletion** (optional). When a branch name is supplied, the
+//! 5. **Branch deletion** (optional). When a branch name is supplied, the
//! branch is deleted according to the requested [`BranchDeletionMode`]:
//! - [`Keep`](BranchDeletionMode::Keep): never delete.
//! - [`SafeDelete`](BranchDeletionMode::SafeDelete): delete only if
@@ -282,11 +286,12 @@ pub struct RemoveOptions {
/// Only consulted when `deletion_mode` is [`BranchDeletionMode::SafeDelete`].
/// `None` falls back to `HEAD`.
pub target_branch: Option<String>,
- /// Pass `--force` to the `git worktree remove` fallback.
+ /// Skip the clean check and pass `--force` to the `git worktree remove`
+ /// fallback.
///
- /// Does not affect the fast path — trash staging is unconditional and
- /// always preserves data (the renamed directory can be recovered from
- /// `<git-common-dir>/wt/trash/` until the caller deletes it).
+ /// Trash staging itself is unconditional and always preserves data (the
+ /// renamed directory can be recovered from `<git-common-dir>/wt/trash/`
+ /// until the caller deletes it).
pub force_worktree: bool,
}
@@ -329,8 +334,22 @@ pub fn remove_worktree_with_cleanup(
worktree_path: &Path,
options: RemoveOptions,
) -> anyhow::Result<RemovalOutput> {
- // Stop the fsmonitor daemon, force-killing a wedged one. Must happen while
- // the worktree path still exists (the IPC socket lives under its git dir).
+ // Final clean check, immediately before the rename. Runs while the
+ // fsmonitor daemon is still up (it serves this status; stopping it first
+ // would force a full re-stat) — the one dirty-worktree gate on this path.
+ if !options.force_worktree {
+ repo.worktree_at(worktree_path).ensure_clean(
+ "remove worktree",
+ options.branch.as_deref(),
+ true,
+ )?;
+ }
+
+ // Stop the fsmonitor daemon, force-killing a wedged one. Must happen after
+ // the clean check (above) and before the rename: on Windows the daemon
+ // holds a handle on the worktree that would fail the rename, and git's
+ // graceful stop resolves the daemon by worktree path, unreachable once
+ // the path moves.
stop_fsmonitor_daemon(&repo.worktree_at(worktree_path));
// Fast path: rename into .git/wt/trash/ (instant on same filesystem),
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index 3c6cd6b18..0ad9106c7 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -16,7 +16,6 @@ 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;
@@ -113,7 +112,8 @@ enum BackgroundRemovalPlan {
CompletedSynchronously,
}
-/// Spawn background worktree removal: stop fsmonitor, rename-then-prune, spawn detached rm.
+/// Spawn background worktree removal: clean-check, stop fsmonitor,
+/// rename-then-prune, spawn detached rm.
///
/// Shared sequence for both detached HEAD and branch background removal paths.
/// The caller is responsible for output messages before this call, and hooks after.
@@ -124,11 +124,6 @@ fn spawn_background_removal(
log_label: &str,
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(removal.worktree_path));
-
let remove_plan = execute_instant_removal_or_fallback(repo, removal, fallback_mode)?;
if let BackgroundRemovalPlan::Detached(remove_command) = remove_plan {
@@ -175,6 +170,14 @@ fn execute_instant_removal_or_fallback(
.ensure_clean("remove worktree", branch_name, true)?;
}
+ // Stop the fsmonitor daemon after the clean check (which it serves — a
+ // status right after the stop re-stats the whole tree) and before the
+ // rename (on Windows the daemon holds a handle on the worktree that would
+ // fail the rename, and git's graceful stop resolves the daemon by worktree
+ // path, unreachable once the path moves). Force-kills a wedged daemon so
+ // it can't leak once the worktree is gone.
+ stop_fsmonitor_daemon(&repo.worktree_at(worktree_path));
+
// 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) {
@@ -1012,6 +1015,7 @@ pub fn handle_remove_output(
branch_name,
deletion_mode,
target_branch,
+ integration_reason,
force_worktree,
removed_commit,
} => handle_removed_worktree_output(
@@ -1022,6 +1026,7 @@ pub fn handle_remove_output(
branch_name: branch_name.as_deref(),
deletion_mode: *deletion_mode,
target_branch: target_branch.as_deref(),
+ integration_reason: *integration_reason,
force_worktree: *force_worktree,
removed_commit: removed_commit.as_deref(),
plan,
@@ -1468,6 +1473,9 @@ struct RemovedWorktreeOutputContext<'a> {
branch_name: Option<&'a str>,
deletion_mode: BranchDeletionMode,
target_branch: Option<&'a str>,
+ /// Planning-time integration verdict (display and retention prediction
+ /// only — the deletion re-decides via `delete_branch_if_safe`'s CAS).
+ integration_reason: Option<IntegrationReason>,
force_worktree: bool,
removed_commit: Option<&'a str>,
/// The frozen, approved hook plan. `pre-remove` / `post-remove` /
@@ -1482,17 +1490,6 @@ struct RemovedWorktreeOutputContext<'a> {
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(
repo: &Repository,
ctx: &RemovedWorktreeOutputContext<'_>,
@@ -1541,44 +1538,6 @@ 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,
worktree_path: &Path,
@@ -1686,7 +1645,6 @@ 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<()> {
@@ -1703,7 +1661,7 @@ fn handle_named_removed_worktree_foreground(
RemoveOptions {
branch: Some(branch_name.to_string()),
deletion_mode: ctx.deletion_mode,
- target_branch: safety.target_branch.clone(),
+ target_branch: ctx.target_branch.map(String::from),
force_worktree: ctx.force_worktree,
},
)
@@ -1722,13 +1680,13 @@ fn handle_named_removed_worktree_foreground(
let display_info = RemovalDisplayInfo::from_branch_result(
output.branch_result,
branch_name,
- safety.integration_reason,
- safety.target_branch(),
+ ctx.integration_reason,
+ ctx.target_branch,
ctx.force_worktree,
)?;
display_info.print_message(branch_name, true, Some(stats))?;
- display_info.print_hints(branch_name, ctx.deletion_mode, safety.integration_reason)?;
+ display_info.print_hints(branch_name, ctx.deletion_mode, ctx.integration_reason)?;
print_switch_message_if_changed(ctx.changed_directory, ctx.main_path)?;
spawn_hooks_after_remove(repo, ctx, branch_name, announcer)?;
@@ -1739,27 +1697,26 @@ 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<()> {
let display_info = RemovalDisplayInfo::from_precomputed(
ctx.deletion_mode,
- safety.integration_reason,
- safety.target_branch(),
+ ctx.integration_reason,
+ ctx.target_branch,
ctx.force_worktree,
);
display_info.print_message(branch_name, false, None)?;
- display_info.print_hints(branch_name, ctx.deletion_mode, safety.integration_reason)?;
+ display_info.print_hints(branch_name, ctx.deletion_mode, ctx.integration_reason)?;
print_switch_message_if_changed(ctx.changed_directory, ctx.main_path)?;
// Planner predicted retention when the user asked to keep, or when the
- // integration check before this returned no reason — `print_hints` has
- // already explained either case. A `NotDeleted` outcome surprises only if
- // the planner predicted deletion.
+ // integration check at planning time returned no reason — `print_hints`
+ // has already explained either case. A `NotDeleted` outcome surprises only
+ // if the planner predicted deletion.
let planner_expected_retention =
- ctx.deletion_mode.should_keep() || safety.integration_reason.is_none();
+ ctx.deletion_mode.should_keep() || ctx.integration_reason.is_none();
spawn_background_removal(
repo,
@@ -1768,7 +1725,7 @@ fn handle_named_removed_worktree_background(
worktree_path: ctx.worktree_path,
branch_name: Some(branch_name),
deletion_mode: ctx.deletion_mode,
- target_branch: safety.target_branch(),
+ target_branch: ctx.target_branch,
force_worktree: ctx.force_worktree,
changed_directory: ctx.changed_directory,
planner_expected_retention,
@@ -1792,14 +1749,19 @@ 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)?;
+
+ // No re-validation after `pre-remove` hooks: the pre-rename `ensure_clean`
+ // in the removal core catches a hook-dirtied worktree, and the branch
+ // deletion re-decides against fresh refs (`delete_branch_if_safe`'s CAS)
+ // — one mechanism per guarantee. `ctx.integration_reason` /
+ // `ctx.target_branch` carry the planning-time verdict for display.
// 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, &safety, announcer);
+ return remove_removed_worktree_silently(&repo, &ctx, announcer);
}
prepare_remove_directory_change(ctx.main_path, ctx.worktree_path, ctx.changed_directory)?;
@@ -1810,9 +1772,9 @@ fn handle_removed_worktree_output(
};
if ctx.foreground {
- handle_named_removed_worktree_foreground(&repo, &ctx, &safety, branch_name, announcer)
+ handle_named_removed_worktree_foreground(&repo, &ctx, branch_name, announcer)
} else {
- handle_named_removed_worktree_background(&repo, &ctx, &safety, branch_name, announcer)
+ handle_named_removed_worktree_background(&repo, &ctx, branch_name, announcer)
}
}
@@ -1830,14 +1792,13 @@ 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: safety.target_branch.clone(),
+ target_branch: ctx.target_branch.map(String::from),
force_worktree: ctx.force_worktree,
};
let output = remove_worktree_with_cleanup(repo, &snapshot, ctx.worktree_path, options)?;
diff --git a/tests/integration_tests/step_prune.rs b/tests/integration_tests/step_prune.rs
index c2175ec71..774053472 100644
--- a/tests/integration_tests/step_prune.rs
+++ b/tests/integration_tests/step_prune.rs
@@ -1460,6 +1460,78 @@ 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 under the write lock
+/// rather than on the scan — so a `git` shim failing `worktree prune` 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) {
+ repo.commit("initial");
+
+ // Integrated branch whose worktree directory is deleted out-of-band → a
+ // stale (prunable) worktree entry, prune's `Prunable` check source.
+ repo.add_worktree("stale-merged");
+ std::fs::remove_dir_all(repo.worktree_path("stale-merged")).unwrap();
+
+ let mut cmd = repo.wt_command();
+ let git_wrapper_dir = repo.home_path().join("git-wrapper");
+ std::fs::create_dir_all(&git_wrapper_dir).unwrap();
+ write_failing_worktree_prune_wrapper(&git_wrapper_dir, &which::which("git").unwrap());
+ prepend_path(&mut cmd, &git_wrapper_dir);
+ let prune_failed_marker = repo.home_path().join("worktree-prune-failed");
+ cmd.env("WT_TEST_WORKTREE_PRUNE_FAILED", &prune_failed_marker);
+
+ let output = cmd
+ .args(["step", "prune", "--yes", "--min-age=0s"])
+ .output()
+ .unwrap();
+ 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}"
+ );
+ assert!(
+ prune_failed_marker.exists(),
+ "the shim never fired — the candidate's preparation was not exercised"
+ );
+ 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}"
+ );
+}
+
+/// A `git` shim that fails every `git worktree prune` and passes everything
+/// else through to the real git.
+#[cfg(unix)]
+fn write_failing_worktree_prune_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());
+ let script = format!(
+ r#"#!/bin/sh
+if [ "$1" = "worktree" ] && [ "$2" = "prune" ]; then
+ : > "$WT_TEST_WORKTREE_PRUNE_FAILED"
+ echo "shim: worktree prune disabled" >&2
+ exit 1
+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();
+}
+
#[cfg(unix)]
fn prepend_path(cmd: &mut std::process::Command, dir: &std::path::Path) {
let (path_var_name, current_path) = std::env::vars_os()