Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix(prune): serialize safe deletions and run hooks concurrently (#4337)
Maximilian Roosf4f1bbdef746
diff --git a/docs/src/content/docs/step.md b/docs/src/content/docs/step.mdindex d1ed1d075..de26b9632 100644--- a/docs/src/content/docs/step.md+++ b/docs/src/content/docs/step.md@@ -819,6 +819,8 @@ In `wt list`, candidates show `_` (same commit) or `⊂` (content integrated). RLocked worktrees, worktrees with uncommitted changes, and the main worktree are always skipped. The current worktree is removed last, triggering cd to the primary worktree. Pre-remove and post-remove hooks run for each removal; a candidate whose hooks include an unapproved project command is skipped with `(approval required)` (pre-approve with `wt config approvals add`, or pass `--yes`).+Removals and their hooks may run concurrently across worktrees. Each worktree's pre-remove hooks finish before its removal begins. Hooks must coordinate writes to shared resources and avoid writing into other worktrees being pruned. On Windows, rewriting shared Git configuration from a hook can cause concurrent Git reads to fail.+### Min-age guardCandidates younger than `--min-age` (default: 1 day) are skipped. A worktree's age comes from its creation time. A branch with no worktree takes its age from its oldest reflog entry, or, when it has none (common in bare repositories), from when git last wrote its ref. Operations such as `git gc` or deleting a branch can rewrite many refs at once, so afterwards older branches without a reflog are skipped until `--min-age` has passed. This prevents removing a worktree just created from the default branch: it looks "merged" because its branch points at the same commit.diff --git a/plugins/worktrunk/skills/worktrunk/reference/step.md b/plugins/worktrunk/skills/worktrunk/reference/step.mdindex 9ed9c7107..cc2cd1379 100644--- a/plugins/worktrunk/skills/worktrunk/reference/step.md+++ b/plugins/worktrunk/skills/worktrunk/reference/step.md@@ -807,6 +807,8 @@ In `wt list`, candidates show `_` (same commit) or `⊂` (content integrated). RLocked worktrees, worktrees with uncommitted changes, and the main worktree are always skipped. The current worktree is removed last, triggering cd to the primary worktree. Pre-remove and post-remove hooks run for each removal; a candidate whose hooks include an unapproved project command is skipped with `(approval required)` (pre-approve with `wt config approvals add`, or pass `--yes`).+Removals and their hooks may run concurrently across worktrees. Each worktree's pre-remove hooks finish before its removal begins. Hooks must coordinate writes to shared resources and avoid writing into other worktrees being pruned. On Windows, rewriting shared Git configuration from a hook can cause concurrent Git reads to fail.+### Min-age guardCandidates younger than `--min-age` (default: 1 day) are skipped. A worktree's age comes from its creation time. A branch with no worktree takes its age from its oldest reflog entry, or, when it has none (common in bare repositories), from when git last wrote its ref. Operations such as `git gc` or deleting a branch can rewrite many refs at once, so afterwards older branches without a reflog are skipped until `--min-age` has passed. This prevents removing a worktree just created from the default branch: it looks "merged" because its branch points at the same commit.diff --git a/skills/worktrunk/reference/step.md b/skills/worktrunk/reference/step.mdindex 9ed9c7107..cc2cd1379 100644--- a/skills/worktrunk/reference/step.md+++ b/skills/worktrunk/reference/step.md@@ -807,6 +807,8 @@ In `wt list`, candidates show `_` (same commit) or `⊂` (content integrated). RLocked worktrees, worktrees with uncommitted changes, and the main worktree are always skipped. The current worktree is removed last, triggering cd to the primary worktree. Pre-remove and post-remove hooks run for each removal; a candidate whose hooks include an unapproved project command is skipped with `(approval required)` (pre-approve with `wt config approvals add`, or pass `--yes`).+Removals and their hooks may run concurrently across worktrees. Each worktree's pre-remove hooks finish before its removal begins. Hooks must coordinate writes to shared resources and avoid writing into other worktrees being pruned. On Windows, rewriting shared Git configuration from a hook can cause concurrent Git reads to fail.+### Min-age guardCandidates younger than `--min-age` (default: 1 day) are skipped. A worktree's age comes from its creation time. A branch with no worktree takes its age from its oldest reflog entry, or, when it has none (common in bare repositories), from when git last wrote its ref. Operations such as `git gc` or deleting a branch can rewrite many refs at once, so afterwards older branches without a reflog are skipped until `--min-age` has passed. This prevents removing a worktree just created from the default branch: it looks "merged" because its branch points at the same commit.diff --git a/src/cli/step.rs b/src/cli/step.rsindex 64765958d..804a9bce2 100644--- a/src/cli/step.rs+++ b/src/cli/step.rs@@ -621,6 +621,8 @@ In `wt list`, candidates show `_` (same commit) or `⊂` (content integrated). RLocked worktrees, worktrees with uncommitted changes, and the main worktree are always skipped. The current worktree is removed last, triggering cd to the primary worktree. Pre-remove and post-remove hooks run for each removal; a candidate whose hooks include an unapproved project command is skipped with `(approval required)` (pre-approve with `wt config approvals add`, or pass `--yes`).+Removals and their hooks may run concurrently across worktrees. Each worktree's pre-remove hooks finish before its removal begins. Hooks must coordinate writes to shared resources and avoid writing into other worktrees being pruned. On Windows, rewriting shared Git configuration from a hook can cause concurrent Git reads to fail.+## Min-age guardCandidates younger than `--min-age` (default: 1 day) are skipped. A worktree's age comes from its creation time. A branch with no worktree takes its age from its oldest reflog entry, or, when it has none (common in bare repositories), from when git last wrote its ref. Operations such as `git gc` or deleting a branch can rewrite many refs at once, so afterwards older branches without a reflog are skipped until `--min-age` has passed. This prevents removing a worktree just created from the default branch: it looks "merged" because its branch points at the same commit.diff --git a/src/commands/process.rs b/src/commands/process.rsindex 58a944e4b..b522a29fe 100644--- a/src/commands/process.rs+++ b/src/commands/process.rs@@ -20,6 +20,8 @@ use crate::commands::hook_filter::HookSource;pub enum InternalOp {/// Background worktree removal (`wt remove` in background mode)Remove,+ /// Delayed cleanup of the removed current worktree's empty PWD placeholder.+ RemovePlaceholder,/// Background cleanup of stale entries in `.git/wt/trash/`TrashSweep,}@@ -590,139 +592,28 @@ fn parse_trash_entry_timestamp(name: &str) -> Option<u64> {suffix.parse::<u64>().ok()}-/// Build shell command for background removal of a staged (renamed) worktree.+/// Remove an already-staged worktree's trash independently of branch deletion.///-/// This is used after the worktree has been renamed to a staging path,-/// git metadata has been pruned, and the branch has been deleted synchronously.-///-/// When `changed_directory` is true — the shell is cd-ing away from the removed-/// worktree — a placeholder directory is created at `original_path` so the shell's-/// working directory remains valid until the wrapper has processed the `cd`-/// directive. Without this, shells that validate `$env.PWD` (notably Nushell)-/// emit errors between binary exit and the `cd`. The background command then-/// waits for the shell wrapper before cleaning up the placeholder.-///-/// When `changed_directory` is false, no placeholder exists, so the background-/// command just removes the staged directory directly.-///-/// # Design alternatives evaluated (2026-04)-///-/// Two weaknesses in the current design prompted an investigation:-///-/// 1. **Silent `rmdir` failure.** If anything lands in the placeholder-/// during the 1-second sleep (e.g., macOS `.DS_Store`, a filesystem-/// race, an editor saving against the old path), `rmdir` fails silently-/// because of `2>/dev/null`, and the empty directory at `original_path`-/// lingers forever. This was the root cause of an intermittent-/// `test_bare_repo_merge_workflow` flake.-/// 2. **"Create then delete" placeholder lifecycle.** wt creates an empty-/// directory that the background shell removes one second later; its-/// only purpose is keeping `$PWD` valid for shells (notably Nushell)-/// that stat it between wt's exit and the wrapper's `cd`.-///-/// Two alternatives were prototyped and reviewed; neither was adopted.-///-/// ## Option A — Fully deferred cleanup with a pending-removal marker-///-/// Sync phase shrinks to: write a `PendingRemoval` marker under-/// `<git-common-dir>/wt/pending/`, spawn detached `wt internal-/// finish-removal <marker>`, exit. The detached process sleeps 1 second,-/// then does rename + prune + `branch -D` + `rm -rf` + marker delete —-/// the work that today happens synchronously. Concurrent operations-/// (e.g., `wt switch --create <same-branch>` within the 1-second window)-/// check for matching markers and force-finish the cleanup inline via a-/// `finish_blocking_for` helper. Crashed cleanup processes are reclaimed-/// by extending the existing `sweep_stale_trash` path with a-/// `sweep_stale_pending` variant.-///-/// Benefits: eliminates the placeholder lifecycle entirely (the original-/// path never disappears during wt's execution, so `$PWD` stays valid-/// "for free"); no `rmdir` silent-failure mode; marker-based-/// coordination on the recreate race.-///-/// Drawbacks surfaced by Codex review:-///-/// - **Data safety (P1).** The clean-check runs sync but the rename-/// runs ~1 second later. Writes to existing files during that window-/// (editor save, background build) are silently renamed into trash-/// and `rm -rf`'d. Today's sync rename keeps that window-/// microsecond-wide. Mitigation: revalidate cleanliness in the-/// finisher and bail on dirty — but that turns "remove" into a silent-/// no-op visible only in log files.-/// - **Hook timing (P2).** `spawn_hooks_after_remove` runs right after-/// the sync phase returns. In the deferred design, `post-remove`-/// hooks fire while `git worktree list` still reports the worktree-/// and the branch still exists, contrary to the hook's documented-/// contract. Fix: move hook invocation into the finisher.-/// - **Retained-branch coordination (P1).** The marker's `branch` field-/// must be recorded independently of the `delete_branch` flag, or-/// `finish_blocking_for(Some("feature"), ..)` misses markers whose-/// branch was retained (`--no-delete-branch`, unmerged safe-delete).-/// - **Complexity cost.** New module (`src/commands/pending.rs`), new-/// hidden CLI subcommand (`wt internal finish-removal`), sweep-/// recovery, coordination calls in `plan_switch`,-/// `validate_worktree_creation`, and `handle_remove_command`. ~450-/// lines of new code plus tests.-///-/// ## Option B — Sync rename + `rm -rf` instead of `rmdir`-///-/// Keep the current sync phase (rename + prune + `branch -D` + create-/// placeholder), add the pending-removal marker + coordination hooks,-/// and in this function substitute `rm -rf <placeholder>` for-/// `rmdir <placeholder> 2>/dev/null`.-///-/// Benefits: fixes the flake's root cause (silent-failure mode gone);-/// inherits marker-based coordination; keeps the data-safety window at-/// microseconds; keeps hook timing correct.-///-/// Drawbacks:-///-/// - Doesn't eliminate the "create then delete" placeholder pattern —-/// just makes its cleanup robust.-/// - Introduces a narrow new window: if something writes to the-/// placeholder during the 1-second sleep, `rm -rf` deletes it.-/// Today's silent `rmdir` accidentally preserves such writes as-/// orphaned leftovers (ugly but data-preserving). Mitigation:-/// revalidate emptiness in the finisher and skip `rm -rf` on-/// non-empty placeholders — turns that accidental preservation into a-/// deliberate invariant.-///-/// ## Decision-///-/// Neither was adopted. The flaky test was fixed at the test layer by-/// teaching `wait_for_worktree_removed` to accept "gone or empty-/// placeholder" as the success condition — matching what-/// `assert_worktree_removed` already documents. If flakiness resurfaces-/// or the visible-placeholder aesthetic becomes a real friction point,-/// Option B is the low-risk path forward: strictly dominates main-/// except for the narrow write-into-placeholder edge case, and reuses-/// most of the pending-module work from Option A.-pub fn build_remove_command_staged(- staged_path: &std::path::Path,- original_path: &std::path::Path,- changed_directory: bool,-) -> String {+/// The worktree has been renamed and its registry entry pruned. This command+/// can start immediately; it never touches the original worktree path.+pub fn build_remove_command_staged(staged_path: &std::path::Path) -> String {use shell_escape::unix::escape;let staged_path_str = staged_path.to_string_lossy();let staged_escaped = escape(staged_path_str.as_ref().into());+ format!("rm -rf -- {}", staged_escaped)+}- if changed_directory {- let original_path_str = original_path.to_string_lossy();- let original_escaped = escape(original_path_str.as_ref().into());+/// Remove the empty shell-PWD placeholder after synchronous removal finishes.+///+/// The one-second delay gives the shell wrapper time to consume its cd+/// directive. `rmdir` preserves any files written into the original path.+pub fn build_remove_placeholder_command(original_path: &std::path::Path) -> String {+ use shell_escape::unix::escape;- // sleep 1: give the shell wrapper time to cd away before removing the placeholder.- // rmdir: remove the empty placeholder (safe — only removes empty directories).- // rm -rf: remove the staged worktree contents.- // Use -- to prevent option parsing for paths starting with -- format!(- "sleep 1 && rmdir -- {} 2>/dev/null; rm -rf -- {}",- original_escaped, staged_escaped- )- } else {- // No placeholder to clean up — just remove the staged directory.- format!("rm -rf -- {}", staged_escaped)- }+ let original_path_str = original_path.to_string_lossy();+ let original_escaped = escape(original_path_str.as_ref().into());+ format!("sleep 1 && rmdir -- {} 2>/dev/null", original_escaped)}/// Build shell command for background worktree removal (legacy path).@@ -897,17 +788,13 @@ mod tests {fn test_build_remove_command_staged() {let staged_path = PathBuf::from("/tmp/repo/.git/wt/trash/my-project.feature-1234567890");let original_path = PathBuf::from("/tmp/my-project.feature");+ assert_snapshot!(build_remove_command_staged(&staged_path), @"rm -rf -- /tmp/repo/.git/wt/trash/my-project.feature-1234567890");+ assert_snapshot!(build_remove_placeholder_command(&original_path), @"sleep 1 && rmdir -- /tmp/my-project.feature 2>/dev/null");- // changed_directory=true: placeholder cleanup before rm -rf- assert_snapshot!(build_remove_command_staged(&staged_path, &original_path, true), @"sleep 1 && rmdir -- /tmp/my-project.feature 2>/dev/null; rm -rf -- /tmp/repo/.git/wt/trash/my-project.feature-1234567890");-- // changed_directory=false: just rm -rf, no placeholder- assert_snapshot!(build_remove_command_staged(&staged_path, &original_path, false), @"rm -rf -- /tmp/repo/.git/wt/trash/my-project.feature-1234567890");-- // Shell escaping for special characters (space in path)let special_path = PathBuf::from("/tmp/repo/.git/wt/trash/test worktree-123");let special_original = PathBuf::from("/tmp/test worktree");- assert_snapshot!(build_remove_command_staged(&special_path, &special_original, true), @"sleep 1 && rmdir -- '/tmp/test worktree' 2>/dev/null; rm -rf -- '/tmp/repo/.git/wt/trash/test worktree-123'");+ assert_snapshot!(build_remove_command_staged(&special_path), @"rm -rf -- '/tmp/repo/.git/wt/trash/test worktree-123'");+ assert_snapshot!(build_remove_placeholder_command(&special_original), @"sleep 1 && rmdir -- '/tmp/test worktree' 2>/dev/null");}#[test]diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rsindex 358fa6778..530e29b63 100644--- a/src/commands/repository_ext.rs+++ b/src/commands/repository_ext.rs@@ -569,7 +569,7 @@ pub(crate) fn compute_integration_reason(////// A branch reaches two worktrees only through `git worktree add --force`,/// which worktrunk never runs itself. Once it has, the ref is live in both, and-/// worktrunk deletes branches with `git update-ref -d` — git's compare-and-swap+/// worktrunk deletes branches with `git update-ref` — git's compare-and-swap/// primitive, which unlike `git branch -d` does not refuse a ref that is/// checked out somewhere. Deleting it leaves the other checkout at a null OID/// with an unresolvable `HEAD`, so every removal that could delete a branchdiff --git a/src/commands/step/prune.rs b/src/commands/step/prune.rsindex 6c3c0fbf6..ba6e1b6be 100644--- a/src/commands/step/prune.rs+++ b/src/commands/step/prune.rs@@ -3,10 +3,11 @@//! Live-path concurrency: candidate checks fan out on the rayon pool and//! stream results to the main thread, which queues per-candidate jobs//! (removals and skip lines) in scan-completion order onto a worker pool-//! sized like rayon's ([`RemovalJob`]). Checks and hook-free removals hold-//! the read side of [`RemovalContext::check_lock`] and run concurrently; the-//! exceptional removals serialize on the write side-//! ([`removal_needs_write`]). Repository operations coordinate the narrower+//! sized like rayon's ([`RemovalJob`]). Checks, background removals, and+//! their pre-remove hooks run concurrently. The output lock excludes other+//! removals and skip messages only while foreground/current removals own+//! terminal output ([`removal_needs_write`]).+//! Repository operations coordinate the narrower//! Git worktree-registry reads and teardowns themselves, so status checks,//! fsmonitor shutdown, and trash renames still overlap. One FIFO queue carrying//! both removals and skip lines means a single worker (`RAYON_NUM_THREADS=1`)@@ -233,38 +234,16 @@ struct RemovalContext<'a> {repo: &'a Repository,foreground: bool,hook_plan: &'a ApprovedHookPlan,- /// Coordinates the parallel workers (scan checks and removals, both on- /// the read side) against the few removals that need exclusivity (write- /// side — see [`removal_needs_write`]).- ///- /// The lock exists for the Windows `.git/config` race: git rewrites- /// config via lockfile + atomic rename, and a concurrent reader's plain- /// `fopen` fails on the rename (#2801). Historically every removal held- /// the write side because branch deletion was `git branch -D`, which- /// rewrites `.git/config` (it drops the `[branch "<name>"]` section —- /// even when none exists). The removal chain has since moved to the CAS- /// `git update-ref -d`, and neither it nor `git worktree remove` (both the- /// scoped metadata prune and the rename-failure fallback) touches- /// `.git/config`, so hook-free removals never rewrite it and can run- /// concurrently. Verified empirically: with `.git/config` made immutable,- /// only `git branch -D` reports `could not write config file`.- /// (`git branch -D` remains reachable only via `delete_branch_if_safe`'s- /// force arm, which prune never uses, and its snapshot-miss arm,- /// unreachable here because the chain captures the snapshot immediately- /// before consulting it.)- check_lock: &'a RwLock<()>,+ /// Keeps background removal output and skip messages out of a foreground+ /// spinner's terminal window. Shared guards do not serialize background+ /// removals or their hooks. Repository mutation coordination belongs to+ /// the registry accessors and the safe-ref deletion coordinator.+ output_lock: &'a RwLock<()>,}-/// Which removals must hold the write side of [`RemovalContext::check_lock`]+/// Which removals must hold the write side of [`RemovalContext::output_lock`]/// instead of joining the parallel (read-side) fan-out:///-/// - **Hook-bearing worktree removals** — the `pre-remove` body runs-/// foreground here, and hook bodies are arbitrary commands (`git branch-/// -D`, `git config`, anything), so it keeps the exclusion every removal-/// had before removals parallelized; the write side also keeps the hook-/// stream and announce lines from interleaving with other candidates'-/// output. (`post-remove`/`post-switch` pipelines spawn detached and-/// always ran outside the lock.)/// - **`--foreground` worktree removals** — the foreground path runs a TTY/// trash-cleanup spinner, and concurrent spinners would fight over the/// cursor.@@ -276,22 +255,17 @@ struct RemovalContext<'a> {/// a hook body nor a spinner, whatever selected it. `StaleDetached` never/// reaches here — [`try_remove`] prunes its entry and returns.///-/// Everything else fans out on the read side. The Git worktree-registry calls-/// inside those removals take their own repository-scoped lock; see-/// [`prune_worktree_entry`](Repository::prune_worktree_entry).+/// Everything else fans out on the read side, including pre-remove hooks.+/// The Git worktree-registry calls inside those removals take their own+/// repository-scoped lock; see [`prune_worktree_entry`](Repository::prune_worktree_entry).+/// Safe branch deletions serialize ref mutation independently of terminal output.fn removal_needs_write(kind: CandidateKind, plan: &RemovalPlan, ctx: &RemovalContext<'_>) -> bool {if matches!(kind, CandidateKind::Current) {return true;}match plan {- // The worktree whose `pre-remove` body and trash-cleanup spinner this- // removal runs.- RemovalPlan::Worktree { worktree_path, .. } => {- ctx.foreground- || ctx- .hook_plan- .has_hooks_for(worktree_path, &[HookType::PreRemove, HookType::PostRemove])- }+ // The foreground worktree cleanup owns the terminal spinner.+ RemovalPlan::Worktree { .. } => ctx.foreground,RemovalPlan::BranchOnly { .. } => false,}}@@ -317,8 +291,8 @@ fn try_remove(if matches!(candidate.kind, CandidateKind::StaleDetached) {// Output side: no exclusive output here (no spinner, no hook stream),- // so join the parallel read side of `check_lock`.- let _read = ctx.check_lock.read().unwrap_or_else(|e| e.into_inner());+ // so join the parallel read side of `output_lock`.+ let _read = ctx.output_lock.read().unwrap_or_else(|e| e.into_inner());// Name the stale entry rather than sweeping the repository, so a// sibling whose directory is merely absent right now (unmounted// volume, half-finished `mv`) keeps its registration. `gather_check_items`@@ -343,11 +317,11 @@ fn try_remove(let (_read, _write) = if removal_needs_write(candidate.kind, &plan, ctx) {(None,- Some(ctx.check_lock.write().unwrap_or_else(|e| e.into_inner())),+ Some(ctx.output_lock.write().unwrap_or_else(|e| e.into_inner())),)} else {(- Some(ctx.check_lock.read().unwrap_or_else(|e| e.into_inner())),+ Some(ctx.output_lock.read().unwrap_or_else(|e| e.into_inner())),None,)};@@ -421,8 +395,6 @@ struct CheckOutcome {}/// One check item's full parallel work: integration + removability + age.-/// Held under the check-lock read guard at the call site so it never overlaps-/// a write-side removal (see [`removal_needs_write`]).#[allow(clippy::too_many_arguments)]fn check_one(item: &CheckItem,@@ -1033,7 +1005,6 @@ pub fn step_prune(// Streaming dry-run path: scans run in parallel, results are collected and// sorted for deterministic output. No removals, no approval — just print.if dry_run {- let check_lock = RwLock::new(());let scan_span = Span::new("prune-scan");let dry_run_info: Vec<(Candidate, DryRunInfo)> = std::thread::scope(|s| {let (tx, rx) = chan::unbounded::<(usize, anyhow::Result<CheckOutcome>)>();@@ -1046,27 +1017,23 @@ pub fn step_prune(let check_items_ref = &check_items;let integration_target_ref = integration_target.as_str();let current_path_ref = current_root.as_path();- let check_lock_ref = &check_lock;let ref_write_times_ref = &ref_write_times;s.spawn(move || {check_items_ref.par_iter().enumerate().for_each(|(idx, item)| {- let outcome = {- let _read = check_lock_ref.read().unwrap_or_else(|e| e.into_inner());- check_one(- item,- repo_ref,- snapshot_ref,- integration_target_ref,- worktrees,- current_path_ref,- min_age_duration,- ref_write_times_ref,- now_secs,- )- };+ let outcome = check_one(+ item,+ repo_ref,+ snapshot_ref,+ integration_target_ref,+ worktrees,+ current_path_ref,+ min_age_duration,+ ref_write_times_ref,+ now_secs,+ );let _ = tx.send((idx, outcome));});});@@ -1193,12 +1160,12 @@ pub fn step_prune(.and_then(|p| std::fs::read(p).ok());let mut skipped_approval: Vec<SkippedApproval> = Vec::new();- let check_lock = RwLock::new(());+ let output_lock = RwLock::new(());let removal_ctx = RemovalContext {repo: &repo,foreground,hook_plan: &hook_plan,- check_lock: &check_lock,+ output_lock: &output_lock,};// Flipped by the first failing removal: the rest of the queue drains// without executing (matching the serial loop's abort-on-first-error),@@ -1208,7 +1175,7 @@ pub fn step_prune(// Streaming live path: scans run in parallel and the main thread queues a// job for each result as it arrives — a "Skipped ..." line or a removal.// Removals execute concurrently on the worker pool (read side of- // `check_lock`; the exceptional candidates take the write side — see+ // `output_lock`; the exceptional candidates take the write side — see// `removal_needs_write`). The current worktree is the one exception to// the fan-out: its removal cd's to the primary, so defer it until last.let scan_span = Span::new("prune-scan");@@ -1224,27 +1191,23 @@ pub fn step_prune(let check_items_ref = &check_items;let integration_target_ref = integration_target.as_str();let current_path_ref = current_root.as_path();- let check_lock_ref = &check_lock;let ref_write_times_ref = &ref_write_times;s.spawn(move || {check_items_ref.par_iter().enumerate().for_each(|(idx, item)| {- let outcome = {- let _read = check_lock_ref.read().unwrap_or_else(|e| e.into_inner());- check_one(- item,- repo_ref,- snapshot_ref,- integration_target_ref,- worktrees,- current_path_ref,- min_age_duration,- ref_write_times_ref,- now_secs,- )- };+ let outcome = check_one(+ item,+ repo_ref,+ snapshot_ref,+ integration_target_ref,+ worktrees,+ current_path_ref,+ min_age_duration,+ ref_write_times_ref,+ now_secs,+ );let _ = tx.send((idx, outcome));});});@@ -1286,10 +1249,9 @@ pub fn step_prune(RemovalJob::PrintSkip(line) => {// Hold the read side so a skip line can't// land inside a write-side removal's- // exclusive output window (spinner, hook- // stream).+ // exclusive output window (spinner).let _read = removal_ctx_ref- .check_lock+ .output_lock.read().unwrap_or_else(|e| e.into_inner());eprintln!("{line}");diff --git a/src/git/mod.rs b/src/git/mod.rsindex 55275ca00..f99960cd6 100644--- a/src/git/mod.rs+++ b/src/git/mod.rs@@ -11,6 +11,7 @@ mod parse;#[cfg(unix)]pub mod reap;pub mod recover;+mod ref_deletion;pub mod remote_ref;pub mod remove;mod repository;diff --git a/src/git/ref_deletion.rs b/src/git/ref_deletion.rsnew file mode 100644index 000000000..ffb134300--- /dev/null+++ b/src/git/ref_deletion.rs@@ -0,0 +1,179 @@+//! Repository-owned serialization of compare-and-swap branch deletion.+//!+//! Each call runs one `git update-ref -d <ref> <original-sha>`. Serialization+//! avoids Worktrunk's own contention on Git's packed-refs lock; the original+//! SHA comparison protects commits from concurrent writers. Integration and+//! checkout reads remain outside this coordinator.+//!+//! A failed deletion returns `false` only when a fresh exact ref read confirms+//! a different live SHA. Missing, unchanged or unreadable refs keep the original+//! Git error. Ordinary failures affect only their caller. An interruption in+//! either the mutation or its failure classification is latched before releasing+//! the mutex, so waiting and later calls cannot mutate after cancellation. The+//! repository's process-wide coordinator lives for one CLI invocation.++use std::sync::Mutex;++use super::{ErrorExt, Repository, WorktrunkError};++#[derive(Debug, Default)]+pub(super) struct RefDeletionCoordinator {+ interrupted: Mutex<Option<i32>>,+}++impl RefDeletionCoordinator {+ /// Delete iff the original SHA still matches; `false` means a moved live ref.+ pub(super) fn delete(+ &self,+ repo: &Repository,+ ref_name: &str,+ expected_sha: &str,+ ) -> anyhow::Result<bool> {+ tracing::debug!(ref_name, "Waiting for safe branch deletion");+ let mut interrupted = self+ .interrupted+ .lock()+ .map_err(|_| anyhow::anyhow!("Branch deletion coordinator stopped"))?;+ if let Some(signal) = *interrupted {+ return Err(WorktrunkError::Interrupted { signal, hint: None }.into());+ }++ let result = match repo.run_command(&["update-ref", "-d", ref_name, expected_sha]) {+ Ok(_) => Ok(true),+ Err(error) if error.interrupt_signal().is_some() => Err(error),+ Err(error) => {+ match repo.run_command(&["show-ref", "--verify", "--hash", "--", ref_name]) {+ Ok(live_sha) if live_sha.trim() != expected_sha => Ok(false),+ Err(read_error) if read_error.interrupt_signal().is_some() => Err(read_error),+ _ => Err(error),+ }+ }+ };+ if let Err(error) = &result+ && let Some(signal) = error.interrupt_signal()+ {+ *interrupted = Some(signal);+ return Err(WorktrunkError::Interrupted { signal, hint: None }.into());+ }+ result+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::testing::TestRepo;++ /// A packed ref with an advanced loose override must retain its new commit.+ #[test]+ fn original_sha_preserves_moved_and_missing_refs_and_deletes_unchanged_ref() {+ let test = TestRepo::with_initial_commit();+ for branch in ["moved", "missing", "unchanged"] {+ test.run_git(&["branch", branch]);+ }+ let original = test.git_output(&["rev-parse", "main"]);+ test.run_git(&["pack-refs", "--all"]);+ test.run_git(&["checkout", "moved"]);+ std::fs::write(test.root_path().join("new.txt"), "new work\n").unwrap();+ test.run_git(&["add", "new.txt"]);+ test.run_git(&["commit", "-m", "advance after snapshot"]);+ test.run_git(&["checkout", "main"]);+ let advanced = test.git_output(&["rev-parse", "moved"]);+ assert_ne!(original, advanced);+ test.run_git(&["tag", "refs/heads/missing", &advanced]);+ test.run_git(&["update-ref", "-d", "refs/heads/missing"]);+ let repo = Repository::at(test.root_path()).unwrap();+ let coordinator = repo.branch_deletions();+ assert!(+ !coordinator+ .delete(&repo, "refs/heads/moved", &original)+ .unwrap()+ );+ let missing_error = coordinator+ .delete(&repo, "refs/heads/missing", &original)+ .unwrap_err();+ assert!(super::super::CommandError::find_in(&missing_error).is_some());+ assert!(+ coordinator+ .delete(&repo, "refs/heads/unchanged", &original)+ .unwrap()+ );+ assert_eq!(test.git_output(&["rev-parse", "moved"]), advanced);+ assert_eq!(+ test.git_output(&["rev-parse", "refs/tags/refs/heads/missing"]),+ advanced+ );+ for branch in ["missing", "unchanged"] {+ assert!(+ repo.run_command(&[+ "show-ref",+ "--verify",+ "--hash",+ "--",+ &format!("refs/heads/{branch}")+ ])+ .is_err()+ );+ }+ }++ #[test]+ fn ref_lock_failures_keep_the_original_error_without_cancelling_other_calls() {+ for packed in [false, true] {+ let test = TestRepo::with_initial_commit();+ for branch in ["blocked", "independent"] {+ test.run_git(&["branch", branch]);+ }+ let lock_name = if packed {+ test.run_git(&["pack-refs", "--all"]);+ test.run_git(&["config", "core.packedRefsTimeout", "0"]);+ "packed-refs.lock"+ } else {+ test.run_git(&["config", "core.filesRefLockTimeout", "0"]);+ "refs/heads/blocked.lock"+ };+ let sha = test.git_output(&["rev-parse", "main"]);+ let repo = Repository::at(test.root_path()).unwrap();+ let lock_path = repo.git_common_dir().join(lock_name);+ std::fs::write(&lock_path, "").unwrap();+ let error = repo+ .branch_deletions()+ .delete(&repo, "refs/heads/blocked", &sha)+ .unwrap_err();+ assert!(error.display_message().contains(lock_name));+ assert!(super::super::CommandError::find_in(&error).is_some());+ assert_eq!(test.git_output(&["rev-parse", "blocked"]), sha);+ std::fs::remove_file(lock_path).unwrap();+ assert!(+ repo.branch_deletions()+ .delete(&repo, "refs/heads/independent", &sha)+ .unwrap()+ );+ assert!(+ repo.run_command(&["rev-parse", "--verify", "--quiet", "refs/heads/independent"])+ .is_err()+ );+ }+ }++ #[test]+ fn cancellation_prevents_later_calls_from_mutating_refs() {+ let test = TestRepo::with_initial_commit();+ test.run_git(&["branch", "candidate"]);+ let sha = test.git_output(&["rev-parse", "candidate"]);+ let repo = Repository::at(test.root_path()).unwrap();+ *repo.branch_deletions().interrupted.lock().unwrap() = Some(2);+ // A fresh repository shares the same command-lifetime cancellation.+ let fresh = Repository::at(test.root_path()).unwrap();+ for repo in [&repo, &fresh] {+ let error = repo+ .branch_deletions()+ .delete(repo, "refs/heads/candidate", &sha)+ .unwrap_err()+ .context("branch removal");+ assert_eq!(error.interrupt_signal(), Some(2));+ assert_eq!(error.exit_code(), Some(130));+ }+ assert_eq!(test.git_output(&["rev-parse", "candidate"]), sha);+ }+}diff --git a/src/git/remove.rs b/src/git/remove.rsindex fee6cff23..bcac99300 100644--- a/src/git/remove.rs+++ b/src/git/remove.rs@@ -261,7 +261,7 @@ pub enum BranchDeletionOutcome {/// Branch was not deleted — it was not integrated, and deletion was not forced.NotDeleted,/// Branch was integrated, but a fresh topology read found it checked out in- /// a worktree immediately before deletion. The ref is retained so that+ /// a worktree before the deletion attempt. The ref is retained so that/// worktree's HEAD remains resolvable.RetainedCheckedOut { path: PathBuf },/// Branch was integrated but the atomic compare-and-swap deletion was@@ -530,8 +530,9 @@ fn rename_into_trash(repo: &Repository, worktree_path: &Path) -> Option<PathBuf>/// [`remove_worktree_with_cleanup`], and the detached fallback can't call/// Rust, so it gets the guarantee from a fresh porcelain topology read followed/// by an `update-ref -d <ref> <sha>` shell tail instead. A hook or concurrent-/// process that checked out or advanced the branch since planning retains it,-/// rather than orphaning a worktree or losing a commit.+/// process that advanced the branch after the integration check cannot lose+/// that commit: the CAS rejects the deletion. Checkout protection is best+/// effort, retaining any checkout observed by the fresh topology read.pub fn execute_branch_deletion(repo: &Repository,branch_name: &str,@@ -574,46 +575,21 @@ pub fn delete_branch_if_safe(let outcome = match reason {Some(r) => {- // `update-ref` deliberately bypasses `git branch`'s checked-out- // branch protection, so sample topology from a brand-new- // Repository immediately before the ref mutation. Never consult- // `repo.list_worktrees()` here: callers often used that planning- // cache before a pre-remove hook or another process had a chance to- // add a checkout.- //- // Git exposes no transaction spanning worktree registration and ref- // updates. Keeping this fresh read directly adjacent to the CAS- // minimizes that unavoidable TOCTOU window; either command failing- // leaves the branch intact.- if let Some(path) = fresh_branch_checkout(repo, branch_name)? {- return Ok(BranchDeletionResult {- outcome: BranchDeletionOutcome::RetainedCheckedOut { path },- integration_target: effective_target,- });- }-// Atomic compare-and-swap against the snapshotted SHA. If the ref// moved between `integration_reason` and the delete (e.g. a hook- // advanced the branch), `git update-ref -d <ref> <expected>` fails+ // advanced the branch), the `git update-ref` mutation fails// closed: the branch is retained and we surface a `RetainedRaced`// outcome rather than dropping the unmerged commits silently.//// Read the SHA from the snapshot inventory (`local_branch`) rather// than `resolve()`, so it reflects the same `refs/heads/` walk// `integration_reason` consulted.- match snapshot.local_branch(branch_name) {- Some(b) => cas_delete_branch_outcome(repo, branch_name, &b.commit_sha, r)?,- // Snapshot doesn't carry the branch SHA — extremely unusual- // (the caller just captured refs, the branch is present in the- // integration check). Fall through to a non-CAS delete rather- // than failing the whole operation: this preserves the- // pre-CAS behavior in a corner case rather than introducing a- // new error class.- None => {- repo.run_command(&["branch", "-D", "--", branch_name])?;- BranchDeletionOutcome::Integrated(r)- }- }+ let Some(branch) = snapshot.local_branch(branch_name) else {+ anyhow::bail!(+ "Cannot safely delete branch {branch_name}: absent from ref snapshot"+ );+ };+ cas_delete_branch_outcome(repo, branch_name, &branch.commit_sha, r)?}None => BranchDeletionOutcome::NotDeleted,};@@ -657,24 +633,19 @@ fn branch_checkout_requires_retention(worktree: &WorktreeInfo, branch_name: &str/// Atomically delete `refs/heads/<branch>` iff it currently points at/// `expected_sha`, and translate the result into a [`BranchDeletionOutcome`].///-/// `git update-ref -d <ref> <oid>` is git's compare-and-swap delete primitive:-/// the ref is removed only if its current value matches `<oid>`. If it has-/// moved (a hook or concurrent process advanced the branch), the command-/// exits non-zero with a `cannot lock ref` message and the ref is left alone —-/// fail-closed semantics that protect unmerged commits.+/// `git update-ref -d <ref> <original-sha>` removes the ref only if its current+/// value still matches. The repository coordinator serializes these mutations+/// to avoid contention on Git's packed-refs lock.///-/// When `update-ref` fails, distinguishes "ref moved" (the ref still exists-/// → `RetainedRaced`) from "real error" (the ref is gone or git itself-/// failed → propagate the original error) by re-checking with `rev-parse-/// --verify --quiet`, which has a structured exit code (0 = present, 1 =-/// absent) rather than relying on locale-sensitive error-message text.+/// A fresh topology read provides best-effort checkout protection before+/// acquiring the deletion mutex. Topology reads can run concurrently. Git has+/// no transaction spanning checkout state and a ref update: a checkout can+/// appear after this check, including during the mutex wait. The atomic SHA+/// comparison still protects concurrent commits.///-/// A `packed-refs.lock` that stays contended past git's ~1 s retry budget-/// (concurrent deletes of packed branches — `wt step prune`'s parallel-/// removals — on slow ref-store I/O) also fails the CAS with the ref-/// present, and reads as `RetainedRaced` even though the tip never moved.-/// Accepted: it is fail-closed, empirically unobserved at 24-way concurrency-/// on local disks, and the next prune collects the branch.+/// On failure, a fresh exact ref read distinguishes actual SHA movement from+/// a lock or I/O error without parsing Git's localized diagnostics. A missing,+/// unchanged or unreadable ref propagates the original deletion error.fn cas_delete_branch_outcome(repo: &Repository,branch_name: &str,@@ -682,22 +653,18 @@ fn cas_delete_branch_outcome(reason: IntegrationReason,) -> anyhow::Result<BranchDeletionOutcome> {let ref_name = format!("refs/heads/{branch_name}");- let update_err = match repo.run_command(&["update-ref", "-d", &ref_name, expected_sha]) {- Ok(_) => return Ok(BranchDeletionOutcome::Integrated(reason)),- Err(e) => e,- };-- // CAS failed. Re-check the ref to distinguish a race rejection (ref- // moved → still present) from a true error (refs DB I/O, permissions,- // git missing → propagate). `rev-parse --verify --quiet` returns exit- // 0 when the ref exists, exit 1 when it does not — no message parsing.+ // update-ref bypasses Git's checked-out-branch protection. Sample topology+ // from a fresh Repository cache, independent of the planning-time cache.+ if let Some(path) = fresh_branch_checkout(repo, branch_name)? {+ return Ok(BranchDeletionOutcome::RetainedCheckedOut { path });+ }if repo- .run_command(&["rev-parse", "--verify", "--quiet", &ref_name])- .is_ok()+ .branch_deletions()+ .delete(repo, &ref_name, expected_sha)?{- Ok(BranchDeletionOutcome::RetainedRaced)+ Ok(BranchDeletionOutcome::Integrated(reason))} else {- Err(update_err)+ Ok(BranchDeletionOutcome::RetainedRaced)}}@@ -722,6 +689,7 @@ pub(crate) fn generate_removing_path(trash_dir: &Path, worktree_path: &Path) ->#[cfg(test)]mod tests {use super::*;+ use crate::git::ErrorExt;use crate::testing::TestRepo;/// A `git worktree lock` must stop the rename even when the caller skipped@@ -869,6 +837,26 @@ mod tests {assert!(!exit.success(), "branch should have been deleted");}+ /// A packed-ref lock failure must preserve the branch and the original+ /// Git error; an unchanged ref is not evidence of branch movement.+ #[test]+ fn cas_propagates_error_when_packed_refs_locked() {+ let test = TestRepo::with_initial_commit();+ test.run_git(&["branch", "feature"]);+ test.run_git(&["pack-refs", "--all"]);+ test.run_git(&["config", "core.packedRefsTimeout", "0"]);+ let repo = Repository::at(test.root_path()).unwrap();+ let snapshot = repo.capture_refs().unwrap();+ let expected_sha = &snapshot.local_branch("feature").unwrap().commit_sha;+ std::fs::write(repo.git_common_dir().join("packed-refs.lock"), "").unwrap();++ let result = delete_branch_if_safe(&repo, &snapshot, "feature", "main", false);+ let error = result.err().expect("lock failure must propagate");+ let message = error.display_message();+ assert!(message.contains("packed-refs.lock"), "{message}");+ assert_eq!(test.git_output(&["rev-parse", "feature"]), *expected_sha);+ }+/// A branch whose name starts with `-` must still force-delete: the/// `git branch -D -- <name>` separator stops git from parsing `-x` as an/// option. Created via `update-ref` since `git branch` rejects leading-dash@@ -939,7 +927,7 @@ mod tests {}/// When the branch ref vanishes between snapshot capture and the CAS- /// delete, `git update-ref -d` fails *and* the ref is already absent, so+ /// delete, `git update-ref` fails *and* the ref is already absent, so/// the outcome is a real error (propagated) — distinct from the/// `RetainedRaced` case where the ref moved but still exists.#[test]@@ -961,18 +949,16 @@ mod tests {);}- /// When the branch is integrated but absent from the captured snapshot- /// (created after capture), `integration_reason` still resolves it via the- /// live `rev-parse` fallback, yet the snapshot carries no SHA to CAS- /// against. The delete falls back to a plain `branch -D` and reports- /// `Integrated` — the non-CAS arm that exists for exactly this skew.+ /// A branch created after the snapshot has no checked SHA. Even if a live+ /// resolution finds it integrated, safe deletion must not force-delete it+ /// without a compare-and-swap protecting a subsequent commit.#[test]- fn deletes_via_fallback_when_branch_absent_from_snapshot() {+ fn retains_branch_when_snapshot_lacks_expected_sha() {let test = TestRepo::with_initial_commit();let repo = Repository::at(test.root_path()).unwrap();// Capture refs BEFORE `feature` exists, so the snapshot carries no SHA- // for it (forcing the snapshot-miss, non-CAS arm).+ // for it.let snapshot = repo.capture_refs().unwrap();assert!(snapshot.local_branch("feature").is_none(),@@ -983,21 +969,20 @@ mod tests {// commit), resolvable live but missing from the stale snapshot.test.run_git(&["branch", "feature"]);- let result = delete_branch_if_safe(&repo, &snapshot, "feature", "main", false).unwrap();+ let (_, reason) = repo+ .integration_reason(&snapshot, "feature", "main")+ .unwrap();+ assert!(reason.is_some(), "the live branch must appear integrated");+ let result = delete_branch_if_safe(&repo, &snapshot, "feature", "main", false);+ let error = result.err().expect("missing checked SHA must fail closed");assert!(- matches!(result.outcome, BranchDeletionOutcome::Integrated(_)),- "expected Integrated via the non-CAS fallback"+ error.to_string().contains("absent from ref snapshot"),+ "unexpected error: {error}"+ );+ assert_eq!(+ test.git_output(&["rev-parse", "feature"]),+ test.git_output(&["rev-parse", "main"]));-- // Branch was deleted.- let mut rev_parse = std::process::Command::new("git");- crate::testing::configure_git_cmd(&mut rev_parse);- let exit = rev_parse- .args(["rev-parse", "--verify", "--quiet", "refs/heads/feature"])- .current_dir(test.root_path())- .status()- .unwrap();- assert!(!exit.success(), "branch should have been deleted");}#[test]diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex 790e0d34f..137bbc140 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -120,9 +120,10 @@//! `LLM_SEMAPHORE` (summary), `COPY_POOL` (copy)//! - Global state: `OUTPUT_STATE` (output), `TRACE` and `SUBPROCESS` (log_files), `COMMAND_LOG`//! - Config: `CONFIG_PATH` (config/user/path), `SHELL_CONFIG`, `GIT_ENV_OVERRIDES` (shell_exec)-//! - Serialization: `WORKTREE_REGISTRY_LOCKS` (this module) — one `RwLock` per-//! canonical git common dir, handed to each `Repository` at construction so-//! `list_worktrees` reads and `git worktree remove` teardowns can't overlap.+//! - Serialization: `REPOSITORY_LOCKS` (this module) — one lock set per canonical+//! git common dir, handed to each `Repository` at construction. Its registry+//! lock prevents `list_worktrees` reads and `git worktree remove` teardowns+//! from overlapping; its deletion coordinator serializes safe ref mutations.//! Keyed like a cache but holding no git data, so nothing in it goes stale;//! see the static's own doc comment for the ordering rules.//!@@ -505,23 +506,32 @@ static DEFAULT_BASE_PATH: LazyLock<PathBuf> = LazyLock::new(|| PathBuf::from("."/// equality on the raw path is sufficient.static GIT_COMMON_DIR_CACHE: LazyLock<DashMap<PathBuf, PathBuf>> = LazyLock::new(DashMap::new);-/// Process-local coordination for Git's worktree registry, keyed by the-/// canonical Git common directory. Every [`Repository`] for the same common-/// directory shares one read/write lock. The dedicated-/// [`Repository::list_worktrees`] accessor takes the read side, while+/// Process-local coordination for repository mutations, keyed by the canonical+/// Git common directory. Every [`Repository`] for the same common directory+/// shares these locks. The registry lock's dedicated+/// [`Repository::list_worktrees`] accessor takes its read side, while/// [`Repository::prune_worktree_entry`] and [`Repository::remove_worktree`]-/// take the write side.+/// take its write side. The branch deletion coordinator serializes safe ref+/// mutations, which contend on Git's packed-refs lock even for different branches.+/// Its interruption state lasts for this process's CLI invocation.///-/// Guards are non-reentrant: a guarded operation must not call another of-/// these accessors. In `wt step prune`, the lock order is the command's-/// `check_lock` followed by this registry lock; code holding a registry guard-/// must never acquire `check_lock`.+/// Registry guards are non-reentrant: a guarded operation must not call another+/// registry accessor. In `wt step prune`, the command's `output_lock` precedes+/// either repository lock; code holding a repository guard must never acquire+/// `output_lock`. Safe branch deletion releases the registry read guard before+/// acquiring the deletion mutex; registry guards never span deletion waits.////// External Git processes and raw worktree commands issued through-/// [`Repository::run_command`] do not honor this lock.-static WORKTREE_REGISTRY_LOCKS: LazyLock<DashMap<PathBuf, Arc<RwLock<()>>>> =+/// [`Repository::run_command`] do not honor these locks.+static REPOSITORY_LOCKS: LazyLock<DashMap<PathBuf, Arc<RepositoryLocks>>> =LazyLock::new(DashMap::new);+#[derive(Debug, Default)]+struct RepositoryLocks {+ worktree_registry: RwLock<()>,+ branch_deletion: super::ref_deletion::RefDeletionCoordinator,+}+/// Process-wide map of `worktree_path -> canonicalized worktree root`,/// keyed by the canonicalized path used as the cache key (same convention as/// [`Repository::worktree_at`] / [`WorkingTree`]).@@ -771,7 +781,7 @@ pub struct Repository {/// Cached data for this repository. Shared across clones via Arc.pub(super) cache: Arc<RepoCache>,/// Shared by every `Repository` that resolves to `git_common_dir`.- worktree_registry_lock: Arc<RwLock<()>>,+ locks: Arc<RepositoryLocks>,/// When set, object-writing git plumbing is redirected into a temporary/// object database. `None` for the normal persistent path. See/// [`Repository::redirect_objects_for_observation`].@@ -829,9 +839,9 @@ impl Repository {pub fn at(path: impl Into<PathBuf>) -> anyhow::Result<Self> {let discovery_path = path.into();let git_common_dir = Self::resolve_git_common_dir(&discovery_path)?;- let worktree_registry_lock = WORKTREE_REGISTRY_LOCKS+ let locks = REPOSITORY_LOCKS.entry(git_common_dir.clone())- .or_insert_with(|| Arc::new(RwLock::new(())))+ .or_insert_with(|| Arc::new(RepositoryLocks::default())).clone();let cache = RepoCache::default();@@ -860,25 +870,32 @@ impl Repository {discovery_path,git_common_dir,cache: Arc::new(cache),- worktree_registry_lock,+ locks,temporary_object_store: None,})}/// Share registry coordination across fresh repository caches.pub(super) fn worktree_registry_read(&self) -> RwLockReadGuard<'_, ()> {- self.worktree_registry_lock+ self.locks+ .worktree_registry.read().unwrap_or_else(|error| error.into_inner())}/// Exclude registry readers and other teardowns for this repository.pub(super) fn worktree_registry_write(&self) -> RwLockWriteGuard<'_, ()> {- self.worktree_registry_lock+ self.locks+ .worktree_registry.write().unwrap_or_else(|error| error.into_inner())}+ /// Serialize safe ref mutations without blocking registry readers.+ pub(super) fn branch_deletions(&self) -> &super::ref_deletion::RefDeletionCoordinator {+ &self.locks.branch_deletion+ }+/// Return a clone whose object-writing git plumbing is redirected into a/// temporary object database.///@@ -2008,7 +2025,6 @@ impl Repository {if let Some(timeout) = timeout {cmd = cmd.timeout(timeout);}-let output = cmd.run().with_context(|| format!("Failed to execute: git {}", args.join(" ")))?;diff --git a/src/git/repository/tests.rs b/src/git/repository/tests.rsindex e91f2ffe7..84e7aa00c 100644--- a/src/git/repository/tests.rs+++ b/src/git/repository/tests.rs@@ -496,7 +496,7 @@ fn repo_path_error_when_is_bare_fails() {discovery_path: PathBuf::from("/nonexistent/repo"),git_common_dir: PathBuf::from("/nonexistent/.git"),cache: Arc::new(RepoCache::default()),- worktree_registry_lock: Arc::new(std::sync::RwLock::new(())),+ locks: Arc::new(super::RepositoryLocks::default()),temporary_object_store: None,};@@ -540,7 +540,7 @@ fn repo_path_ignores_non_local_core_worktree() {discovery_path: tmp.path().to_path_buf(),git_common_dir: git_dir.clone(),cache: Arc::new(cache),- worktree_registry_lock: Arc::new(std::sync::RwLock::new(())),+ locks: Arc::new(super::RepositoryLocks::default()),temporary_object_store: None,};@@ -764,7 +764,7 @@ fn is_builtin_fsmonitor_enabled_variants() {discovery_path: PathBuf::from("/nonexistent/repo"),git_common_dir: PathBuf::from("/nonexistent/.git"),cache: Arc::new(cache),- worktree_registry_lock: Arc::new(std::sync::RwLock::new(())),+ locks: Arc::new(super::RepositoryLocks::default()),temporary_object_store: None,}}@@ -1573,7 +1573,7 @@ fn prewarm_after_early_repository_still_preloads_config() {}#[test]-fn repository_instances_share_worktree_registry_coordination() {+fn repository_instances_share_mutation_coordination() {use crate::git::Repository;use crate::testing::TestRepo;@@ -1581,11 +1581,30 @@ fn repository_instances_share_worktree_registry_coordination() {let linked = test.add_worktree("registry-lock-linked");let first = Repository::at(test.root_path()).unwrap();let second = Repository::at(linked).unwrap();-- let _write = first.worktree_registry_write();+ test.run_git(&["branch", "safe-deletion"]);+ let expected = test.git_output(&["rev-parse", "safe-deletion"]);+ assert!(std::ptr::eq(+ first.branch_deletions(),+ second.branch_deletions()+ ));++ {+ let _write = first.worktree_registry_write();+ assert!(+ second.locks.worktree_registry.try_read().is_err(),+ "fresh repository handles for one common directory must share the registry lock"+ );+ assert!(+ second+ .branch_deletions()+ .delete(&second, "refs/heads/safe-deletion", &expected)+ .unwrap(),+ "registry coordination must not block ref mutation"+ );+ }assert!(- second.worktree_registry_lock.try_read().is_err(),- "fresh repository handles for one common directory must share the registry lock"+ second.locks.worktree_registry.try_read().is_ok(),+ "registry remains readable after branch deletion");}diff --git a/src/output/handlers.rs b/src/output/handlers.rsindex 93a8904ab..997acff0e 100644--- a/src/output/handlers.rs+++ b/src/output/handlers.rs@@ -14,7 +14,8 @@ use crate::commands::command_executor::FailureStrategy;use crate::commands::hook_plan::{ApprovedHookPlan, execute_planned_hook, register_planned};use crate::commands::hooks::HookAnnouncer;use crate::commands::process::{- HookLog, InternalOp, build_remove_command, build_remove_command_staged, spawn_detached,+ HookLog, InternalOp, build_remove_command, build_remove_command_staged,+ build_remove_placeholder_command, spawn_detached,};use crate::commands::template_vars::TemplateVars;use crate::commands::worktree::hooks::PostRemoveContext;@@ -129,10 +130,19 @@ pub enum RemovalExecution {}enum BackgroundRemovalPlan {- Detached(String),+ /// The worktree has been removed and trash cleanup scheduling was attempted.+ Staged(anyhow::Result<()>),+ /// The detached command still has to remove the worktree.+ Deferred(String),CompletedSynchronously,}+/// Cleanup still runs when branch deletion fails after staging the worktree.+struct BackgroundRemovalOutcome {+ plan: BackgroundRemovalPlan,+ branch_fate: anyhow::Result<BranchFate>,+}+/// Print `live` when a complete porcelain record names the requested branch/// and is either non-prunable or locked.///@@ -162,28 +172,41 @@ const LIVE_BRANCH_WORKTREE_AWK: &str = r#"BEGIN { RS = ""; FS = "\n" }////// Shared sequence for both detached HEAD and branch background removal paths./// The caller is responsible for output messages before this call, and hooks-/// after. Returns the branch's fate — known synchronously on every path except-/// the detached fallback, whose CAS tail runs after this process exits.+/// after. An outer error means removal was neither completed nor scheduled;+/// the inner result reports branch deletion or cleanup scheduling after removal,+/// so callers register teardown before propagating it. The fate is known synchronously+/// except on the detached fallback, whose CAS tail runs after this process exits.fn spawn_background_removal(repo: &Repository,main_path: &Path,removal: &BackgroundRemoval<'_>,log_label: &str,fallback_mode: BackgroundFallbackMode,-) -> anyhow::Result<BranchFate> {- let (remove_plan, fate) = execute_instant_removal_or_fallback(repo, removal, fallback_mode)?;-- if let BackgroundRemovalPlan::Detached(remove_command) = remove_plan {+) -> anyhow::Result<anyhow::Result<BranchFate>> {+ let spawn = |remove_command: &str, operation: InternalOp| {spawn_detached(repo,main_path,- &remove_command,+ remove_command,log_label,- &HookLog::Internal(InternalOp::Remove),+ &HookLog::Internal(operation),None,- )?;+ )+ .map(|_| ())+ };+ let outcome = execute_instant_removal_or_fallback(repo, removal, fallback_mode, spawn)?;+ match outcome.plan {+ BackgroundRemovalPlan::Staged(cleanup) => {+ // Cleanup was scheduled before branch deletion could wait. Preserve+ // the deletion error (including its interrupt signal) if both fail.+ Ok(outcome.branch_fate.and_then(|fate| cleanup.map(|_| fate)))+ }+ BackgroundRemovalPlan::Deferred(command) => {+ spawn(&command, InternalOp::Remove)?;+ Ok(outcome.branch_fate)+ }+ BackgroundRemovalPlan::CompletedSynchronously => Ok(outcome.branch_fate),}- Ok(fate)}/// Execute instant worktree removal via rename-then-prune.@@ -196,12 +219,14 @@ fn spawn_background_removal(/// runs that fallback synchronously for non-current worktrees when the caller needs the/// removal complete before it reports success (`wt step prune`).///-/// The caller is responsible for spawning detached plans in the background.+/// Stage cleanup is scheduled before synchronous branch deletion can wait;+/// the caller spawns only deferred removal plans after command preparation.fn execute_instant_removal_or_fallback(repo: &Repository,removal: &BackgroundRemoval<'_>,fallback_mode: BackgroundFallbackMode,-) -> anyhow::Result<(BackgroundRemovalPlan, BranchFate)> {+ spawn_cleanup: impl Fn(&str, InternalOp) -> anyhow::Result<()>,+) -> anyhow::Result<BackgroundRemovalOutcome> {let BackgroundRemoval {worktree_path,branch_name,@@ -219,6 +244,16 @@ fn execute_instant_removal_or_fallback(if let Some(staged_path) =stage_worktree_removal(repo, worktree_path, branch_name, force_worktree)?{+ if changed_directory {+ // Keep the shell's PWD valid until its cd directive is consumed.+ let _ = std::fs::create_dir(worktree_path);+ }+ // Trash cleanup is independent of branch deletion. Start it before a+ // deletion lock wait, and still attempt deletion if scheduling fails.+ let cleanup = spawn_cleanup(+ &build_remove_command_staged(&staged_path),+ InternalOp::Remove,+ );// Delete branch synchronously now that prune has removed the worktree metadata.// Fresh refs, not the pre-hook planning decision: hooks or concurrent// processes may have advanced the branch (`execute_branch_deletion`).@@ -232,27 +267,24 @@ fn execute_instant_removal_or_fallback(deletion_mode.is_force(),);warn_if_branch_retained(branch, &result, planner_expected_retention);- BranchFate::from_result(Some(&result))+ result.map(|result| BranchFate::from_outcome(&result.outcome))} else {- BranchFate::NotAttempted+ Ok(BranchFate::NotAttempted)};- if changed_directory {- // Create an empty placeholder at the original path so the shell's working- // directory ($env.PWD) remains valid until the wrapper has cd'd away.- // Without this, shells that validate PWD (notably Nushell) emit errors- // between binary exit and the cd directive executing.- // Best-effort: if create_dir fails (permissions, race), the only effect- // is that Nushell may still emit PWD errors — not a correctness issue.- let _ = std::fs::create_dir(worktree_path);- }- Ok((- BackgroundRemovalPlan::Detached(build_remove_command_staged(- &staged_path,- worktree_path,- changed_directory,- )),- fate,- ))+ // The placeholder protects the shell's PWD until exit. Its delay must+ // start after any synchronous branch wait, unlike independent trash.+ let placeholder_cleanup = if changed_directory {+ spawn_cleanup(+ &build_remove_placeholder_command(worktree_path),+ InternalOp::RemovePlaceholder,+ )+ } else {+ Ok(())+ };+ Ok(BackgroundRemovalOutcome {+ plan: BackgroundRemovalPlan::Staged(cleanup.and(placeholder_cleanup)),+ branch_fate: fate,+ })} else {if matches!(fallback_mode,@@ -271,9 +303,12 @@ fn execute_instant_removal_or_fallback(planner_expected_retention,)} else {- BranchFate::NotAttempted+ Ok(BranchFate::NotAttempted)};- return Ok((BackgroundRemovalPlan::CompletedSynchronously, fate));+ return Ok(BackgroundRemovalOutcome {+ plan: BackgroundRemovalPlan::CompletedSynchronously,+ branch_fate: fate,+ });}// Fallback: cross-filesystem, permissions, Windows file locking, etc.@@ -339,7 +374,10 @@ fn execute_instant_removal_or_fallback(BranchFate::NotAttempted,),};- Ok((BackgroundRemovalPlan::Detached(command), fate))+ Ok(BackgroundRemovalOutcome {+ plan: BackgroundRemovalPlan::Deferred(command),+ branch_fate: Ok(fate),+ })}}@@ -357,7 +395,7 @@ fn delete_branch_in_synchronous_fallback(target_branch: Option<&str>,deletion_mode: BranchDeletionMode,planner_expected_retention: bool,-) -> BranchFate {+) -> anyhow::Result<BranchFate> {let result = execute_branch_deletion(repo,branch,@@ -365,7 +403,7 @@ fn delete_branch_in_synchronous_fallback(deletion_mode.is_force(),);warn_if_branch_retained(branch, &result, planner_expected_retention);- BranchFate::from_result(Some(&result))+ result.map(|result| BranchFate::from_outcome(&result.outcome))}/// Surface the residual branch when `delete_branch_if_safe` returned an@@ -389,46 +427,43 @@ fn delete_branch_in_synchronous_fallback(/// similar race) — otherwise `print_hints` has explained the case and a/// second message would duplicate./// - `Ok(ForceDeleted)` / `Ok(Integrated(_))`: succeeded; no message.-/// - `Err`: `tracing::warn!` for developer diagnostics; the failure modes-/// here (`git update-ref` exec error, refs DB I/O failure) are not-/// user-actionable beyond re-running the command.+/// - `Err`: no warning; the caller propagates the Git error after arranging+/// trash cleanup, so a failed deletion never becomes a successful prune.fn warn_if_branch_retained(branch: &str,result: &anyhow::Result<BranchDeletionResult>,planner_expected_retention: bool,) {- match result {- Ok(result) => match &result.outcome {- BranchDeletionOutcome::RetainedCheckedOut { path } => {- eprintln!(- "{}",- retained_checked_out_branch_message(branch, path, true)- );- }- BranchDeletionOutcome::RetainedRaced => {- // The branch tip moved between the integration check and the- // atomic delete (a hook commit, a concurrent push). The- // compare-and-swap refused — fail-closed — so the unmerged- // commits are preserved. Always surface, regardless of planner- // prediction.- eprintln!("{}", retained_raced_branch_message(branch, true));- }- BranchDeletionOutcome::NotDeleted if !planner_expected_retention => {- let cmd = suggest_command("remove", &[branch], &["-D"]);- eprintln!(- "{}",- warning_message(cformat!(- "Removed worktree but kept branch <bold>{branch}</> (not integrated); to delete, run <bold>{cmd}</>"- ))- );- }- BranchDeletionOutcome::NotDeleted- | BranchDeletionOutcome::ForceDeleted- | BranchDeletionOutcome::Integrated(_) => {}- },- Err(e) => {- tracing::warn!(branch = %branch, error = %e, "Failed to delete branch {branch} after removing worktree: {e}");+ let Ok(result) = result else {+ return;+ };+ match &result.outcome {+ BranchDeletionOutcome::RetainedCheckedOut { path } => {+ eprintln!(+ "{}",+ retained_checked_out_branch_message(branch, path, true)+ );+ }+ BranchDeletionOutcome::RetainedRaced => {+ // The branch tip moved between the integration check and the+ // atomic delete (a hook commit, a concurrent push). The+ // compare-and-swap refused — fail-closed — so the unmerged+ // commits are preserved. Always surface, regardless of planner+ // prediction.+ eprintln!("{}", retained_raced_branch_message(branch, true));}+ BranchDeletionOutcome::NotDeleted if !planner_expected_retention => {+ let cmd = suggest_command("remove", &[branch], &["-D"]);+ eprintln!(+ "{}",+ warning_message(cformat!(+ "Removed worktree but kept branch <bold>{branch}</> (not integrated); to delete, run <bold>{cmd}</>"+ ))+ );+ }+ BranchDeletionOutcome::NotDeleted+ | BranchDeletionOutcome::ForceDeleted+ | BranchDeletionOutcome::Integrated(_) => {}}}@@ -1168,11 +1203,10 @@ pub fn execute_user_command(////// Returns the branch's [`BranchFate`] so callers report what happened rather/// than what the plan intended — the prune summary and `--format=json` both-/// read it. Worktree-removal failures propagate as `Err`, and for a-/// `Worktree` plan a surviving branch is a fate, not an error — the removal-/// was the primary operation. For a `BranchOnly` plan the deletion *is* the-/// operation, so a hard command failure (not a declined or raced deletion)-/// still propagates as `Err`.+/// read it. Worktree-removal failures and hard branch-deletion failures+/// propagate as `Err`; an intentionally retained, unmerged, or moved branch+/// is a fate. Silent worktree removal keeps its best-effort deletion contract,+/// reporting a hard branch failure as a retained fate to the picker.////// Approval is handled at the gate (command entry point), not here. The/// `announcer`'s `show_branch` setting (set by the caller) controls whether@@ -1858,7 +1892,7 @@ fn handle_detached_removed_worktree_output(ctx: &WorktreeRemovalContext<'_>,announcer: &mut HookAnnouncer<'_>,) -> anyhow::Result<BranchFate> {- if matches!(ctx.execution, RemovalExecution::Foreground) {+ let fate = if matches!(ctx.execution, RemovalExecution::Foreground) {eprintln!("{}",progress_message(cformat!(@@ -1898,6 +1932,7 @@ fn handle_detached_removed_worktree_output()).append(&stats_paren));+ Ok(BranchFate::NotAttempted)} else {let path_display = format_path_for_display(ctx.worktree_path);eprintln!(@@ -1923,14 +1958,14 @@ fn handle_detached_removed_worktree_output(},"detached",ctx.background_fallback(),- )?;- }+ )?+ };// A detached worktree was on no branch, so `{{ branch }}` stays unset for// the post-remove hooks (issue #4009).spawn_hooks_after_remove(repo, ctx, None, announcer)?;stderr().flush()?;- Ok(BranchFate::NotAttempted)+ fate}fn handle_named_removed_worktree_foreground(@@ -1968,6 +2003,10 @@ fn handle_named_removed_worktree_foreground(.map(cleanup_staged_with_progress).unwrap_or((0, 0));+ // Worktree removal happened even if the subsequent branch deletion failed.+ // Register teardown before display_info can propagate that failure.+ spawn_hooks_after_remove(repo, ctx, Some(branch_name), announcer)?;+// The observed fate, read before the display path consumes (and, on Err,// propagates) the deletion result.let fate = BranchFate::from_result(output.branch_result.as_ref());@@ -1987,7 +2026,6 @@ fn handle_named_removed_worktree_foreground(}print_switch_message_if_changed(ctx.changed_directory, ctx.main_path)?;- spawn_hooks_after_remove(repo, ctx, Some(branch_name), announcer)?;stderr().flush()?;Ok(fate)}@@ -2037,7 +2075,7 @@ fn handle_named_removed_worktree_background(spawn_hooks_after_remove(repo, ctx, Some(branch_name), announcer)?;stderr().flush()?;- Ok(fate)+ fate}/// Execute and narrate a [`RemovalPlan::Worktree`] plan.@@ -2049,7 +2087,12 @@ fn handle_removed_worktree_output(// and git operations after removal need a valid working directory.let repo = worktrunk::git::Repository::at(ctx.main_path)?;- execute_pre_remove_hooks_if_needed(&repo, &ctx)?;+ if ctx+ .hook_plan+ .has_hooks_for(ctx.worktree_path, &[worktrunk::HookType::PreRemove])+ {+ execute_pre_remove_hooks_if_needed(&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@@ -2307,7 +2350,7 @@ mod tests {false,);- // Err arm → tracing::warn! only, no stderr message+ // Err arm → caller propagates it after arranging trash cleanup.warn_if_branch_retained("feature",&Err(anyhow::anyhow!("simulated git failure")),diff --git a/tests/integration_tests/step_prune.rs b/tests/integration_tests/step_prune.rsindex ed0daceac..edd094963 100644--- a/tests/integration_tests/step_prune.rs+++ b/tests/integration_tests/step_prune.rs@@ -1711,9 +1711,8 @@ fn test_prune_summary_counts_declined_deletion_as_worktree_only(mut repo: TestRe/// and regression test for synchronous fallback completion.////// Prune's hook-free removals — the rename-failure fallback included — run-/// concurrently with the parallel `integration_reason` readers on the read-/// side of `check_lock` (`src/commands/step/prune.rs`). That is safe because-/// the chain's branch deletion is a CAS `git update-ref -d`, which never+/// concurrently with the parallel `integration_reason` readers. That is safe+/// because the chain's branch deletion is a CAS `git update-ref -d`, which never/// rewrites `.git/config`; a deletion mechanism that rewrites config via/// lockfile+rename (as `git branch -D` does — the original Windows race,/// #2801) would collide with those readers again. Each branch here gets a@@ -1731,7 +1730,7 @@ fn test_prune_summary_counts_declined_deletion_as_worktree_only(mut repo: TestRe/// returns) holds on every platform.////// 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*+/// update-ref -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@@ -1899,8 +1898,8 @@ fn test_prune_surfaces_failing_metadata_prune(mut repo: TestRepo) {/// A stale entry is unregistered before its branch is deleted, so it goes/// even when the branch deletion loses its compare-and-swap: prune reports the-/// pruned entry, then the kept branch. The shim fails the CAS delete and leaves-/// the ref, which is how a branch that moved during deletion reads.+/// pruned entry, then the kept branch. The shim advances the ref before+/// rejecting the CAS delete, reproducing an actual branch-tip race.#[cfg(unix)]#[rstest]fn test_prune_unregisters_stale_entry_when_branch_delete_races(mut repo: TestRepo) {@@ -1914,7 +1913,11 @@ fn test_prune_unregisters_stale_entry_when_branch_delete_races(mut repo: TestRepwrite_failing_branch_delete_wrapper(&git_wrapper_dir, &which::which("git").unwrap());prepend_path(&mut cmd, &git_wrapper_dir);cmd.env("WT_TEST_FAIL_DELETE_BRANCH", "stale-raced");- cmd.env("WT_TEST_FAIL_DELETE_KEEPS_REF", "1");+ let raced_sha = repo.git_output(&["commit-tree", "HEAD^{tree}", "-p", "HEAD", "-m", "raced"]);+ cmd.env(+ "WORKTRUNK_TEST_FAIL_DELETE_REPLACEMENT_SHA",+ raced_sha.trim(),+ );let output = cmd.args(["step", "prune", "--yes", "--min-age=0s"])@@ -1977,27 +1980,233 @@ fn test_prune_dry_run_leaves_stale_entry_registered(mut repo: TestRepo) {);}-/// Hook-free removals execute concurrently (the read side of `check_lock`),-/// not one at a time.+/// A lock held by another Git process is a deletion error, not evidence that+/// the branch moved. Both branch-only and staged-worktree deletion must report+/// the underlying failure while preserving the original branch tip.+#[rstest]+#[case::branch_only(false, false)]+#[case::worktree(true, false)]+#[case::foreground_worktree(true, true)]+fn test_prune_reports_external_packed_ref_lock(+ mut repo: TestRepo,+ #[case] worktree: bool,+ #[case] foreground: bool,+) {+ use path_slash::PathExt as _;++ repo.commit("initial");+ if worktree {+ repo.add_worktree("locked-delete");+ } else {+ repo.create_branch("locked-delete");+ }+ let expected_sha = repo.git_output(&["rev-parse", "locked-delete"]);+ repo.run_git(&["pack-refs", "--all", "--prune"]);+ repo.run_git(&["config", "core.packedRefsTimeout", "0"]);+ let common_dir = crate::common::resolve_git_common_dir(repo.root_path());+ assert!(+ std::fs::read_to_string(common_dir.join("packed-refs"))+ .unwrap()+ .contains("refs/heads/locked-delete")+ );+ assert!(!common_dir.join("refs/heads/locked-delete").exists());+ std::fs::write(common_dir.join("packed-refs.lock"), "external Git writer\n").unwrap();++ let post_remove_marker = repo.home_path().join("post-remove-ran");+ if worktree {+ repo.write_test_config(&format!(+ "post-remove = 'echo ran > {}'",+ post_remove_marker.to_slash_lossy()+ ));+ }+ let mut cmd = repo.wt_command();+ cmd.args(["step", "prune", "--yes", "--min-age=0s"]);+ if foreground {+ cmd.arg("--foreground");+ }+ let output = cmd.output().unwrap();+ let stderr = String::from_utf8_lossy(&output.stderr)+ .ansi_strip()+ .into_owned();+ assert!(+ !output.status.success(),+ "a real branch-deletion error must fail prune:\n{stderr}"+ );+ assert!(+ stderr.contains("packed-refs.lock") && !stderr.contains("moved during deletion"),+ "prune must report the Git error without inventing ref movement:\n{stderr}"+ );+ assert_eq!(+ repo.git_output(&["rev-parse", "locked-delete"]),+ expected_sha+ );+ assert!(common_dir.join("packed-refs.lock").exists());+ if worktree {+ assert!(!repo.worktree_path("locked-delete").exists());+ let trash_dir = common_dir.join("wt/trash");+ assert!(trash_dir.is_dir(), "the worktree must use trash staging");+ crate::common::wait_for(+ "staged worktree cleaned after branch deletion fails",+ || std::fs::read_dir(&trash_dir).unwrap().next().is_none(),+ );+ crate::common::wait_for("post-remove hook after branch deletion fails", || {+ post_remove_marker.exists()+ });+ }+}++/// Failure to schedule trash cleanup follows an already completed removal;+/// it must report the error while still launching the worktree's teardown.+#[rstest]+#[case::named(false, false)]+#[case::detached(true, false)]+#[cfg_attr(unix, case::interrupted_named(false, true))]+fn test_removal_runs_post_remove_after_cleanup_spawn_failure(+ mut repo: TestRepo,+ #[case] detached: bool,+ #[case] interrupt: bool,+) {+ use path_slash::PathExt as _;++ repo.commit("initial");+ let worktree = repo.add_worktree("cleanup-error");+ if detached {+ repo.run_git(&["-C", worktree.to_str().unwrap(), "checkout", "--detach"]);+ }+ let common_dir = crate::common::resolve_git_common_dir(repo.root_path());+ let label = if detached {+ "detached"+ } else {+ "cleanup-error"+ };+ let branch_log_dir = common_dir.join("wt/logs").join(label);+ std::fs::create_dir_all(&branch_log_dir).unwrap();+ // Block only the internal cleanup log, keeping the user's hook log writable.+ std::fs::write(branch_log_dir.join("internal"), "blocked").unwrap();+ let marker = repo.home_path().join("post-remove-ran");+ repo.write_test_config(&format!(+ "post-remove = 'echo ran > {}'",+ marker.to_slash_lossy()+ ));++ let mut cmd = repo.wt_command();+ if detached {+ cmd.arg("remove").arg(&worktree).arg("--yes");+ } else {+ cmd.args(["step", "prune", "--yes", "--min-age=0s"]);+ }+ #[cfg(unix)]+ if interrupt {+ let wrapper = repo.home_path().join("git-wrapper");+ std::fs::create_dir_all(&wrapper).unwrap();+ write_failing_branch_delete_wrapper(&wrapper, &which::which("git").unwrap());+ prepend_path(&mut cmd, &wrapper);+ cmd.env("WT_TEST_FAIL_DELETE_BRANCH", "cleanup-error");+ cmd.env("WORKTRUNK_TEST_FAIL_DELETE_INTERRUPT", "1");+ }+ let output = cmd.output().unwrap();+ let stderr = String::from_utf8_lossy(&output.stderr)+ .ansi_strip()+ .into_owned();+ assert!(!output.status.success(), "{stderr}");+ if interrupt {+ assert_eq!(output.status.code(), Some(130), "{stderr}");+ assert_eq!(+ repo.git_output(&["rev-parse", "cleanup-error"]),+ repo.git_output(&["rev-parse", "main"])+ );+ } else {+ assert!(+ stderr.contains("Failed to create log directory"),+ "{stderr}"+ );+ }+ assert!(!worktree.exists());+ assert!(+ common_dir+ .join("wt/trash")+ .read_dir()+ .unwrap()+ .next()+ .is_some()+ );+ crate::common::wait_for("post-remove hook after cleanup scheduling fails", || {+ marker.exists()+ });+}++/// A checkout created by a pre-remove hook must keep its branch, even after+/// the original worktree's registration has been removed.+#[rstest]+fn test_prune_retains_branch_checked_out_during_pre_remove(mut repo: TestRepo) {+ use path_slash::PathExt as _;++ repo.commit("initial");+ let original = repo.add_worktree("hook-checkout");+ let shared = repo.home_path().join("shared-checkout");+ repo.write_test_config(&format!(+ "pre-remove = 'git worktree add --force {} hook-checkout'",+ shared.to_slash_lossy()+ ));++ let output = repo+ .wt_command()+ .args(["step", "prune", "--yes", "--min-age=0s"])+ .output()+ .unwrap();+ let stderr = String::from_utf8_lossy(&output.stderr)+ .ansi_strip()+ .into_owned();+ assert!(output.status.success(), "{stderr}");+ assert!(!original.exists());+ assert!(shared.exists());+ assert!(+ stderr.contains("retained branch") && stderr.contains("checked out"),+ "{stderr}"+ );+ assert_eq!(+ repo.git_output(&["rev-parse", "hook-checkout"]),+ repo.git_output(&["rev-parse", "main"])+ );+}++/// Worktree staging stays concurrent, but packed branch mutations do not+/// contend on Git's shared packed-refs lock.///-/// Two integrated orphan branches are removed through a `git` shim whose-/// `update-ref -d` arms barrier on each other: each records that it started,-/// then waits for the *other* branch's deletion to start before proceeding.-/// The barrier only resolves if both removals are in flight at once — under-/// serialized removals the first deletion would wait out the shim's 15 s-/// timeout and drop a sentinel file, which the test asserts absent. Causally-/// driven, so it runs at barrier speed when concurrency works; the timeout is-/// only the safety net. Unix-only for the same `CreateProcess` shim reason as-/// the canary above.+/// The shim rendezvouses at the fsmonitor stop, before either worktree is+/// staged. At deletion it holds the real packed-refs lock through an absence+/// window: a concurrent deletion reaches real Git and fails its lock attempt.+/// A serialized whole removal cannot pass the staging barrier; parallel ref+/// mutation cannot pass the final ref and contention assertions.#[cfg(unix)]#[rstest]-fn test_prune_removals_run_concurrently(repo: TestRepo) {+#[case::without_hooks(false)]+#[case::post_remove_only(true)]+fn test_prune_stages_concurrently_without_packed_ref_contention(+ mut repo: TestRepo,+ #[case] post_remove: bool,+) {+ use path_slash::PathExt as _;repo.commit("initial");- // Orphan branches at main HEAD: same-commit integrated, no worktree, so- // each becomes a hook-free BranchOnly candidate on the parallel path.- repo.create_branch("para-a");- repo.create_branch("para-b");+ repo.add_worktree("para-a");+ repo.add_worktree("para-b");+ repo.run_git(&["pack-refs", "--all", "--prune"]);+ repo.run_git(&["config", "core.packedRefsTimeout", "0"]);+ let common_dir = crate::common::resolve_git_common_dir(repo.root_path());+ let packed_refs = std::fs::read_to_string(common_dir.join("packed-refs")).unwrap();+ for name in ["para-a", "para-b"] {+ assert!(packed_refs.contains(&format!("refs/heads/{name}")));+ assert!(!common_dir.join("refs/heads").join(name).exists());+ }++ let hook_marker = repo.home_path().join("post-hooks");+ if post_remove {+ repo.write_test_config(&format!(+ "post-remove = 'echo {{ branch }} >> {}'",+ hook_marker.to_slash_lossy()+ ));+ }let mut cmd = repo.wt_command();// The removal pool is sized from the rayon thread count; pin it to two so@@ -2011,6 +2220,16 @@ fn test_prune_removals_run_concurrently(repo: TestRepo) {let barrier_dir = repo.home_path().join("barrier");std::fs::create_dir_all(&barrier_dir).unwrap();cmd.env("WT_TEST_BARRIER_DIR", &barrier_dir);+ cmd.env(+ "WORKTRUNK_TEST_PACKED_REFS_LOCK",+ common_dir.join("packed-refs.lock"),+ );+ cmd.env(+ "WORKTRUNK_TEST_REF_LOCK_WINDOW",+ worktrunk::testing::SLEEP_FOR_ABSENCE_CHECK+ .as_secs_f64()+ .to_string(),+ );let output = cmd.args(["step", "prune", "--yes", "--min-age=0s"])@@ -2022,7 +2241,7 @@ fn test_prune_removals_run_concurrently(repo: TestRepo) {for name in ["para-a", "para-b"] {assert!(barrier_dir.join(format!("started-{name}")).exists(),- "the shim never fired for {name} — its CAS delete was not exercised"+ "the staging rendezvous never ran for {name}");}let timeouts: Vec<String> = std::fs::read_dir(&barrier_dir)@@ -2035,6 +2254,19 @@ fn test_prune_removals_run_concurrently(repo: TestRepo) {timeouts.is_empty(),"a deletion waited out the barrier — removals ran serially: {timeouts:?}");+ assert!(+ !barrier_dir.join("contended").exists(),+ "prune's branch deletions contended on packed-refs.lock:\n{stderr}"+ );+ let calls = prune_delete_calls(&git_wrapper_dir);+ for name in ["para-a", "para-b"] {+ assert!(+ calls+ .iter()+ .any(|call| call.lines().next() == Some(format!("refs/heads/{name}").as_str())),+ "the packed-ref lock shim must intercept the actual deletion of {name}"+ );+ }let branches = repo.git_output(&["branch", "--format=%(refname:short)"]);for name in ["para-a", "para-b"] {assert!(@@ -2042,6 +2274,386 @@ fn test_prune_removals_run_concurrently(repo: TestRepo) {"{name} should have been deleted; branches:\n{branches}");}+ if post_remove {+ crate::common::wait_for("both post-remove hooks", || {+ std::fs::read_to_string(&hook_marker)+ .is_ok_and(|contents| contents.lines().count() == 2)+ });+ }+}++/// Each hook waits for its peer to start: serial hook execution cannot finish+/// the rendezvous. Both worktrees must still complete their own hook before+/// removal, and branch deletion must retain its usual safe-delete behavior.+#[cfg(unix)]+#[rstest]+fn test_prune_pre_remove_hooks_run_concurrently(mut repo: TestRepo) {+ use path_slash::PathExt as _;++ repo.commit("initial");+ let worktrees: Vec<_> = ["parallel-a", "parallel-b"]+ .into_iter()+ .map(|name| (name, repo.add_worktree(name)))+ .collect();+ let barriers = repo.home_path().join("barriers");+ std::fs::create_dir_all(&barriers).unwrap();+ repo.write_test_config(&format!(+ r#"pre-remove = """+touch {0}/started-{{{{ branch }}}}+attempts=0+while [ ! -f {0}/started-parallel-a ] || [ ! -f {0}/started-parallel-b ]; do+ attempts=$((attempts + 1))+ if [ "$attempts" -ge 200 ]; then+ echo 'peer pre-remove hook never started' >&2+ exit 1+ fi+ sleep 0.05+done+[ -e .git ] || exit 1+touch {0}/completed-{{{{ branch }}}}+""""#,+ barriers.to_slash_lossy()+ ));+ let output = repo+ .wt_command()+ .env("RAYON_NUM_THREADS", "2")+ .args(["step", "prune", "--yes", "--min-age=0s"])+ .output()+ .unwrap();+ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(output.status.success(), "{stderr}");+ let branches = repo.git_output(&["branch", "--format=%(refname:short)"]);+ for (name, path) in worktrees {+ assert!(barriers.join(format!("completed-{name}")).exists());+ assert!(!path.exists());+ assert!(!branches.lines().any(|branch| branch == name));+ }+}++#[cfg(unix)]+#[derive(Clone, Copy, PartialEq)]+enum SerializedDeleteFailure {+ None,+ Moved,+ Locked,+ ClassificationError,+ MutationInterrupt,+ ClassificationInterrupt,+}++/// All worktrees stage and clean up while the first CAS is blocked. Waiting+/// deletions never overlap, and one candidate's ordinary failure does not+/// strand already-waiting peers. Interrupts stop every later Git mutation,+/// including when interruption happens while classifying the first failure.+#[cfg(unix)]+#[rstest]+#[case::deleted(SerializedDeleteFailure::None)]+#[case::moved(SerializedDeleteFailure::Moved)]+#[case::locked(SerializedDeleteFailure::Locked)]+#[case::classification_error(SerializedDeleteFailure::ClassificationError)]+#[case::mutation_interrupt(SerializedDeleteFailure::MutationInterrupt)]+#[case::classification_interrupt(SerializedDeleteFailure::ClassificationInterrupt)]+fn test_prune_serializes_safe_deletions(+ mut repo: TestRepo,+ #[case] failure: SerializedDeleteFailure,+) {+ use path_slash::PathExt as _;+ use std::io::{BufRead as _, BufReader};+ use std::process::Stdio;++ repo.commit("initial");+ let names: Vec<_> = (0..8).map(|i| format!("serialized-{i}")).collect();+ let worktrees: Vec<_> = names.iter().map(|name| repo.add_worktree(name)).collect();+ let original_sha = repo.git_output(&["rev-parse", "main"]);+ let advanced_sha =+ repo.git_output(&["commit-tree", "HEAD^{tree}", "-p", "HEAD", "-m", "advanced"]);+ assert_ne!(advanced_sha, original_sha);+ repo.run_git(&["pack-refs", "--all", "--prune"]);+ repo.run_git(&["config", "core.packedRefsTimeout", "0"]);+ let common = crate::common::resolve_git_common_dir(repo.root_path());+ let barriers = repo.home_path().join("barriers");+ std::fs::create_dir_all(&barriers).unwrap();+ let hooks = repo.home_path().join("post-hooks");+ repo.write_test_config(&format!(+ "post-remove = 'echo {{ branch }} >> {}'",+ hooks.to_slash_lossy()+ ));+ let wrapper = repo.home_path().join("git-wrapper");+ std::fs::create_dir_all(&wrapper).unwrap();+ let real_git = which::which("git").unwrap();+ let real = shell_escape::unix::escape(real_git.to_string_lossy());+ write_prune_git_wrapper(+ &wrapper,+ &real_git,+ &format!(+ r#"+if [ "$1 $2 $3 $4" = 'show-ref --verify --hash --' ] &&+ [ -f "$WORKTRUNK_TEST_CAS_BARRIERS/locked-ref" ] &&+ [ "$5" = "$(cat "$WORKTRUNK_TEST_CAS_BARRIERS/locked-ref")" ]; then+ case "$WORKTRUNK_TEST_CAS_FAILURE" in+ classification-error)+ touch "$WORKTRUNK_TEST_CAS_BARRIERS/classification-error"+ printf 'classification unavailable\n' >&2+ exit 128+ ;;+ classification-interrupt)+ touch "$WORKTRUNK_TEST_CAS_BARRIERS/classification-interrupt"+ kill -INT $$+ ;;+ esac+fi+if [ "$1 $2" = 'update-ref -d' ] &&+ mkdir "$WORKTRUNK_TEST_CAS_BARRIERS/first" 2>/dev/null; then+ printf '%s\n' "$3" > "$WORKTRUNK_TEST_CAS_BARRIERS/first-ref"+ i=0+ while [ ! -f "$WORKTRUNK_TEST_CAS_BARRIERS/release" ]; do+ i=$((i+1))+ if [ "$i" -gt 600 ]; then+ touch "$WORKTRUNK_TEST_CAS_BARRIERS/timeout"+ exit 2+ fi+ sleep 0.05+ done+ case "$WORKTRUNK_TEST_CAS_FAILURE" in+ moved)+ {real} update-ref "$3" "$WORKTRUNK_TEST_CAS_ADVANCE" || exit 2+ ;;+ locked|classification-error|classification-interrupt)+ printf '%s\n' "$3" > "$WORKTRUNK_TEST_CAS_BARRIERS/locked-ref"+ lock="$WORKTRUNK_TEST_CAS_COMMON/$3.lock"+ mkdir -p "${{lock%/*}}"+ printf 'external writer\n' > "$lock"+ ;;+ mutation-interrupt)+ touch "$WORKTRUNK_TEST_CAS_BARRIERS/mutation-interrupt"+ kill -INT $$+ ;;+ esac+fi+"#+ ),+ );+ let mode = match failure {+ SerializedDeleteFailure::None => "",+ SerializedDeleteFailure::Moved => "moved",+ SerializedDeleteFailure::Locked => "locked",+ SerializedDeleteFailure::ClassificationError => "classification-error",+ SerializedDeleteFailure::MutationInterrupt => "mutation-interrupt",+ SerializedDeleteFailure::ClassificationInterrupt => "classification-interrupt",+ };+ let interrupted = matches!(+ failure,+ SerializedDeleteFailure::MutationInterrupt+ | SerializedDeleteFailure::ClassificationInterrupt+ );+ let mut cmd = repo.wt_command();+ prepend_path(&mut cmd, &wrapper);+ let mut child = cmd+ .env("RAYON_NUM_THREADS", "8")+ .env("RUST_LOG", "worktrunk::git::ref_deletion=debug")+ .env("WORKTRUNK_TEST_CAS_BARRIERS", &barriers)+ .env("WORKTRUNK_TEST_CAS_COMMON", &common)+ .env("WORKTRUNK_TEST_CAS_FAILURE", mode)+ .env("WORKTRUNK_TEST_CAS_ADVANCE", advanced_sha.trim())+ .args(["step", "prune", "--yes", "--min-age=0s"])+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .spawn()+ .unwrap();+ let child_stderr = child.stderr.take().unwrap();+ let release = barriers.join("release");+ let cleanup_marker = barriers.join("cleanup-before-cas");+ let first_ref_marker = barriers.join("first-ref");+ let trash = common.join("wt/trash");+ let recorded_calls = wrapper.clone();+ let reader = std::thread::spawn(move || {+ let mut waiting = 0;+ let mut captured = Vec::new();+ for line in BufReader::new(child_stderr).split(b'\n') {+ let line = line.unwrap();+ let text = String::from_utf8_lossy(&line).ansi_strip().into_owned();+ if text.contains("Waiting for safe branch deletion") {+ waiting += 1;+ if waiting == 8 {+ assert!(worktrees.iter().all(|path| !path.exists()));+ crate::common::wait_for("first CAS blocked", || first_ref_marker.exists());+ crate::common::wait_for("trash cleanup while CAS is blocked", || {+ std::fs::read_dir(&trash).unwrap().next().is_none()+ });+ // All peers reached the coordinator; an unlocked deletion+ // could now start. Keep observing for the absence window.+ let started = std::time::Instant::now();+ while started.elapsed() < worktrunk::testing::SLEEP_FOR_ABSENCE_CHECK {+ assert_eq!(prune_delete_calls(&recorded_calls).len(), 1);+ std::thread::sleep(std::time::Duration::from_millis(10));+ }+ std::fs::write(&cleanup_marker, "cleaned").unwrap();+ std::fs::write(&release, "ready").unwrap();+ }+ }+ captured.extend(line);+ captured.push(b'\n');+ }+ captured+ });+ let output = child.wait_with_output().unwrap();+ let stderr_bytes = reader.join().unwrap();+ let stderr = String::from_utf8_lossy(&stderr_bytes)+ .ansi_strip()+ .into_owned();+ assert!(+ !barriers.join("timeout").exists(),+ "waiting deletions did not all arrive:\n{stderr}"+ );+ assert!(barriers.join("cleanup-before-cas").exists());+ assert_eq!(+ output.status.success(),+ matches!(+ failure,+ SerializedDeleteFailure::None | SerializedDeleteFailure::Moved+ ),+ "{stderr}"+ );+ let calls = prune_delete_calls(&wrapper);+ assert_eq!(calls.len(), if interrupted { 1 } else { 8 }, "{stderr}");+ let first_ref = std::fs::read_to_string(barriers.join("first-ref")).unwrap();+ let mut attempted = std::collections::HashSet::new();+ for call in calls {+ let mut args = call.lines();+ let reference = args.next().unwrap();+ assert!(+ attempted.insert(reference.to_owned()),+ "no blind CAS retries"+ );+ assert_eq!(args.next().unwrap(), original_sha.trim());+ assert!(args.next().is_none());+ }+ for name in &names {+ let reference = format!("refs/heads/{name}");+ let result = repo+ .git_command()+ .args(["rev-parse", "--verify", &reference])+ .run()+ .unwrap();+ let retained = interrupted+ || (failure != SerializedDeleteFailure::None && reference == first_ref.trim());+ assert_eq!(result.status.success(), retained, "{name}: {stderr}");+ if retained {+ assert_eq!(+ String::from_utf8_lossy(&result.stdout).trim(),+ if failure == SerializedDeleteFailure::Moved && reference == first_ref.trim() {+ advanced_sha.trim()+ } else {+ original_sha.trim()+ }+ );+ }+ }+ if interrupted {+ assert_eq!(output.status.code(), Some(130), "{stderr}");+ assert!(barriers.join(mode).exists());+ } else if failure == SerializedDeleteFailure::Moved {+ assert!(stderr.contains("moved during deletion"), "{stderr}");+ } else if failure != SerializedDeleteFailure::None {+ assert!(stderr.contains(".lock"), "{stderr}");+ assert!(!stderr.contains("moved during deletion"), "{stderr}");+ assert!(common.join(format!("{}.lock", first_ref.trim())).is_file());+ }+ if failure == SerializedDeleteFailure::ClassificationError {+ assert!(barriers.join(mode).exists());+ assert!(+ !stderr.contains("classification unavailable"),+ "classification failure must preserve original mutation error: {stderr}"+ );+ }+ crate::common::wait_for("all staged removals run post-remove", || {+ std::fs::read_to_string(&hooks).is_ok_and(|text| text.lines().count() == 8)+ });+}++/// Current-directory trash cleanup runs before CAS; the empty replacement+/// directory remains usable until the branch result lets prune finish.+#[cfg(unix)]+#[rstest]+fn test_prune_current_placeholder_survives_blocked_cas(mut repo: TestRepo) {+ repo.commit("initial");+ let original = repo.add_worktree("blocked-current");+ let barriers = repo.home_path().join("barriers");+ std::fs::create_dir_all(&barriers).unwrap();+ let wrapper = repo.home_path().join("git-wrapper");+ std::fs::create_dir_all(&wrapper).unwrap();+ write_prune_git_wrapper(+ &wrapper,+ &which::which("git").unwrap(),+ r#"+if has_delete blocked-current; then+ touch "$WORKTRUNK_TEST_CURRENT_BARRIERS/started"+ i=0+ while [ ! -f "$WORKTRUNK_TEST_CURRENT_BARRIERS/release" ]; do+ i=$((i+1))+ if [ "$i" -gt 600 ]; then+ touch "$WORKTRUNK_TEST_CURRENT_BARRIERS/timeout"+ exit 2+ fi+ sleep 0.05+ done+fi+"#,+ );+ let mut cmd = repo.wt_command();+ prepend_path(&mut cmd, &wrapper);+ let child = cmd+ .current_dir(&original)+ .env("WORKTRUNK_TEST_CURRENT_BARRIERS", &barriers)+ .args(["step", "prune", "--yes", "--min-age=0s"])+ .stdout(std::process::Stdio::piped())+ .stderr(std::process::Stdio::piped())+ .spawn()+ .unwrap();+ crate::common::wait_for("current-worktree CAS started", || {+ barriers.join("started").exists()+ });+ let trash = crate::common::resolve_git_common_dir(repo.root_path()).join("wt/trash");+ crate::common::wait_for("current-worktree trash cleaned while CAS waits", || {+ std::fs::read_dir(&trash).unwrap().next().is_none()+ });+ assert!(+ original.is_dir(),+ "current-directory placeholder must remain while CAS waits"+ );+ assert!(original.read_dir().unwrap().next().is_none());+ // The placeholder cleaner has a one-second delay. Keep CAS blocked past+ // that delay so prematurely scheduling it cannot pass on a fast machine.+ let absence_window =+ std::time::Duration::from_secs(1) + worktrunk::testing::SLEEP_FOR_ABSENCE_CHECK;+ let started = std::time::Instant::now();+ while started.elapsed() < absence_window {+ assert!(+ original.is_dir(),+ "placeholder removed before CAS completed"+ );+ std::thread::sleep(std::time::Duration::from_millis(10));+ }+ std::fs::write(barriers.join("release"), "ready").unwrap();+ let output = child.wait_with_output().unwrap();+ assert!(+ output.status.success(),+ "{}",+ String::from_utf8_lossy(&output.stderr)+ );+ assert!(!barriers.join("timeout").exists());+ crate::common::wait_for("current-directory placeholder removed after CAS", || {+ !original.exists()+ });+ assert!(+ !repo+ .git_command()+ .args(["rev-parse", "--verify", "refs/heads/blocked-current"])+ .run()+ .unwrap()+ .status+ .success()+ );}/// The first failing removal aborts the rest of the queue.@@ -2103,71 +2715,27 @@ fn test_prune_removal_failure_aborts_remaining_queue(repo: TestRepo) {}}-/// Concurrent failures: the first error is reported, the rest stay quiet.-///-/// Two failing removals rendezvous inside the shim (the barrier from-/// `test_prune_removals_run_concurrently`) so both are in flight before-/// either error lands — exercising the drain's duplicate-failure arm, which-/// logs at debug rather than printing a second error.-#[cfg(unix)]-#[rstest]-fn test_prune_concurrent_removal_failures_report_first(repo: TestRepo) {- repo.commit("initial");-- repo.create_branch("dupe-a");- repo.create_branch("dupe-b");-- let mut cmd = repo.wt_command();- cmd.env("RAYON_NUM_THREADS", "2"); // both jobs in flight at once- let git_wrapper_dir = repo.home_path().join("git-wrapper");- std::fs::create_dir_all(&git_wrapper_dir).unwrap();- write_barrier_failing_delete_wrapper(&git_wrapper_dir, &which::which("git").unwrap());- prepend_path(&mut cmd, &git_wrapper_dir);- let barrier_dir = repo.home_path().join("barrier");- std::fs::create_dir_all(&barrier_dir).unwrap();- cmd.env("WT_TEST_BARRIER_DIR", &barrier_dir);-- let output = cmd- .args(["step", "prune", "--yes", "--min-age=0s"])- .output()- .unwrap();- let stderr = String::from_utf8_lossy(&output.stderr);-- assert!(- !output.status.success(),- "failed removals must fail the run:\n{stderr}"- );- for name in ["dupe-a", "dupe-b"] {- assert!(- barrier_dir.join(format!("started-{name}")).exists(),- "the shim never fired for {name}"- );- }- // Exactly one candidate's failure reaches the terminal.- assert_eq!(- stderr.matches("removing branch dupe-").count(),- 1,- "exactly one of the concurrent failures should be reported:\n{stderr}"- );-}--/// A `git` shim that fails prune's CAS delete of-/// `refs/heads/$WT_TEST_FAIL_DELETE_BRANCH`. By default it deletes the ref for-/// real first, making `cas_delete_branch_outcome` propagate an error (ref gone-/// on re-check); with `WT_TEST_FAIL_DELETE_KEEPS_REF` set it leaves the ref,-/// which reads as `RetainedRaced` (a branch that moved during deletion).+/// Record the exact ref and expected SHA while letting shims intercept CAS.#[cfg(unix)]-fn write_failing_branch_delete_wrapper(dir: &std::path::Path, real_git: &std::path::Path) {+fn write_prune_git_wrapper(dir: &std::path::Path, real_git: &std::path::Path, body: &str) {use std::os::unix::fs::PermissionsExt;let real_git = shell_escape::unix::escape(real_git.to_string_lossy());+ let shell_dir = shell_escape::unix::escape(dir.to_string_lossy());let script = format!(r#"#!/bin/sh-if [ "$1" = "update-ref" ] && [ "$2" = "-d" ] && [ "$3" = "refs/heads/$WT_TEST_FAIL_DELETE_BRANCH" ]; then- [ -n "$WT_TEST_FAIL_DELETE_KEEPS_REF" ] || {real_git} update-ref -d "$3" || true- exit 1+if [ "$1 $2" = 'update-ref -d' ]; then+ printf '%s\n%s\n' "$3" "$4" > {shell_dir}/delete-$$fi-exec {real_git} "$@"+has_delete() {{+ [ "$original_command" = "update-ref -d refs/heads/$1" ]+}}+run_git() {{+ {real_git} "$@"+}}+original_command="$1 $2 $3"+{body}+run_git "$@""#);let path = dir.join("git");@@ -2177,54 +2745,53 @@ exec {real_git} "$@"std::fs::set_permissions(&path, permissions).unwrap();}-/// The barrier shim (see `write_barrier_git_wrapper`) with a failing tail:-/// both `dupe-{a,b}` deletions rendezvous, delete their ref for real, then-/// report failure — two concurrent removal errors.#[cfg(unix)]-fn write_barrier_failing_delete_wrapper(dir: &std::path::Path, real_git: &std::path::Path) {- use std::os::unix::fs::PermissionsExt;+fn prune_delete_calls(dir: &std::path::Path) -> Vec<String> {+ std::fs::read_dir(dir)+ .unwrap()+ .map(|entry| entry.unwrap().path())+ .filter(|path| {+ path.file_name()+ .unwrap()+ .to_string_lossy()+ .starts_with("delete-")+ })+ .map(|path| std::fs::read_to_string(path).unwrap())+ .collect()+}- let real_git = shell_escape::unix::escape(real_git.to_string_lossy());- let script = format!(- r#"#!/bin/sh-case "$1 $2 $3" in- "update-ref -d refs/heads/dupe-a") own=dupe-a; other=dupe-b ;;- "update-ref -d refs/heads/dupe-b") own=dupe-b; other=dupe-a ;;- *) exec {real_git} "$@" ;;-esac-: > "$WT_TEST_BARRIER_DIR/started-$own"-i=0-while [ ! -e "$WT_TEST_BARRIER_DIR/started-$other" ]; do- i=$((i+1))- if [ "$i" -gt 300 ]; then- break+/// Advance or remove the requested ref before rejecting its CAS transaction.+#[cfg(unix)]+fn write_failing_branch_delete_wrapper(dir: &std::path::Path, real_git: &std::path::Path) {+ let real = shell_escape::unix::escape(real_git.to_string_lossy());+ write_prune_git_wrapper(+ dir,+ real_git,+ &format!(+ r#"+if has_delete "$WT_TEST_FAIL_DELETE_BRANCH"; then+ [ -z "$WORKTRUNK_TEST_FAIL_DELETE_INTERRUPT" ] || kill -INT "$$"+ if [ -n "$WORKTRUNK_TEST_FAIL_DELETE_REPLACEMENT_SHA" ]; then+ {real} update-ref "refs/heads/$WT_TEST_FAIL_DELETE_BRANCH" "$WORKTRUNK_TEST_FAIL_DELETE_REPLACEMENT_SHA" || exit 2+ else+ {real} update-ref -d "refs/heads/$WT_TEST_FAIL_DELETE_BRANCH" || truefi- sleep 0.05-done-{real_git} update-ref -d "$3" || true-exit 1+ exit 1+fi"#+ ),);- 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();}-/// A `git` shim that holds the reflog read for `refs/heads/packed-b` until-/// `update-ref -d refs/heads/packed-a` has finished (see-/// `test_prune_removals_keep_packed_branch_ages`); everything else passes-/// through to the real git.+/// Keep the later age read behind a completed packed-ref transaction.#[cfg(unix)]fn write_deletion_ordering_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());- let script = format!(- r#"#!/bin/sh-if [ "$1 $2 $3" = "update-ref -d refs/heads/packed-a" ]; then- {real_git} "$@"+ write_prune_git_wrapper(+ dir,+ real_git,+ r#"+if has_delete packed-a; then+ run_git "$@"status=$?: > "$WT_TEST_BARRIER_DIR/deleted-packed-a"exit $status@@ -2244,49 +2811,44 @@ if [ "$1 $2" = "reflog show" ]; then;;esacfi-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();}-/// A `git` shim whose `update-ref -d refs/heads/para-{a,b}` arms rendezvous-/// with each other (see `test_prune_removals_run_concurrently`); everything-/// else passes through to the real git.+/// Rendezvous before staging and expose concurrent packed-ref writers.#[cfg(unix)]fn write_barrier_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());- let script = format!(- r#"#!/bin/sh-case "$1 $2 $3" in- "update-ref -d refs/heads/para-a") own=para-a; other=para-b ;;- "update-ref -d refs/heads/para-b") own=para-b; other=para-a ;;- *) exec {real_git} "$@" ;;-esac-: > "$WT_TEST_BARRIER_DIR/started-$own"-i=0-while [ ! -e "$WT_TEST_BARRIER_DIR/started-$other" ]; do- i=$((i+1))- if [ "$i" -gt 300 ]; then- : > "$WT_TEST_BARRIER_DIR/timeout-$own"- break+ write_prune_git_wrapper(+ dir,+ real_git,+ r#"+if has_delete para-a || has_delete para-b; then+ if (set -C; : > "$WORKTRUNK_TEST_PACKED_REFS_LOCK") 2>/dev/null; then+ sleep "$WORKTRUNK_TEST_REF_LOCK_WINDOW"+ rm "$WORKTRUNK_TEST_PACKED_REFS_LOCK"+ else+ : > "$WT_TEST_BARRIER_DIR/contended"fi- sleep 0.05-done-exec {real_git} "$@"-"#+fi+if [ "$1 $2" = "fsmonitor--daemon stop" ]; then+ case "$PWD" in+ *.para-a) own=para-a; other=para-b ;;+ *.para-b) own=para-b; other=para-a ;;+ *) run_git "$@"; exit $? ;;+ esac+ : > "$WT_TEST_BARRIER_DIR/started-$own"+ i=0+ while [ ! -e "$WT_TEST_BARRIER_DIR/started-$other" ]; do+ i=$((i+1))+ if [ "$i" -gt 300 ]; then+ : > "$WT_TEST_BARRIER_DIR/timeout-$own"+ break+ fi+ sleep 0.05+ done+fi+"#,);- 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)]@@ -2307,34 +2869,16 @@ fn prepend_path(cmd: &mut std::process::Command, dir: &std::path::Path) {#[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 every deletion shape this prune might take. `delete_branch_if_safe`- // emits one of:- // - `branch -D <branch>` (the force path, and the fallback when there's- // no snapshot SHA to compare-and-swap against)- // - `update-ref -d refs/heads/<branch> <expected-sha>` (the CAS path it- // takes when the branch is integrated)- // The `-d` arm below is also matched defensively for the plain-delete form;- // production no longer emits it.- 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-elif [ "$1" = "update-ref" ] && [ "$2" = "-d" ] && [ "$3" = "refs/heads/$WT_PRUNE_DELAY_BRANCH" ]; then+ write_prune_git_wrapper(+ dir,+ real_git,+ r#"+if has_delete "$WT_PRUNE_DELAY_BRANCH" || { [ "$1" = branch ] && [ "$2" = -D ] && [ "$4" = "$WT_PRUNE_DELAY_BRANCH" ]; }; then: > "$WT_PRUNE_BRANCH_DELETE_STARTED"sleep 2fi-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();}/// `wt step prune` sweeps stale worktrees unattended, so it's the worst place todiff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rsindex 8bfd4aada..e2abe174b 100644--- a/tests/integration_tests/switch.rs+++ b/tests/integration_tests/switch.rs@@ -331,7 +331,18 @@ fn test_switch_dwim_ambiguous_remotes(#[from(repo_with_remote)] mut repo: TestRe// Now shared-feature exists on origin and upstream but not locally// DWIM can't pick — git worktree add should error- snapshot_switch("switch_dwim_ambiguous_remotes", &repo, &["shared-feature"]);+ let mut settings = setup_snapshot_settings(&repo);+ // Git 2.50 reports an invalid reference; Git 2.56 names the ambiguity.+ settings.add_filter(+ r"'shared-feature' matched multiple \(2\) remote tracking branches",+ "invalid reference: shared-feature",+ );+ settings.bind(|| {+ assert_cmd_snapshot!(+ "switch_dwim_ambiguous_remotes",+ make_snapshot_cmd(&repo, "switch", &["shared-feature"], None)+ );+ });}/// `--base <branch>` should accept a branch that exists only as a remote-tracking ref