Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix(remove): gate removal on the registration, not the repository (#3808)
Maximilian Roos7aba380f0c89
diff --git a/docs/content/faq.md b/docs/content/faq.mdindex d2ce419dd..da49265e6 100644--- a/docs/content/faq.md+++ b/docs/content/faq.md@@ -177,7 +177,7 @@ Worktrunk can delete **worktrees** and **branches**. Both have safeguards.`wt remove` mirrors `git worktree remove`: it refuses to remove worktrees with uncommitted changes (staged, modified, or untracked files). The `--force` flag removes the worktree anyway, discarding all of those changes.-Removal also refuses, `--force` included, when the directory at a registered path has come to hold a *different* repository — a clone made there after the worktree was deleted, say. `--force` waives uncommitted changes, not the check for whose directory it is, and `git worktree remove` refuses the same case.+Removal also refuses, `--force` included, when the directory at a registered path no longer holds the worktree registered there — a clone made there after the worktree was deleted, say, or another worktree of the same repository moved onto the path. `--force` waives uncommitted changes, not the check for what the directory holds, and `git worktree remove` refuses the same cases.To protect a worktree from removal entirely (say it holds a local database), lock it:diff --git a/plugins/worktrunk/skills/worktrunk/reference/faq.md b/plugins/worktrunk/skills/worktrunk/reference/faq.mdindex 2f2d7c5a6..1b3da5e42 100644--- a/plugins/worktrunk/skills/worktrunk/reference/faq.md+++ b/plugins/worktrunk/skills/worktrunk/reference/faq.md@@ -170,7 +170,7 @@ Worktrunk can delete **worktrees** and **branches**. Both have safeguards.`wt remove` mirrors `git worktree remove`: it refuses to remove worktrees with uncommitted changes (staged, modified, or untracked files). The `--force` flag removes the worktree anyway, discarding all of those changes.-Removal also refuses, `--force` included, when the directory at a registered path has come to hold a *different* repository — a clone made there after the worktree was deleted, say. `--force` waives uncommitted changes, not the check for whose directory it is, and `git worktree remove` refuses the same case.+Removal also refuses, `--force` included, when the directory at a registered path no longer holds the worktree registered there — a clone made there after the worktree was deleted, say, or another worktree of the same repository moved onto the path. `--force` waives uncommitted changes, not the check for what the directory holds, and `git worktree remove` refuses the same cases.To protect a worktree from removal entirely (say it holds a local database), lock it:diff --git a/skills/worktrunk/reference/faq.md b/skills/worktrunk/reference/faq.mdindex 2f2d7c5a6..1b3da5e42 100644--- a/skills/worktrunk/reference/faq.md+++ b/skills/worktrunk/reference/faq.md@@ -170,7 +170,7 @@ Worktrunk can delete **worktrees** and **branches**. Both have safeguards.`wt remove` mirrors `git worktree remove`: it refuses to remove worktrees with uncommitted changes (staged, modified, or untracked files). The `--force` flag removes the worktree anyway, discarding all of those changes.-Removal also refuses, `--force` included, when the directory at a registered path has come to hold a *different* repository — a clone made there after the worktree was deleted, say. `--force` waives uncommitted changes, not the check for whose directory it is, and `git worktree remove` refuses the same case.+Removal also refuses, `--force` included, when the directory at a registered path no longer holds the worktree registered there — a clone made there after the worktree was deleted, say, or another worktree of the same repository moved onto the path. `--force` waives uncommitted changes, not the check for what the directory holds, and `git worktree remove` refuses the same cases.To protect a worktree from removal entirely (say it holds a local database), lock it:diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rsindex 0ac4ef357..481f4d382 100644--- a/src/commands/repository_ext.rs+++ b/src/commands/repository_ext.rs@@ -360,13 +360,12 @@ impl RepositoryCliExt for Repository {// upstream of the "Removing …" announcement, so the refusal arrives// before wt claims to be doing it.//- // `stage_worktree_removal` asks the same question at the rename, for- // the callers that reach it without planning here. That is not a- // re-validation of this one: `git_dir()` caches per worktree path for- // the process, so within a single removal the second call answers from- // the first. A directory swapped in between would not be caught — the- // same time-of-check window `ensure_clean` carries, and narrower.- target_wt.ensure_belongs_to_repo()?;+ // `stage_worktree_removal` asks again at the rename, and that is a+ // genuine re-check rather than a repeat of this one: the gate reads the+ // directory's `.git` entry every call, so a directory swapped in+ // between — across the approval prompt and the `pre-remove` hook — is+ // caught there.+ target_wt.ensure_holds_this_worktree()?;if !force_worktree {target_wt.ensure_clean("remove worktree", branch_name.as_deref(), true)?;diff --git a/src/git/error.rs b/src/git/error.rsindex 2acb68b85..a557938f5 100644--- a/src/git/error.rs+++ b/src/git/error.rs@@ -610,21 +610,34 @@ pub enum GitError {WorktreeNotFoundAtPath {path: PathBuf,},- /// A registered worktree's path that some *other* repository now occupies.+ /// A registered worktree's path that something else now occupies: another+ /// repository, or a sibling worktree of this one moved onto the path.////// The registration still resolves and the directory is still there, so- /// every check short of asking who owns it passes — including the- /// dirty-worktree gate, which reads the occupant's `git status` and- /// reports it as this worktree's. Removal is the operation that has to- /// care: the directory holds someone else's work, and possibly the only- /// copy of their objects.+ /// every check short of asking what the directory points at passes —+ /// including the dirty-worktree gate, which reads the occupant's `git+ /// status` and reports it as this worktree's. Removal is the operation that+ /// has to care: the directory holds work this registration cannot account+ /// for, and possibly the only copy of its objects.///- /// git refuses the same removal (`validation failed … is not a .git- /// file`), `--force` included. Worktrunk's fast path renames the directory- /// itself rather than asking git to, so it has to make this check for- /// itself — see `ensure_belongs_to_repo`.+ /// git refuses the same removal (`validation failed … does not point back+ /// to '.git/worktrees/<id>'`), `--force` included. Worktrunk's fast path+ /// renames the directory itself rather than asking git to, so it has to+ /// make this check for itself — see `ensure_holds_this_worktree`.WorktreePathNotOurs {path: PathBuf,+ /// Where the occupant's own registration records it, when this+ /// repository has a registration to ask: the occupant is one of its+ /// worktrees, sitting at the wrong path.+ ///+ /// `None` covers both ways that question goes unanswered — an occupant+ /// answering to a different repository, and a registration of ours whose+ /// `gitdir` file has gone missing. Neither names a path to move the+ /// directory to, so both take the hint that doesn't name one.+ ///+ /// The two remedies differ, which is why the case is carried rather+ /// than inferred at display time — see the hint below.+ occupant_registered_at: Option<PathBuf>,},/// --create flag used with pr:/mr: syntax (conflict - branch already exists)RefCreateConflict {@@ -892,9 +905,11 @@ impl GitError {cformat!("No worktree @ <bold>{path_display}</>")}- GitError::WorktreePathNotOurs { path } => {+ GitError::WorktreePathNotOurs { path, .. } => {let path_display = format_path_for_display(path);- cformat!("Directory @ <bold>{path_display}</> is not this repository's worktree")+ cformat!(+ "Directory @ <bold>{path_display}</> does not hold the worktree registered there"+ )}GitError::RefCreateConflict {@@ -1466,20 +1481,35 @@ impl GitError {)}- GitError::WorktreePathNotOurs { .. } => {+ GitError::WorktreePathNotOurs {+ occupant_registered_at,+ ..+ } => {let title = self.title();- write!(- f,- "{}\n{}",- error_message(&title),- // No `git worktree prune` on its own: prune keeps a- // registration whose directory resolves, which this one- // does — the occupant's own `.git` answers for it. Moving- // the directory is what makes prune able to act.- hint_message(cformat!(+ // Both remedies end in `git worktree prune`, and neither can+ // start with it: prune keeps a registration whose directory+ // resolves, which this one does — the occupant's own `.git`+ // answers for it. Moving the directory is what makes prune able+ // to act. Where it should move to is what the two cases+ // disagree on.+ let hint = match occupant_registered_at {+ // A worktree of this repository, whose own registration+ // still records the directory it left. Naming that path is+ // what keeps prune to the one stale entry: from anywhere+ // else both registrations are prunable, and clearing them+ // both leaves this checkout pointing at a registration that+ // no longer exists.+ Some(registered_at) => {+ let registered_display = format_path_for_display(registered_at);+ cformat!(+ "Removing it could destroy the worktree registered @ <underline>{registered_display}</>; move the directory back there, then run <underline>git worktree prune</>"+ )+ }+ None => cformat!("Removing it could destroy unrelated data; move the directory aside, then run <underline>git worktree prune</>"- ))- )+ ),+ };+ write!(f, "{}\n{}", error_message(&title), hint_message(hint))}GitError::RefCreateConflict {diff --git a/src/git/remove.rs b/src/git/remove.rsindex 7855a6114..ed1607fe2 100644--- a/src/git/remove.rs+++ b/src/git/remove.rs@@ -440,9 +440,9 @@ pub fn remove_worktree_with_cleanup(////// `wt remove` and `wt merge --remove` have already asked this during/// planning, where the answer can precede the "Removing …" announcement. The-/// call here is for the paths that stage without planning, not a fresh-/// re-check — `git_dir()` caches per worktree path, so a second call in the-/// same process answers from the first.+/// call here still re-reads the directory's `.git` entry, so it also closes the+/// window those two leave open: the approval prompt and the `pre-remove` hook+/// run between their check and this rename.////// # Errors///@@ -455,7 +455,8 @@ pub fn stage_worktree_removal(branch: Option<&str>,force_worktree: bool,) -> anyhow::Result<Option<PathBuf>> {- repo.worktree_at(worktree_path).ensure_belongs_to_repo()?;+ repo.worktree_at(worktree_path)+ .ensure_holds_this_worktree()?;if !force_worktree {repo.worktree_at(worktree_path)diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex 551b4e821..c2817c4ea 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -1326,26 +1326,38 @@ impl Repository {// A worktree's top-level path is its own `root()`.WORKTREE_ROOTS.entry(key.clone()).or_insert(key.clone());- if let Some(git_dir) = self.derive_worktree_git_dir(&key) {+ if let Some(git_dir) = Self::git_dir_at(&key) {GIT_DIRS.entry(key).or_insert(git_dir);}}}- /// Resolve a worktree's git dir from its `.git` entry without forking- /// `git rev-parse --git-dir`. A `.git` directory *is* the git dir (the main- /// worktree, whose common dir we already hold); a `.git` file holds+ /// The git dir a directory's own `.git` entry names, without forking+ /// `git rev-parse --git-dir`. A `.git` directory *is* the git dir (a main+ /// worktree, or the root of some other repository); a `.git` file holds/// `gitdir: <path>` pointing at `<common>/worktrees/<id>` (a linked/// worktree). Returns the canonicalized git dir, or `None` when the entry- /// is missing, unreadable, or in a form not worth second-guessing — the- /// caller then leaves it to the subprocess. Mirrors the `--git-dir`- /// canonicalization in [`Self::prewarm`] (`prewarm_rev_parse`).- fn derive_worktree_git_dir(&self, worktree: &Path) -> Option<PathBuf> {- let dot_git = worktree.join(".git");- let file_type = std::fs::symlink_metadata(&dot_git).ok()?.file_type();+ /// is missing, unreadable, or in a form not worth second-guessing. Mirrors+ /// the `--git-dir` canonicalization in [`Self::prewarm`]+ /// (`prewarm_rev_parse`).+ ///+ /// Answers for the directory rather than for a repository: it reads the+ /// `.git` entry sitting there and never walks up to a parent, which is what+ /// lets [`WorkingTree::ensure_holds_this_worktree`] compare the answer+ /// against this repository and learn something. Every call reads the+ /// filesystem, so a caller consulting it twice sees any change in between —+ /// the reason that gate uses it rather than the `GIT_DIRS`-cached+ /// [`WorkingTree::git_dir`].+ ///+ /// Two callers, with opposite readings of `None`:+ /// [`Self::prime_worktree_path_caches`] declines to seed a cache entry and+ /// leaves the answer to the subprocess, while the removal gate refuses.+ fn git_dir_at(dir: &Path) -> Option<PathBuf> {+ let dot_git = dir.join(".git");+ // Follows a symlinked `.git`, as git and the subprocess fallback do.+ let file_type = std::fs::metadata(&dot_git).ok()?.file_type();if file_type.is_dir() {- // Main worktree: git dir is the common dir (already canonicalized).- return Some(self.git_common_dir().to_path_buf());+ return canonicalize(&dot_git).ok();}if !file_type.is_file() {return None;@@ -1356,7 +1368,7 @@ impl Repository {let gitdir = content.lines().find_map(|l| l.strip_prefix("gitdir: "))?;let path = PathBuf::from(gitdir.trim());let absolute = if path.is_relative() {- worktree.join(path)+ dir.join(path)} else {path};diff --git a/src/git/repository/tests.rs b/src/git/repository/tests.rsindex 7a97d05f2..5f07dec8a 100644--- a/src/git/repository/tests.rs+++ b/src/git/repository/tests.rs@@ -2076,3 +2076,88 @@ fn worktree_is_unusable_covers_locked_absent_and_recreated() {"a recreated directory exists, so only the `prunable` half catches it");}++/// The ownership gate accepts a worktree that holds its own registration, in+/// both shapes: a linked worktree, whose `.git` file names a registration that+/// names it back, and the main worktree, which has no registration at all+/// because its git dir *is* the common dir.+///+/// The main-worktree arm is a backstop rather than a path a command reaches —+/// `wt remove` rejects the main worktree well before this gate, and a bare+/// repository's worktrees are all linked — so nothing through the CLI would+/// notice it inverting.+#[test]+fn ensure_holds_this_worktree_accepts_both_worktree_shapes() {+ use crate::git::Repository;+ use crate::testing::TestRepo;++ let mut test = TestRepo::with_initial_commit();+ let linked = test.add_worktree("linked");+ let repo = Repository::at(test.root_path()).unwrap();++ repo.worktree_at(&linked)+ .ensure_holds_this_worktree()+ .expect("a linked worktree holding its own registration is accepted");+ repo.worktree_at(test.root_path())+ .ensure_holds_this_worktree()+ .expect("the main worktree is accepted, having no registration to point back at");+}++/// The refusal names where the occupant belongs in a form the user can act on,+/// including when the registration records it relatively.+///+/// A relative `gitdir` entry is resolved against the registration directory, so+/// the recorded path arrives with a `..` chain through `.git/worktrees/<id>`+/// still in it, and the directory it names no longer exists — that is why the+/// gate is refusing. Plain canonicalization can't normalize a path that isn't+/// there, so the hint would otherwise print the traversal verbatim.+///+/// Asserted against `Diagnostic::render`, since the path is in the hint and+/// `Display` carries only the title.+#[test]+fn worktree_path_not_ours_names_a_normalized_path() {+ use crate::git::{Diagnostic, GitError, Repository};+ use crate::testing::TestRepo;++ let mut test = TestRepo::with_initial_commit();+ let occupied = test.add_worktree("occupied");+ let occupant = test.add_worktree("occupant");++ // Record the occupant's own worktree relatively, as git does under+ // `worktree.useRelativePaths`, then move it onto the other's path.+ let registration = PathBuf::from(+ std::fs::read_to_string(occupant.join(".git"))+ .unwrap()+ .trim()+ .strip_prefix("gitdir: ")+ .unwrap(),+ );+ let relative = PathBuf::from("../../../..")+ .join(occupant.file_name().unwrap())+ .join(".git");+ std::fs::write(+ registration.join("gitdir"),+ relative.to_string_lossy().as_ref(),+ )+ .unwrap();+ std::fs::remove_dir_all(&occupied).unwrap();+ std::fs::rename(&occupant, &occupied).unwrap();++ let repo = Repository::at(test.root_path()).unwrap();+ let refusal = repo+ .worktree_at(&occupied)+ .ensure_holds_this_worktree()+ .expect_err("the occupant's registration records a path it has left")+ .downcast_ref::<GitError>()+ .expect("the gate refuses with a GitError")+ .render();++ assert!(+ !refusal.contains(".."),+ "the refusal must name a normalized path:\n{refusal}"+ );+ assert!(+ refusal.contains(&occupant.file_name().unwrap().to_string_lossy().to_string()),+ "the refusal must name where the occupant belongs:\n{refusal}"+ );+}diff --git a/src/git/repository/working_tree.rs b/src/git/repository/working_tree.rsindex 48e235b4b..8d4e6bf88 100644--- a/src/git/repository/working_tree.rs+++ b/src/git/repository/working_tree.rs@@ -5,6 +5,7 @@ use std::path::{Path, PathBuf};use anyhow::Context;use dashmap::mapref::entry::Entry;+use crate::path::canonicalize_with_parents;use crate::shell_exec::Cmd;use dunce::canonicalize;@@ -71,6 +72,31 @@ fn sequencer_operation(git_dir: &Path) -> Option<InProgressOperation> {}}+/// The working tree a `<common>/worktrees/<id>` registration records, read from+/// its `gitdir` file.+///+/// The file holds the path of that working tree's `.git`, absolute or relative to+/// the registration directory — git writes the relative form under+/// `worktree.useRelativePaths` and resolves either, so both are ordinary. Its+/// parent is the working tree, which is the half of git's `validate_worktree`+/// that reads from the registration side.+///+/// Resolved through [`canonicalize_with_parents`], which normalizes the `..`+/// chain a relative entry leaves behind even though the directory it names may+/// no longer exist — the case the caller is usually asking about, and the path it+/// then shows the user. Normalizing rewrites spellings only, so it cannot make+/// two directories compare equal.+fn registration_worktree_path(registration: &Path) -> Option<PathBuf> {+ let content = std::fs::read_to_string(registration.join("gitdir")).ok()?;+ let recorded = PathBuf::from(content.trim());+ let absolute = if recorded.is_relative() {+ registration.join(recorded)+ } else {+ recorded+ };+ absolute.parent().map(canonicalize_with_parents)+}+/// Typed snapshot returned by [`WorkingTree::prewarm_info`].////// Mirrors what the batched `git rev-parse` actually resolved so callers can@@ -597,25 +623,36 @@ impl<'a> WorkingTree<'a> {Ok(git_dir != common_dir)}- /// Refuse when the directory at this worktree's path is not this- /// repository's worktree.+ /// Refuse when the directory at this worktree's path does not hold this+ /// worktree.////// Git makes this check itself before `git worktree remove` and refuses- /// with `validation failed … is not a .git file`, `--force` included.- /// Worktrunk's removal fast path renames the directory into trash rather- /// than asking git to (see+ /// with `validation failed … does not point back to+ /// '.git/worktrees/<id>'`, `--force` included. Worktrunk's removal fast+ /// path renames the directory into trash rather than asking git to (see/// [`stage_worktree_removal`](crate::git::remove::stage_worktree_removal)),/// so git's validation never runs and the guarantee has to be made here.- /// Removing the wrong directory is unrecoverable — the case this was- /// written for is a full clone that came to sit at a stale registration's- /// path, holding uncommitted work and the only copy of its objects.+ /// Removing the wrong directory is unrecoverable, whether it holds a full+ /// clone that came to sit at a stale registration's path (uncommitted work+ /// and, for a repo never pushed, the only copy of its objects) or a sibling+ /// worktree of this repository, moved onto the path after this one was+ /// deleted.+ ///+ /// So the test is git's own: the directory's `.git` must name *this+ /// registration*, and that registration's `gitdir` file must name this+ /// directory back (`registration_worktree_path`). Repository-level+ /// ownership is the weaker half: a sibling worktree's git dir sits under+ /// `<common>/worktrees/` too, so asking only which repository the occupant+ /// answers to accepts one moved onto this path. The main worktree is the+ /// same test where there is no registration to point back at: its git dir+ /// *is* the common dir, and that equality is the whole of it.///- /// The test is ownership of the git directory rather than git's- /// `.git`-is-a-file shape: a linked worktree's git dir sits under- /// `<common>/worktrees/`, the main worktree's *is* the common dir, and- /// anything else answers to a different repository. One comparison covers- /// both worktree kinds with no special case, and it rejects a `.git` file- /// pointing at another repository, which the shape test alone accepts.+ /// Resolution reads the `.git` entry in this directory on every call+ /// (`Repository::git_dir_at`) instead of going through the `GIT_DIRS`-cached+ /// [`git_dir`](Self::git_dir), which would answer from whenever an earlier+ /// caller asked. That is what makes the second call worth making: removal+ /// gates at planning and again at the rename, with the approval prompt and+ /// the `pre-remove` hook running in between.////// Deliberately not a `prunable` check — git leaves the registration alone/// precisely because the occupant's own `.git` resolves, so@@ -623,20 +660,35 @@ impl<'a> WorkingTree<'a> {/// two cover different halves of "the directory no longer holds this/// worktree": prunable is the half git notices, this is the half it does/// not.- pub fn ensure_belongs_to_repo(&self) -> anyhow::Result<()> {+ pub fn ensure_holds_this_worktree(&self) -> anyhow::Result<()> {let common_dir = self.repo.git_common_dir();- // A git directory that can't be resolved at all is the strongest form- // of "not ours": nothing there answers for this worktree. Treating it- // as a refusal keeps the failure closed, where propagating git's exit- // 128 would leave the caller to decide.- let is_ours = self.git_dir().is_ok_and(|git_dir| {- git_dir == common_dir || git_dir.starts_with(common_dir.join("worktrees"))- });- if is_ours {+ // A git dir that can't be resolved at all is the strongest form of "not+ // this worktree": nothing there answers for it. Treating that as a+ // refusal keeps the failure closed.+ let git_dir = Repository::git_dir_at(&self.path);+ if git_dir.as_deref() == Some(common_dir) {return Ok(());}++ // Where the occupant's own registration says it lives. `None` when there+ // is no registration of ours to ask — the occupant answers to a+ // different repository, or its registration here has lost its `gitdir`+ // file.+ let registrations = common_dir.join("worktrees");+ let occupant_registered_at = git_dir+ .filter(|git_dir| git_dir.parent() == Some(registrations.as_path()))+ .as_deref()+ .and_then(registration_worktree_path);+ if occupant_registered_at+ .as_deref()+ .is_some_and(|recorded| crate::path::paths_match(recorded, &self.path))+ {+ return Ok(());+ }+Err(GitError::WorktreePathNotOurs {path: self.path.clone(),+ occupant_registered_at,}.into())}diff --git a/src/path.rs b/src/path.rsindex 4ded02115..d98516e24 100644--- a/src/path.rs+++ b/src/path.rs@@ -163,6 +163,13 @@ pub fn expand_tilde(path: &Path) -> Cow<'_, Path> {/// For non-existent paths, canonicalizes the longest existing prefix and appends/// the remaining components. This handles macOS `/var` -> `/private/var` symlinks/// correctly for computed worktree paths that don't exist yet.+///+/// A `..` is resolved by the filesystem rather than collapsed lexically, which is+/// load-bearing where [`paths_match`] decides whether two paths name one+/// directory: crossing a symlink, the two readings name different directories,+/// and `WorkingTree::ensure_holds_this_worktree` compares a worktree+/// registration's recorded path against the directory sitting at it to decide+/// whether removal may delete that directory.pub(crate) fn canonicalize_with_parents(path: &Path) -> PathBuf {if let Ok(canonical) = canonicalize(path) {return canonical;diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rsindex d333a7283..ccc68b626 100644--- a/tests/integration_tests/remove.rs+++ b/tests/integration_tests/remove.rs@@ -8,6 +8,7 @@ use insta::assert_snapshot;use insta_cmd::assert_cmd_snapshot;use path_slash::PathExt as _;use rstest::rstest;+use std::path::{Path, PathBuf};#[rstest]fn test_remove_from_worktree(mut repo: TestRepo) {@@ -589,6 +590,160 @@ fn test_remove_refuses_foreign_repository_at_worktree_path(mut repo: TestRepo) {);}+/// The registration a worktree's `.git` file names — `<common>/worktrees/<id>`.+///+/// Read from the worktree rather than assembled from its directory name, so a+/// test never depends on how git derives the id.+fn registration_dir(worktree: &Path) -> PathBuf {+ let dot_git = std::fs::read_to_string(worktree.join(".git")).unwrap();+ PathBuf::from(dot_git.trim().strip_prefix("gitdir: ").unwrap())+}++/// A registration whose directory now holds a *sibling worktree of the same+/// repository* is refused on the same terms, `--force` included.+///+/// This is the case repository-level ownership cannot see: the occupant's git+/// dir sits under `<common>/worktrees/` like any worktree of this repo, so only+/// the pointer back — the registration's `gitdir` file naming this directory —+/// tells the two registrations apart. git refuses it (`does not point back to+/// '.git/worktrees/<id>'`), and what removal would destroy is a live checkout+/// with its own uncommitted work.+///+/// The occupant has to be *moved* onto the path rather than created there:+/// `git worktree add` refuses a registered path, which is what leaves a plain+/// `mv` as the way this state arises.+///+/// The hint is part of the assertion. Moving the occupant back to the path its+/// own registration records — which is what the hint names — leaves `git+/// worktree prune` with only the stale entry to clear; from anywhere else both+/// registrations are prunable, and clearing them both would leave this checkout+/// pointing at a registration that no longer exists.+#[rstest]+fn test_remove_refuses_sibling_worktree_at_worktree_path(mut repo: TestRepo) {+ let worktree_path = repo.add_worktree("feature");+ let sibling_path = repo.add_worktree("other");++ std::fs::remove_dir_all(&worktree_path).unwrap();+ std::fs::rename(&sibling_path, &worktree_path).unwrap();+ std::fs::write(worktree_path.join("precious.txt"), "unpushed work").unwrap();++ assert_cmd_snapshot!(make_snapshot_cmd(+ &repo,+ "remove",+ &["--force", "feature", "--yes"],+ None+ ));++ // The refusal is worth nothing if the directory went anyway: removal stages+ // by rename and deletes in a detached process, so the exit code alone would+ // not catch a staged-then-deleted tree.+ assert!(+ worktree_path.join("precious.txt").exists(),+ "the sibling worktree's uncommitted file must survive",+ );+ assert!(+ worktree_path.join(".git").is_file(),+ "the sibling worktree's link to its own registration must survive",+ );+}++/// The ownership gate is re-decided at the rename, not carried over from+/// planning.+///+/// Removal asks twice — once while planning, once with nothing between it and+/// the `mv` into trash — and the approval prompt and this `pre-remove` hook run+/// in between. So the hook repoints the worktree's `.git` at a sibling's+/// registration, exactly the state the planning gate had just cleared, and the+/// second gate has to catch it. Resolving through a per-process cache instead+/// would answer from the planning-time read and delete the directory.+#[rstest]+fn test_remove_rechecks_ownership_after_pre_remove_hook(mut repo: TestRepo) {+ let worktree_path = repo.add_worktree("feature");+ let sibling_registration = registration_dir(&repo.add_worktree("other"));++ // Hooks run under a POSIX shell on every platform (Git Bash on Windows), and+ // a TOML literal string carries the `"` the format needs verbatim.+ let hook = format!(+ r#"printf "gitdir: %s" {} > {}"#,+ sibling_registration.to_slash_lossy(),+ worktree_path.join(".git").to_slash_lossy(),+ );+ repo.write_project_config(&format!("pre-remove = '{hook}'"));+ repo.commit("Add pre-remove config");+ repo.write_test_config(r#"worktree-path = "../{{ repo }}.{{ branch }}""#);+ repo.write_test_approvals(&format!(+ r#"[projects."../origin"]+approved-commands = ['{hook}']+"#+ ));++ let output = repo+ .wt_command()+ .args(["remove", "--foreground", "feature"])+ .output()+ .unwrap();+ let stderr = String::from_utf8_lossy(&output.stderr);++ assert!(+ !output.status.success(),+ "removal must refuse once the hook has repointed the worktree.\nstderr: {stderr}"+ );+ assert!(+ stderr.contains("does not hold the worktree registered there"),+ "the refusal must come from the ownership gate, not the dirty check.\nstderr: {stderr}"+ );+ assert!(+ worktree_path.join("file.txt").exists(),+ "the worktree the hook repointed must survive.\nstderr: {stderr}"+ );+}++/// A registration recording its worktree with a *relative* `gitdir` entry is+/// recognized, and that worktree removes normally.+///+/// git writes the relative form under `worktree.useRelativePaths` and resolves+/// either, so the gate resolves an entry against the registration directory as+/// git does. Rewriting the entry rather than setting the config keeps this+/// independent of the git version that introduced the option — and git reads the+/// rewritten entry back, which is what makes it the same form git would write.+#[rstest]+fn test_remove_worktree_with_relative_registration_gitdir(mut repo: TestRepo) {+ let worktree_path = repo.add_worktree("feature");+ let registration = registration_dir(&worktree_path);++ // From `<repo>/.git/worktrees/<id>`, four levels up is the directory the+ // worktree sits in, under the default `../{{ repo }}.{{ branch }}` layout.+ let relative = Path::new("../../../..")+ .join(worktree_path.file_name().unwrap())+ .join(".git");+ assert_eq!(+ dunce::canonicalize(registration.join(&relative)).unwrap(),+ dunce::canonicalize(worktree_path.join(".git")).unwrap(),+ "the relative entry must resolve to this worktree's own .git",+ );+ std::fs::write(+ registration.join("gitdir"),+ relative.to_slash_lossy().as_ref(),+ )+ .unwrap();+ assert!(+ repo.git_output(&["worktree", "list", "--porcelain"])+ .contains(&worktree_path.to_slash_lossy().to_string()),+ "git must still resolve the worktree from the relative entry",+ );++ assert_cmd_snapshot!(make_snapshot_cmd(+ &repo,+ "remove",+ &["--foreground", "feature"],+ None+ ));+ assert!(+ !worktree_path.exists(),+ "the worktree directory must be gone",+ );+}+#[rstest]fn test_remove_partial_success(mut repo: TestRepo) {// Create one valid worktreediff --git a/tests/snapshots/integration__integration_tests__remove__remove_refuses_sibling_worktree_at_worktree_path.snap b/tests/snapshots/integration__integration_tests__remove__remove_refuses_sibling_worktree_at_worktree_path.snapnew file mode 100644index 000000000..4ee5aa7f5--- /dev/null+++ b/tests/snapshots/integration__integration_tests__remove__remove_refuses_sibling_worktree_at_worktree_path.snap@@ -0,0 +1,65 @@+---+source: tests/integration_tests/remove.rs+info:+ program: wt+ args:+ - remove+ - "--force"+ - feature+ - "--yes"+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "500"+ GIT_ALLOW_PROTOCOL: file+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_AUTHOR_EMAIL: [email protected]+ GIT_AUTHOR_NAME: Test User+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_EMAIL: [email protected]+ GIT_COMMITTER_NAME: Test User+ GIT_CONFIG_COUNT: "2"+ GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig+ GIT_CONFIG_KEY_0: user.useConfigOnly+ GIT_CONFIG_KEY_1: rerere.enabled+ GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig+ GIT_CONFIG_VALUE_0: "true"+ GIT_CONFIG_VALUE_1: "false"+ GIT_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"+ PATH: "[PATH]"+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"+ WORKTRUNK_TEST_BASH_INSTALLED: "0"+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"+ WORKTRUNK_TEST_CODEX_INSTALLED: "0"+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"+ WORKTRUNK_TEST_EPOCH: "1735776000"+ WORKTRUNK_TEST_FISH_INSTALLED: "0"+ WORKTRUNK_TEST_GEMINI_INSTALLED: "0"+ WORKTRUNK_TEST_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"+ WORKTRUNK_TEST_NUSHELL_ENV: "0"+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"+ WORKTRUNK_TEST_PARENT_SHELL: ""+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"+ WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"+ WORKTRUNK_TEST_PROBE_TIMEOUT_MS: "60000"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ WORKTRUNK_TEST_ZSH_INSTALLED: "0"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: false+exit_code: 1+----- stdout -----++----- stderr -----+[31m✗[39m [31mDirectory @ [1m_REPO_.feature[22m does not hold the worktree registered there[39m+[2m↳[22m [2mRemoving it could destroy the worktree registered @ [4m_REPO_.other[24m; move the directory back there, then run [4mgit worktree prune[24m[22mdiff --git a/tests/snapshots/integration__integration_tests__remove__remove_worktree_with_relative_registration_gitdir.snap b/tests/snapshots/integration__integration_tests__remove__remove_worktree_with_relative_registration_gitdir.snapnew file mode 100644index 000000000..41a83b28f--- /dev/null+++ b/tests/snapshots/integration__integration_tests__remove__remove_worktree_with_relative_registration_gitdir.snap@@ -0,0 +1,64 @@+---+source: tests/integration_tests/remove.rs+info:+ program: wt+ args:+ - remove+ - "--foreground"+ - feature+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "500"+ GIT_ALLOW_PROTOCOL: file+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_AUTHOR_EMAIL: [email protected]+ GIT_AUTHOR_NAME: Test User+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_EMAIL: [email protected]+ GIT_COMMITTER_NAME: Test User+ GIT_CONFIG_COUNT: "2"+ GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig+ GIT_CONFIG_KEY_0: user.useConfigOnly+ GIT_CONFIG_KEY_1: rerere.enabled+ GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig+ GIT_CONFIG_VALUE_0: "true"+ GIT_CONFIG_VALUE_1: "false"+ GIT_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"+ PATH: "[PATH]"+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"+ WORKTRUNK_TEST_BASH_INSTALLED: "0"+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"+ WORKTRUNK_TEST_CODEX_INSTALLED: "0"+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"+ WORKTRUNK_TEST_EPOCH: "1735776000"+ WORKTRUNK_TEST_FISH_INSTALLED: "0"+ WORKTRUNK_TEST_GEMINI_INSTALLED: "0"+ WORKTRUNK_TEST_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"+ WORKTRUNK_TEST_NUSHELL_ENV: "0"+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"+ WORKTRUNK_TEST_PARENT_SHELL: ""+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"+ WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"+ WORKTRUNK_TEST_PROBE_TIMEOUT_MS: "60000"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ WORKTRUNK_TEST_ZSH_INSTALLED: "0"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: true+exit_code: 0+----- stdout -----++----- stderr -----+[36m◎[39m [36mRemoving [1mfeature[22m worktree...[39m+[32m✓[39m [32mRemoved [1mfeature[22m worktree & branch (same commit as [1mmain[22m,[39m [2m_[22m[32m)[39m [90m(3 files · [BYTES] B[39m[90m)[39m