Skip to content

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

fix(remove): prune the named worktree's metadata, not the repository's (#3650)

Maximilian Roose9f69b203815
diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rs
index 8ba450fa2..a9733a6c2 100644
--- a/src/commands/picker/mod.rs
+++ b/src/commands/picker/mod.rs
@@ -3238,8 +3238,9 @@ pub mod tests {
/// concurrent background removal can trigger.
///
/// `apply` renames the worktree into the trash (so its path vanishes) and
- /// then runs `git worktree prune`, which deletes the `.git/worktrees/<id>`
- /// admin dir — all on a background thread. `git branch --list` enumerates
+ /// then runs `git worktree remove` on it, which deletes that worktree's
+ /// `.git/worktrees/<id>` admin dir — all on a background thread.
+ /// `git branch --list` enumerates
/// worktrees to mark checked-out branches, so a query that races the
/// in-flight prune can read a half-deleted admin dir and fail with
/// `exit 128`. A test that `.unwrap()`s such a query flakes; retry until the
diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rs
index d5b1ab2e7..ce8e19362 100644
--- a/src/commands/repository_ext.rs
+++ b/src/commands/repository_ext.rs
@@ -229,10 +229,17 @@ impl RepositoryCliExt for Repository {
// handling the branch-targeted path applies. A detached
// worktree has no branch to fall back to, so it proceeds and
// surfaces the removal error.
+ //
+ // The prune names this worktree rather than sweeping the repo,
+ // so a sibling whose directory is merely absent right now keeps
+ // its registration. `git worktree remove` refuses a locked
+ // worktree where a repo-wide prune ignored one, which needs no
+ // guard here: the lock check above already returned for every
+ // locked entry in this arm.
if let Some(branch) = wt.branch.as_deref()
&& !wt.path.exists()
{
- self.prune_worktrees()?;
+ self.prune_worktree_entry(&wt.path)?;
Resolved::BranchOnly {
pruned_from: Some(wt.path.clone()),
branch: branch.to_string(),
diff --git a/src/commands/step/prune.rs b/src/commands/step/prune.rs
index 290f22f10..9b1730fde 100644
--- a/src/commands/step/prune.rs
+++ b/src/commands/step/prune.rs
@@ -251,8 +251,8 @@ struct RemovalContext<'a> {
/// 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 prune` /
- /// `git worktree remove` (the rename-failure fallback) touches
+ /// `git update-ref -d`, and neither it nor `git worktree remove` (both the
+ /// scoped metadata prune and the rename-failure fallback) touches
/// `.git/config` — verified empirically by inode-watching `.git/config`
/// across each command — so hook-free removals only spawn readers of
/// shared repo state and can run concurrently. (`git branch -D` remains
@@ -276,11 +276,13 @@ struct RemovalContext<'a> {
/// trash-cleanup spinner, and concurrent spinners would fight over the
/// cursor.
/// - **`StaleDetached` and plan-less `Prunable` candidates** — both call
-/// `prune_worktrees()` fail-hard, so they don't race sibling prunes.
+/// `prune_worktree_entry()` fail-hard. The exclusion is now conservative:
+/// each call names its own stale entry, so it touches only that
+/// `.git/worktrees/<id>` and can no longer disturb a sibling's. TODO(prune):
+/// move these to the read-side fan-out.
/// (The fail-soft prune inside `stage_worktree_removal` stays on the read
-/// side: concurrent `git worktree prune` runs are idempotent and exit 0 —
-/// verified empirically — and a swallowed failure only leaves stale
-/// metadata for the next prune, never data loss. The scan's
+/// side, as it always has: a swallowed failure only leaves stale metadata
+/// for the next prune, never data loss. The scan's
/// `prepare_worktree_removal` can also prune under the read guard when a
/// Linked item's directory vanished mid-scan; `check_one` `.ok()`s that
/// prepare, so an error there just deselects the candidate.)
@@ -342,7 +344,16 @@ fn try_remove(
};
if matches!(candidate.kind, CandidateKind::StaleDetached) {
- ctx.repo.prune_worktrees()?;
+ // 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`
+ // never selects a locked worktree, so the scoped removal can't hit
+ // git's lock refusal.
+ let path = candidate
+ .path
+ .as_deref()
+ .context("stale detached candidate has no worktree path")?;
+ ctx.repo.prune_worktree_entry(path)?;
// A stale detached entry has no branch to delete.
return Ok(Some(false));
}
@@ -416,7 +427,8 @@ struct CheckOutcome {
/// `None` means not removable (dirty, locked, primary — filtered
/// silently, never reported as "younger than") — except for `Prunable`
/// items, which are always removable but plan in `try_remove`: preparing
- /// them calls `prune_worktrees()`, a mutation that must stay serialized.
+ /// them calls `prune_worktree_entry()`, a mutation that must stay
+ /// serialized.
plan: Option<RemovalPlan>,
/// Whether the item passed the removability gate (see `plan`).
removable: bool,
diff --git a/src/git/remove.rs b/src/git/remove.rs
index 9a7824bb7..d18684f8a 100644
--- a/src/git/remove.rs
+++ b/src/git/remove.rs
@@ -391,14 +391,23 @@ pub fn remove_worktree_with_cleanup(
/// This is a lower-level building block exposed for callers that want to
/// stage the directory up-front and defer the `rm -rf` to a detached
/// background process (the pattern `wt remove` uses internally).
+///
+/// The metadata cleanup names this worktree
+/// ([`prune_worktree_entry`](Repository::prune_worktree_entry)) rather than
+/// sweeping the repository, so a sibling worktree whose directory happens to
+/// be absent right now keeps its registration. A locked worktree never reaches
+/// here — `prepare_worktree_removal` rejects one before staging.
pub fn stage_worktree_removal(repo: &Repository, worktree_path: &Path) -> Option<PathBuf> {
let trash_dir = repo.wt_trash_dir();
let _ = std::fs::create_dir_all(&trash_dir);
let staged_path = generate_removing_path(&trash_dir, worktree_path);
if std::fs::rename(worktree_path, &staged_path).is_ok() {
- if let Err(e) = repo.prune_worktrees() {
- tracing::debug!(error = %e, "Failed to prune worktrees after rename: {e}");
+ // The rename moved the directory out from under `worktree_path`, so
+ // git resolves the entry by its recorded path and skips the clean
+ // check.
+ if let Err(e) = repo.prune_worktree_entry(worktree_path) {
+ tracing::debug!(error = %e, "Failed to prune worktree entry after rename: {e}");
}
Some(staged_path)
} else {
diff --git a/src/git/repository/worktrees.rs b/src/git/repository/worktrees.rs
index 9bb501a31..8452aeda5 100644
--- a/src/git/repository/worktrees.rs
+++ b/src/git/repository/worktrees.rs
@@ -4,6 +4,7 @@ use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::sync::{LazyLock, Mutex};
+use anyhow::Context as _;
use color_print::cformat;
use dunce::canonicalize;
@@ -116,13 +117,44 @@ impl Repository {
.map(|wt| (wt.path.clone(), wt.branch.clone())))
}
- /// Prune worktree entries whose directories no longer exist.
+ /// Unregister the one worktree at `path`, whose directory is already gone.
///
- /// Git tracks worktrees in `.git/worktrees/`. If a worktree directory is deleted
- /// externally (e.g., `rm -rf`), this method runs `git worktree prune` to clean
- /// up the entries.
- pub fn prune_worktrees(&self) -> anyhow::Result<()> {
- self.run_command(&["worktree", "prune"])?;
+ /// Git tracks worktrees in `.git/worktrees/<id>/`. When a worktree's
+ /// directory disappears — deleted externally, or renamed into the trash by
+ /// [`stage_worktree_removal`](crate::git::remove::stage_worktree_removal) —
+ /// that admin dir is stale and has to go. `git worktree remove` skips its
+ /// clean check when the directory is missing and deletes just that entry,
+ /// so it is the scoped spelling of the cleanup.
+ ///
+ /// # Why not `git worktree prune`
+ ///
+ /// `git worktree prune` takes no path filter: it walks *every* entry and
+ /// unregisters each one whose directory it cannot find at that instant. A
+ /// worktree that is merely absent right now — an unmounted volume, a
+ /// dropped network mount, a half-finished `mv` — is indistinguishable from
+ /// a deleted one, so removing worktree A would also unregister bystander
+ /// B. B's committed work survives (refs and objects are shared) and its
+ /// files stay on disk, but its admin dir does not: the index, `ORIG_HEAD`,
+ /// the per-worktree reflog, `refs/worktree/*` and `refs/bisect/*`, and any
+ /// in-progress rebase or merge all go with it. `git worktree repair`
+ /// cannot rebuild them — it relinks an admin dir, it does not recreate
+ /// one. Naming the target keeps a removal's blast radius equal to its
+ /// intent.
+ ///
+ /// # Locked worktrees
+ ///
+ /// A repo-wide prune silently skips a locked entry; `git worktree remove`
+ /// fails on one instead. Every call site has already established the target
+ /// is unlocked, by a different route each: `prepare_worktree_removal`
+ /// returns `WorktreeLocked` at the top of its path/current arm and rejects
+ /// a locked worktree before staging one for removal, and prune's
+ /// `gather_check_items` never selects one as a candidate.
+ pub fn prune_worktree_entry(&self, path: &Path) -> anyhow::Result<()> {
+ // Every caller's path came from `list_worktrees`, which parses git's
+ // porcelain as UTF-8, so this only fires if that edge ever stops
+ // guaranteeing it — a bare `?` rather than a rendered path.
+ let path_str = path.to_str().context("worktree path is not valid UTF-8")?;
+ self.run_command(&["worktree", "remove", path_str])?;
Ok(())
}
diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rs
index c1e0fd92d..3074b58f5 100644
--- a/tests/integration_tests/remove.rs
+++ b/tests/integration_tests/remove.rs
@@ -4305,3 +4305,77 @@ fn test_remove_last_live_checkout_deletes_branch(mut repo: TestRepo) {
"a stale entry is not a checkout to retain the branch for\nstderr:\n{stderr}",
);
}
+
+/// Assert git still tracks `branch`'s worktree — that its `.git/worktrees/<id>`
+/// admin dir survived a neighbouring removal.
+fn assert_still_registered(repo: &TestRepo, branch: &str) {
+ let listed = repo
+ .git_command()
+ .args(["worktree", "list", "--porcelain"])
+ .run()
+ .unwrap();
+ let listed = String::from_utf8_lossy(&listed.stdout);
+ assert!(
+ listed.contains(&format!("branch refs/heads/{branch}")),
+ "worktree for `{branch}` must still be registered\n{listed}"
+ );
+}
+
+/// Displace a worktree's directory, as an unmounted volume or a half-finished
+/// `mv` would, and return the path it was parked at.
+fn displace(worktree: &std::path::Path) -> std::path::PathBuf {
+ let parked = worktree.parent().unwrap().join("displaced-elsewhere");
+ std::fs::rename(worktree, &parked).unwrap();
+ parked
+}
+
+/// A removal clears the metadata for the worktree it was asked to remove, and
+/// for no other.
+///
+/// `git worktree prune` takes no path filter: it unregisters every entry whose
+/// directory it cannot find at that instant. A sibling that is merely absent is
+/// indistinguishable from a deleted one, so a repo-wide sweep would take its
+/// `.git/worktrees/<id>` admin dir too — discarding the index, `ORIG_HEAD`, the
+/// per-worktree refs, and any in-progress rebase. `git worktree repair` cannot
+/// rebuild those, so the removal has to name its target.
+#[rstest]
+fn test_remove_spares_absent_sibling(mut repo: TestRepo) {
+ let victim = repo.add_worktree("victim");
+ let bystander = repo.add_worktree("bystander");
+ let parked = displace(&bystander);
+
+ run_remove(&repo, &["--foreground", "victim"]);
+ assert!(!victim.exists(), "the named worktree should be gone");
+
+ // The bystander's volume comes back.
+ std::fs::rename(&parked, &bystander).unwrap();
+ assert_still_registered(&repo, "bystander");
+}
+
+/// The same guarantee on the missing-directory route: `wt remove` on a worktree
+/// whose directory is already gone degrades to a branch-only deletion, and the
+/// stale-metadata cleanup that precedes it must also spare a displaced sibling.
+#[rstest]
+fn test_remove_stale_entry_spares_absent_sibling(mut repo: TestRepo) {
+ let victim = repo.add_worktree("victim");
+ let bystander = repo.add_worktree("bystander");
+ std::fs::remove_dir_all(&victim).unwrap();
+ let parked = displace(&bystander);
+
+ run_remove(&repo, &["--foreground", "victim"]);
+
+ std::fs::rename(&parked, &bystander).unwrap();
+ assert_still_registered(&repo, "bystander");
+
+ // The entry that was actually targeted is the one that went.
+ let listed = repo
+ .git_command()
+ .args(["worktree", "list", "--porcelain"])
+ .run()
+ .unwrap();
+ let listed = String::from_utf8_lossy(&listed.stdout);
+ assert!(
+ !listed.contains("branch refs/heads/victim"),
+ "the stale entry should have been pruned\n{listed}"
+ );
+}
diff --git a/tests/integration_tests/step_prune.rs b/tests/integration_tests/step_prune.rs
index 85f7788d1..769332538 100644
--- a/tests/integration_tests/step_prune.rs
+++ b/tests/integration_tests/step_prune.rs
@@ -1558,8 +1558,9 @@ fn test_prune_fallback_config_race_canary(mut repo: TestRepo) {
/// continues: `try_remove` treats a preparation error as "not selected", not
/// a command failure. Preparing a stale entry prunes its metadata — the
/// mutation that keeps `Prunable` candidates planning under the write lock
-/// rather than on the scan — so a `git` shim failing `worktree prune` is the
-/// deterministic trigger. Unix-only for the same `CreateProcess` reason as
+/// rather than on the scan — and it names the entry (`git worktree remove`)
+/// rather than sweeping the repo, so a `git` shim failing `worktree remove` is
+/// the deterministic trigger. Unix-only for the same `CreateProcess` reason as
/// the canary shim above.
#[cfg(unix)]
#[rstest]
@@ -1574,10 +1575,10 @@ fn test_prune_skips_prunable_candidate_whose_preparation_fails(mut repo: TestRep
let mut cmd = repo.wt_command();
let git_wrapper_dir = repo.home_path().join("git-wrapper");
std::fs::create_dir_all(&git_wrapper_dir).unwrap();
- write_failing_worktree_prune_wrapper(&git_wrapper_dir, &which::which("git").unwrap());
+ write_failing_worktree_remove_wrapper(&git_wrapper_dir, &which::which("git").unwrap());
prepend_path(&mut cmd, &git_wrapper_dir);
- let prune_failed_marker = repo.home_path().join("worktree-prune-failed");
- cmd.env("WT_TEST_WORKTREE_PRUNE_FAILED", &prune_failed_marker);
+ let prune_failed_marker = repo.home_path().join("worktree-remove-failed");
+ cmd.env("WT_TEST_WORKTREE_REMOVE_FAILED", &prune_failed_marker);
let output = cmd
.args(["step", "prune", "--yes", "--min-age=0s"])
@@ -1870,18 +1871,18 @@ exec {real_git} "$@"
std::fs::set_permissions(&path, permissions).unwrap();
}
-/// A `git` shim that fails every `git worktree prune` and passes everything
+/// A `git` shim that fails every `git worktree remove` and passes everything
/// else through to the real git.
#[cfg(unix)]
-fn write_failing_worktree_prune_wrapper(dir: &std::path::Path, real_git: &std::path::Path) {
+fn write_failing_worktree_remove_wrapper(dir: &std::path::Path, real_git: &std::path::Path) {
use std::os::unix::fs::PermissionsExt;
let real_git = shell_escape::unix::escape(real_git.to_string_lossy());
let script = format!(
r#"#!/bin/sh
-if [ "$1" = "worktree" ] && [ "$2" = "prune" ]; then
- : > "$WT_TEST_WORKTREE_PRUNE_FAILED"
- echo "shim: worktree prune disabled" >&2
+if [ "$1" = "worktree" ] && [ "$2" = "remove" ]; then
+ : > "$WT_TEST_WORKTREE_REMOVE_FAILED"
+ echo "shim: worktree remove disabled" >&2
exit 1
fi
exec {real_git} "$@"