Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix(remove, prune, merge): target the named worktree, retain shared branches (#3533)
Worktrunk Bot4af04c2260cc
diff --git a/docs/content/faq.md b/docs/content/faq.mdindex 394fa485f..afca131c8 100644--- a/docs/content/faq.md+++ b/docs/content/faq.md@@ -191,6 +191,8 @@ For the full algorithm, see [Branch cleanup](@/remove.md#branch-cleanup) — itUse `-D` to force-delete branches with unmerged changes. Use `--no-delete-branch` to keep the branch regardless of status.+A branch checked out in a second worktree is retained regardless, `-D` included. Deleting it would leave that worktree unable to resolve `HEAD`; only `git worktree add --force` produces that state.+### Other cleanup- `wt remove` — besides the target worktree, two cleanup mechanisms run. The removed worktree's own `git fsmonitor--daemon` (git's per-worktree filesystem watcher under `core.fsmonitor=true`, which would leak once its worktree is gone) is sent `git fsmonitor--daemon stop`, then force-terminated (`SIGTERM`, then `SIGKILL`) via the PID resolved from its IPC socket if it didn't exit. A background sweep then deletes `.git/wt/trash/` entries older than 24 hours (directories orphaned when a previous background removal was interrupted) and terminates fsmonitor daemons whose worktree no longer exists (orphans from `git worktree remove`, `rm -rf`, or a crashed `wt`)diff --git a/docs/content/remove.md b/docs/content/remove.mdindex 362dc9d3a..68b078309 100644--- a/docs/content/remove.md+++ b/docs/content/remove.md@@ -54,6 +54,8 @@ The 'same commit' check uses the local default branch; for other checks, 'targetBranches matching these conditions and with empty working trees are dimmed in `wt list` as safe to delete.+Those six ask whether deleting loses work. A branch checked out in a second worktree (only reachable via `git worktree add --force`) fails a different test: deleting the ref would leave that worktree unable to resolve `HEAD`, which is why `git branch -d` refuses the same delete. Such a branch is retained whatever `-D` asks, and the surviving checkout is named.+## Force flagsWorktrunk has two force flags for different situations:diff --git a/plugins/worktrunk/skills/worktrunk/reference/faq.md b/plugins/worktrunk/skills/worktrunk/reference/faq.mdindex 46c49169f..3d055e05c 100644--- a/plugins/worktrunk/skills/worktrunk/reference/faq.md+++ b/plugins/worktrunk/skills/worktrunk/reference/faq.md@@ -186,6 +186,8 @@ For the full algorithm, see [Branch cleanup](https://worktrunk.dev/remove/#brancUse `-D` to force-delete branches with unmerged changes. Use `--no-delete-branch` to keep the branch regardless of status.+A branch checked out in a second worktree is retained regardless, `-D` included. Deleting it would leave that worktree unable to resolve `HEAD`; only `git worktree add --force` produces that state.+### Other cleanup- `wt remove` — besides the target worktree, two cleanup mechanisms run. The removed worktree's own `git fsmonitor--daemon` (git's per-worktree filesystem watcher under `core.fsmonitor=true`, which would leak once its worktree is gone) is sent `git fsmonitor--daemon stop`, then force-terminated (`SIGTERM`, then `SIGKILL`) via the PID resolved from its IPC socket if it didn't exit. A background sweep then deletes `.git/wt/trash/` entries older than 24 hours (directories orphaned when a previous background removal was interrupted) and terminates fsmonitor daemons whose worktree no longer exists (orphans from `git worktree remove`, `rm -rf`, or a crashed `wt`)diff --git a/plugins/worktrunk/skills/worktrunk/reference/remove.md b/plugins/worktrunk/skills/worktrunk/reference/remove.mdindex c5c9e4881..b13df326a 100644--- a/plugins/worktrunk/skills/worktrunk/reference/remove.md+++ b/plugins/worktrunk/skills/worktrunk/reference/remove.md@@ -53,6 +53,8 @@ The 'same commit' check uses the local default branch; for other checks, 'targetBranches matching these conditions and with empty working trees are dimmed in `wt list` as safe to delete.+Those six ask whether deleting loses work. A branch checked out in a second worktree (only reachable via `git worktree add --force`) fails a different test: deleting the ref would leave that worktree unable to resolve `HEAD`, which is why `git branch -d` refuses the same delete. Such a branch is retained whatever `-D` asks, and the surviving checkout is named.+## Force flagsWorktrunk has two force flags for different situations:diff --git a/skills/worktrunk/reference/faq.md b/skills/worktrunk/reference/faq.mdindex 46c49169f..3d055e05c 100644--- a/skills/worktrunk/reference/faq.md+++ b/skills/worktrunk/reference/faq.md@@ -186,6 +186,8 @@ For the full algorithm, see [Branch cleanup](https://worktrunk.dev/remove/#brancUse `-D` to force-delete branches with unmerged changes. Use `--no-delete-branch` to keep the branch regardless of status.+A branch checked out in a second worktree is retained regardless, `-D` included. Deleting it would leave that worktree unable to resolve `HEAD`; only `git worktree add --force` produces that state.+### Other cleanup- `wt remove` — besides the target worktree, two cleanup mechanisms run. The removed worktree's own `git fsmonitor--daemon` (git's per-worktree filesystem watcher under `core.fsmonitor=true`, which would leak once its worktree is gone) is sent `git fsmonitor--daemon stop`, then force-terminated (`SIGTERM`, then `SIGKILL`) via the PID resolved from its IPC socket if it didn't exit. A background sweep then deletes `.git/wt/trash/` entries older than 24 hours (directories orphaned when a previous background removal was interrupted) and terminates fsmonitor daemons whose worktree no longer exists (orphans from `git worktree remove`, `rm -rf`, or a crashed `wt`)diff --git a/skills/worktrunk/reference/remove.md b/skills/worktrunk/reference/remove.mdindex c5c9e4881..b13df326a 100644--- a/skills/worktrunk/reference/remove.md+++ b/skills/worktrunk/reference/remove.md@@ -53,6 +53,8 @@ The 'same commit' check uses the local default branch; for other checks, 'targetBranches matching these conditions and with empty working trees are dimmed in `wt list` as safe to delete.+Those six ask whether deleting loses work. A branch checked out in a second worktree (only reachable via `git worktree add --force`) fails a different test: deleting the ref would leave that worktree unable to resolve `HEAD`, which is why `git branch -d` refuses the same delete. Such a branch is retained whatever `-D` asks, and the surviving checkout is named.+## Force flagsWorktrunk has two force flags for different situations:diff --git a/src/cli/mod.rs b/src/cli/mod.rsindex 127c5610b..3513134ba 100644--- a/src/cli/mod.rs+++ b/src/cli/mod.rs@@ -1277,6 +1277,8 @@ The 'same commit' check uses the local default branch; for other checks, 'targetBranches matching these conditions and with empty working trees are dimmed in `wt list` as safe to delete.+Those six ask whether deleting loses work. A branch checked out in a second worktree (only reachable via `git worktree add --force`) fails a different test: deleting the ref would leave that worktree unable to resolve `HEAD`, which is why `git branch -d` refuses the same delete. Such a branch is retained whatever `-D` asks, and the surviving checkout is named.+## Force flagsWorktrunk has two force flags for different situations:diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rsindex e14fc8036..6f9aeeb13 100644--- a/src/commands/picker/mod.rs+++ b/src/commands/picker/mod.rs@@ -2803,6 +2803,7 @@ pub mod tests {integration_reason: None,force_worktree: false,removed_commit: None,+ branch_checked_out_at: None,};AltXRemover::do_removal(&repo, &result, &Approvals::default()).unwrap();@@ -2826,6 +2827,7 @@ pub mod tests {pruned: false,target_branch: None,integration_reason: None,+ branch_checked_out_at: None,};AltXRemover::do_removal(&repo, &result, &Approvals::default()).unwrap();@@ -2852,6 +2854,7 @@ pub mod tests {pruned: false,target_branch: None,integration_reason: None,+ branch_checked_out_at: None,};AltXRemover::do_removal(&repo, &result, &Approvals::default()).unwrap();@@ -2898,6 +2901,7 @@ pub mod tests {integration_reason: None,force_worktree: false,removed_commit: None,+ branch_checked_out_at: None,};AltXRemover::do_removal(&repo, &result, &Approvals::default()).unwrap();@@ -2989,6 +2993,7 @@ pub mod tests {integration_reason: None,force_worktree: false,removed_commit: None,+ branch_checked_out_at: None,};// Empty approvals → `approve_readonly` drops the unapproved project@@ -3676,6 +3681,7 @@ pub mod tests {integration_reason: None,force_worktree: false,removed_commit: None,+ branch_checked_out_at: None,};assert_eq!(super::removal_failure_subject(&branched),@@ -3692,6 +3698,7 @@ pub mod tests {integration_reason: None,force_worktree: false,removed_commit: None,+ branch_checked_out_at: None,};assert_eq!(super::removal_failure_subject(&detached),@@ -3704,6 +3711,7 @@ pub mod tests {pruned: false,target_branch: None,integration_reason: None,+ branch_checked_out_at: None,};assert_eq!(super::removal_failure_subject(&branch_only),@@ -4040,6 +4048,7 @@ pub mod tests {integration_reason: None,force_worktree: false,removed_commit: None,+ branch_checked_out_at: None,};assert_eq!(@@ -4138,6 +4147,7 @@ pub mod tests {integration_reason: None,force_worktree: false,removed_commit: None,+ branch_checked_out_at: None,};assert!(super::removal_target_still_present(&repo,@@ -4155,6 +4165,7 @@ pub mod tests {pruned: false,target_branch: None,integration_reason: None,+ branch_checked_out_at: None,};assert!(super::removal_target_still_present(&repo, &present_branch));@@ -4164,6 +4175,7 @@ pub mod tests {pruned: false,target_branch: None,integration_reason: None,+ branch_checked_out_at: None,};assert!(!super::removal_target_still_present(&repo, &gone_branch));}@@ -4184,6 +4196,7 @@ pub mod tests {pruned: false,target_branch: None,integration_reason: integration,+ branch_checked_out_at: None,}};@@ -4197,6 +4210,7 @@ pub mod tests {integration_reason: None,force_worktree: false,removed_commit: None,+ branch_checked_out_at: None,};assert!(super::removal_will_remove_target(&worktree),@@ -4243,6 +4257,7 @@ pub mod tests {integration_reason: None,force_worktree: false,removed_commit: None,+ branch_checked_out_at: None,};assert!(super::removal_targets_current_worktree(&worktree(true)),@@ -4259,6 +4274,7 @@ pub mod tests {pruned: false,target_branch: None,integration_reason: None,+ branch_checked_out_at: None,}),"a branch-only row has no worktree to be standing in");diff --git a/src/commands/remove.rs b/src/commands/remove.rsindex 7bcbbd16f..875ca995a 100644--- a/src/commands/remove.rs+++ b/src/commands/remove.rs@@ -101,7 +101,7 @@ fn validate_remove_targets(};match resolved {- ResolvedWorktree::Worktree { path, branch } => {+ ResolvedWorktree::Worktree { path, branch: _ } => {// Use canonical paths to avoid symlink/normalization mismatcheslet path_canonical = dunce::canonicalize(&path).unwrap_or(path);let is_current = current_worktree.as_ref() == Some(&path_canonical);@@ -121,13 +121,14 @@ fn validate_remove_targets(continue;}- // Non-current worktree: remove by branch name, or by path for- // detached worktrees (which have no branch).- let target = if let Some(ref branch_name) = branch {- RemoveTarget::Branch(branch_name)- } else {- RemoveTarget::Path(&path_canonical)- };+ // Remove exactly the resolved worktree by its path. Targeting by+ // branch name would resolve an ambiguous branch (one checked out+ // in several worktrees via `git worktree add --force`) back to+ // git's first-listed worktree — removing the wrong one — whereas+ // the path is unambiguous. `prepare_worktree_removal` still+ // deletes the branch when it's the sole checkout, and retains it+ // otherwise (see its shared-branch handling).+ let target = RemoveTarget::Path(&path_canonical);match repo.prepare_worktree_removal(target,deletion_mode,diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rsindex 74bbc6948..4128c8560 100644--- a/src/commands/repository_ext.rs+++ b/src/commands/repository_ext.rs@@ -2,7 +2,7 @@ use std::path::{Path, PathBuf};use std::process;use std::time::{SystemTime, UNIX_EPOCH};-use super::worktree::RemoveResult;+use super::worktree::{RemoveResult, SharedBranchCheckout};use anyhow::{Context, bail};use color_print::cformat;use worktrunk::git::{@@ -132,8 +132,13 @@ impl RepositoryCliExt for Repository {is_current: bool,},BranchOnly {+ /// Path of the stale worktree entry this fell back from, when+ /// the fallback was a prune. `None` when the branch never had a+ /// worktree, which is also the only case with no sibling to+ /// check — a branch whose worktree exists resolves to+ /// `Worktree` above.+ pruned_from: Option<PathBuf>,branch: String,- pruned: bool,},}@@ -148,8 +153,8 @@ impl RepositoryCliExt for Repository {// Directory missing - prune and continueself.prune_worktrees()?;Resolved::BranchOnly {+ pruned_from: Some(wt.path.clone()),branch: branch.to_string(),- pruned: true,}} else if wt.locked.is_some() {return Err(GitError::WorktreeLocked {@@ -188,8 +193,8 @@ impl RepositoryCliExt for Repository {.into());}Resolved::BranchOnly {+ pruned_from: None,branch: branch.to_string(),- pruned: false,}}}@@ -201,27 +206,42 @@ impl RepositoryCliExt for Repository {};let wt = worktrees.iter()- .find(|wt| wt.path == lookup_path)+ .find(|wt| worktrunk::path::paths_match(&wt.path, lookup_path)).ok_or_else(|| {anyhow::anyhow!("Worktree not found at {}", lookup_path.display())})?;- if wt.locked.is_some() {- let name = wt- .branch- .clone()- .unwrap_or_else(|| wt.dir_name().to_string());- return Err(GitError::WorktreeLocked {- branch: name,+ // Directory missing (e.g. external `rm -rf`): prune the stale+ // metadata and fall back to branch-only deletion — the same+ // handling the branch-targeted path applies. A detached+ // worktree has no branch to fall back to, so it proceeds and+ // surfaces the removal error.+ if let Some(branch) = wt.branch.as_deref()+ && !wt.path.exists()+ {+ self.prune_worktrees()?;+ Resolved::BranchOnly {+ pruned_from: Some(wt.path.clone()),+ branch: branch.to_string(),+ }+ } else {+ if wt.locked.is_some() {+ let name = wt+ .branch+ .clone()+ .unwrap_or_else(|| wt.dir_name().to_string());+ return Err(GitError::WorktreeLocked {+ branch: name,+ path: wt.path.clone(),+ reason: wt.locked.clone(),+ }+ .into());+ }+ let is_current = wt.path == current_path;+ Resolved::Worktree {path: wt.path.clone(),- reason: wt.locked.clone(),+ branch: wt.branch.clone(),+ is_current,}- .into());- }- let is_current = wt.path == current_path;- Resolved::Worktree {- path: wt.path.clone(),- branch: wt.branch.clone(),- is_current,}}};@@ -247,7 +267,27 @@ impl RepositoryCliExt for Repository {// worktree-level checks. Branch-only removals have no pre-remove hook,// so their integration decision can be computed here.let (worktree_path, branch_name, is_current) = match resolved {- Resolved::BranchOnly { branch, pruned } => {+ Resolved::BranchOnly {+ pruned_from,+ branch,+ } => {+ // The missing-directory fallback reaches the same ref deletion a+ // worktree removal does, so it needs the same guard: a sibling+ // checkout whose directory is intact would be orphaned by it.+ let shared = pruned_from.as_deref().and_then(|target| {+ live_sibling_checkout(worktrees, &branch, target)+ .map(|sibling| SharedBranchCheckout::new(&sibling.path, &deletion_mode))+ });+ if let Some(shared) = shared {+ return Ok(RemoveResult::BranchOnly {+ branch_name: branch,+ deletion_mode: BranchDeletionMode::Keep,+ pruned: true,+ target_branch: None,+ integration_reason: None,+ branch_checked_out_at: Some(shared),+ });+ }let default_branch = self.default_branch();let target = default_branch.as_deref().or(Some("HEAD"));let (integration_reason, target_branch) = compute_integration_reason(@@ -260,9 +300,10 @@ impl RepositoryCliExt for Repository {return Ok(RemoveResult::BranchOnly {branch_name: branch,deletion_mode,- pruned,+ pruned: pruned_from.is_some(),target_branch,integration_reason,+ branch_checked_out_at: None,});}Resolved::Worktree {@@ -292,23 +333,40 @@ impl RepositoryCliExt for Repository {primary_path};+ let branch_checked_out_at = branch_name.as_deref().and_then(|branch| {+ live_sibling_checkout(worktrees, branch, &worktree_path)+ .map(|sibling| SharedBranchCheckout::new(&sibling.path, &deletion_mode))+ });+// Resolve target branch and integration verdict for display and// retention prediction. The actual branch deletion re-decides against// fresh refs (`delete_branch_if_safe`'s CAS), so this is display-only.- let default_branch = self.default_branch();- let target_branch = match (&default_branch, &branch_name) {- (Some(db), Some(bn)) if db == bn => None,- _ => default_branch,- };- let (integration_reason, target_branch) = match compute_integration_reason(- self,- snapshot,- branch_name.as_deref(),- target_branch.as_deref(),- deletion_mode,- ) {- (reason, Some(effective_target)) => (reason, Some(effective_target)),- (reason, None) => (reason, target_branch),+ //+ // A retained shared branch skips all of it: forcing `Keep` — the single+ // chokepoint every deletion path honors — settles the outcome, so an+ // integration verdict would only be computed to be ignored, and+ // reporting one alongside a branch that survives reads as a+ // contradiction.+ let (deletion_mode, target_branch, integration_reason) = if branch_checked_out_at.is_some()+ {+ (BranchDeletionMode::Keep, None, None)+ } else {+ let default_branch = self.default_branch();+ let target_branch = match (&default_branch, &branch_name) {+ (Some(db), Some(bn)) if db == bn => None,+ _ => default_branch,+ };+ let (integration_reason, target_branch) = match compute_integration_reason(+ self,+ snapshot,+ branch_name.as_deref(),+ target_branch.as_deref(),+ deletion_mode,+ ) {+ (reason, Some(effective_target)) => (reason, Some(effective_target)),+ (reason, None) => (reason, target_branch),+ };+ (deletion_mode, target_branch, integration_reason)};// Capture commit SHA before removal for post-remove hook template variables.@@ -332,6 +390,7 @@ impl RepositoryCliExt for Repository {integration_reason,force_worktree,removed_commit,+ branch_checked_out_at,})}@@ -512,6 +571,33 @@ pub(crate) fn compute_integration_reason(////// The default branch is the integration target — checking it against itself is/// tautological (same logic as `wt list`'s `is_main` guard in `check_integration_state`).+/// The worktree, other than the one being removed, whose checkout of `branch`+/// deleting the ref would orphan.+///+/// 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+/// 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 branch+/// asks this first.+///+/// Only a live directory counts. A sibling entry whose directory is already+/// gone is stale metadata awaiting `git worktree prune`, not a checkout with+/// anything to lose — retaining a branch for it would strand the branch and+/// point the user at a directory that isn't there.+pub(crate) fn live_sibling_checkout<'a>(+ worktrees: &'a [WorktreeInfo],+ branch: &str,+ removing: &Path,+) -> Option<&'a WorktreeInfo> {+ worktrees.iter().find(|wt| {+ wt.branch.as_deref() == Some(branch)+ && !worktrunk::path::paths_match(&wt.path, removing)+ && wt.path.exists()+ })+}+pub(crate) fn check_not_default_branch(repo: &Repository,branch: &str,diff --git a/src/commands/step/prune.rs b/src/commands/step/prune.rsindex 9e7272cdf..2d60129a1 100644--- a/src/commands/step/prune.rs+++ b/src/commands/step/prune.rs@@ -43,25 +43,27 @@ struct Candidate {}impl Candidate {+ /// Always the path, because the scan already identified the exact worktree:+ /// naming it by branch instead re-resolves to git's first-listed checkout,+ /// which for a branch checked out twice is a different worktree — and for a+ /// stale entry is the live one. `RemoveTarget::Path` degrades to branch-only+ /// deletion when the directory is already gone, so a stale entry still+ /// prunes.+ ///+ /// Only a candidate that arrives without a scan-time plan reaches this, and+ /// `check_one` plans everything except `Prunable`, which always carries the+ /// stale worktree's path.fn remove_target(&self) -> anyhow::Result<RemoveTarget<'_>> {match self.kind {CandidateKind::Current => Ok(RemoveTarget::Current),- CandidateKind::BranchOnly => Ok(RemoveTarget::Branch(- self.branch- .as_ref()- .context("BranchOnly candidate missing branch")?,- )),CandidateKind::StaleDetached => Err(anyhow::anyhow!("stale detached candidate has no remove target")),- CandidateKind::Other => match &self.branch {- Some(branch) => Ok(RemoveTarget::Branch(branch)),- None => Ok(RemoveTarget::Path(- self.path- .as_ref()- .context("detached candidate missing path")?,- )),- },+ CandidateKind::BranchOnly | CandidateKind::Other => Ok(RemoveTarget::Path(+ self.path+ .as_ref()+ .context("candidate has no worktree path")?,+ )),}}@@ -326,12 +328,11 @@ fn check_one(.ok(),CheckSource::Linked { wt_idx } => {let wt = &worktrees[*wt_idx];- let target = match &wt.branch {- Some(b) if !wt.detached => RemoveTarget::Branch(b),- _ => RemoveTarget::Path(&wt.path),- };repo.prepare_worktree_removal(- target,+ // The scan already knows which worktree this is; naming it by+ // branch would re-resolve to git's first-listed checkout, which+ // for a duplicated branch is a different worktree.+ RemoveTarget::Path(&wt.path),BranchDeletionMode::SafeDelete,false,None,@@ -400,10 +401,14 @@ fn candidate_fields(format!("(detached {short})")});match &wt.branch {+ // The stale entry's own path, so the removal targets it rather+ // than re-resolving the branch to whichever worktree git lists+ // first — which, for a branch this one duplicates, is a live+ // worktree the prune never selected.Some(branch) => (label,Some(branch.clone()),- None,+ Some(wt.path.clone()),CandidateKind::BranchOnly," (stale)",),diff --git a/src/commands/worktree/finish.rs b/src/commands/worktree/finish.rsindex 78acad5e2..065dd3fbd 100644--- a/src/commands/worktree/finish.rs+++ b/src/commands/worktree/finish.rs@@ -27,13 +27,14 @@ use worktrunk::config::UserConfig;use worktrunk::git::{BranchDeletionMode, Repository};use worktrunk::styling::{eprintln, info_message};-use super::types::RemoveResult;+use super::types::{RemoveResult, SharedBranchCheckout};use crate::commands::command_executor::CommandContext;use crate::commands::context::CommandEnv;use crate::commands::hook_plan::{ApprovedHookPlan, register_planned};use crate::commands::hooks::HookAnnouncer;use crate::commands::repository_ext::{check_not_default_branch, compute_integration_reason, is_primary_worktree,+ live_sibling_checkout,};use crate::commands::template_vars::TemplateVars;use crate::output::{@@ -131,26 +132,51 @@ pub fn finish_after_merge(let worktree_root = current_wt.root()?;+ // Merge reaches the same ref deletion `wt remove` does, so it asks the+ // same question: is this branch checked out anywhere else? Merging is+ // the likeliest way to meet a `--force` duplicate — the branch is+ // integrated, so nothing else would stop the delete, and deleting it+ // strands the duplicate at a null OID.+ let branch_checked_out_at =+ live_sibling_checkout(repo.list_worktrees()?, current_branch, &worktree_root).map(+ |sibling| SharedBranchCheckout::new(&sibling.path, &BranchDeletionMode::SafeDelete),+ );++ // A retained branch has no deletion to justify, so the integration+ // check is skipped rather than computed and discarded — same shape as+ // `prepare_worktree_removal`'s Phase 5.+ let (deletion_mode, display_target, integration_reason) = if branch_checked_out_at.is_some()+ {+ (BranchDeletionMode::Keep, None, None)+ } else {+ let (integration_reason, effective_target) = compute_integration_reason(+ repo,+ &repo.capture_refs()?,+ Some(current_branch),+ Some(target_branch),+ BranchDeletionMode::SafeDelete,+ );+ (+ BranchDeletionMode::SafeDelete,+ effective_target.or_else(|| Some(target_branch.to_string())),+ integration_reason,+ )+ };+// No config snapshot: `pre-remove` / `post-remove` were selected and// frozen into `plan` at the gate (anchored at `feature_path`), so the// executor needs no config — it runs only the frozen `plan`.- let (integration_reason, effective_target) = compute_integration_reason(- repo,- &repo.capture_refs()?,- Some(current_branch),- Some(target_branch),- BranchDeletionMode::SafeDelete,- );let remove_result = RemoveResult::RemovedWorktree {main_path: destination_path.clone(),worktree_path: worktree_root,changed_directory: true,branch_name: Some(current_branch.to_string()),- deletion_mode: BranchDeletionMode::SafeDelete,- target_branch: effective_target.or_else(|| Some(target_branch.to_string())),+ deletion_mode,+ target_branch: display_target,integration_reason,force_worktree: false,removed_commit: feature_commit.clone(),+ branch_checked_out_at,};handle_remove_output(&remove_result,diff --git a/src/commands/worktree/mod.rs b/src/commands/worktree/mod.rsindex e809013bb..9cae3c3ac 100644--- a/src/commands/worktree/mod.rs+++ b/src/commands/worktree/mod.rs@@ -94,4 +94,6 @@ pub use push::{PushKind, PushOutcome, PushResult, handle_no_ff_merge, handle_puspub use resolve::{compute_worktree_path, is_worktree_at_expected_path, worktree_display_name};pub(crate) use switch::SwitchPipeline;pub use switch::handle_switch_command;-pub use types::{MergeOperations, RemoveResult, SwitchBranchInfo, SwitchResult};+pub use types::{+ MergeOperations, RemoveResult, SharedBranchCheckout, SwitchBranchInfo, SwitchResult,+};diff --git a/src/commands/worktree/types.rs b/src/commands/worktree/types.rsindex 7ac638bc4..364d5a7b8 100644--- a/src/commands/worktree/types.rs+++ b/src/commands/worktree/types.rs@@ -143,6 +143,32 @@ impl SwitchPlan {}}+/// A surviving checkout of the branch a removal would otherwise have deleted.+///+/// Present only when the branch is checked out in more than one worktree, which+/// takes a deliberate `git worktree add --force`. Its presence is what retains+/// the branch: `deletion_mode` is forced to [`BranchDeletionMode::Keep`], since+/// deleting a ref another worktree still holds leaves that worktree at a null+/// OID with an unresolvable `HEAD`.+pub struct SharedBranchCheckout {+ /// The surviving worktree, named in the output so the retention reads as a+ /// consequence of something the user can see rather than a refusal.+ pub path: PathBuf,+ /// The removal asked to force-delete the branch (`-D`) and was refused.+ /// Everywhere else `-D` is the override that wins, so a `-D` that doesn't+ /// delete is unexpected and says so at warning volume.+ pub refused_force_delete: bool,+}++impl SharedBranchCheckout {+ pub fn new(path: &Path, requested: &BranchDeletionMode) -> Self {+ Self {+ path: path.to_path_buf(),+ refused_force_delete: requested.is_force(),+ }+ }+}+/// Result of a worktree remove operationpub enum RemoveResult {/// Removed worktree and changed directory (if needed)@@ -169,6 +195,10 @@ pub enum RemoveResult {/// Used for post-remove hook template variables so they reference the/// removed worktree's state, not the execution context.removed_commit: Option<String>,+ /// A surviving checkout of `branch_name`, when one exists. `Some`+ /// retains the branch and forces `deletion_mode` to `Keep`; see+ /// [`SharedBranchCheckout`].+ branch_checked_out_at: Option<SharedBranchCheckout>,},/// Branch exists but has no worktree - attempt branch deletion only.///@@ -187,6 +217,11 @@ pub enum RemoveResult {/// worktree-local `pre-remove` hook, so the integration decision can/// be made during preparation.integration_reason: Option<worktrunk::git::IntegrationReason>,+ /// A surviving checkout of `branch_name`, when one exists. Only reachable+ /// on a pruned removal — the target's directory was gone, but a sibling+ /// checkout of the same branch survives the fallback to branch-only+ /// deletion. See [`SharedBranchCheckout`].+ branch_checked_out_at: Option<SharedBranchCheckout>,},}@@ -234,23 +269,27 @@ impl RemoveResult {worktree_path,branch_name,deletion_mode,+ branch_checked_out_at,..} => serde_json::json!({"kind": "worktree","branch": branch_name,"path": worktree_path,"branch_deleted": !deletion_mode.should_keep(),+ "branch_checked_out_at": branch_checked_out_at.as_ref().map(|c| &c.path),}),RemoveResult::BranchOnly {branch_name,deletion_mode,pruned,+ branch_checked_out_at,..} => serde_json::json!({"kind": "branch_only","branch": branch_name,"pruned": pruned,"branch_deleted": !deletion_mode.should_keep(),+ "branch_checked_out_at": branch_checked_out_at.as_ref().map(|c| &c.path),}),}}@@ -280,6 +319,7 @@ mod tests {integration_reason: None,force_worktree: false,removed_commit: None,+ branch_checked_out_at: None,};assert_eq!(removed.branch_name(), Some("feature"));@@ -289,6 +329,7 @@ mod tests {pruned: false,target_branch: None,integration_reason: None,+ branch_checked_out_at: None,};assert_eq!(branch_only.branch_name(), Some("solo"));}@@ -342,6 +383,7 @@ mod tests {integration_reason: None,force_worktree: false,removed_commit: Some("abc1234567890".to_string()),+ branch_checked_out_at: None,};match result {RemoveResult::RemovedWorktree {@@ -354,6 +396,7 @@ mod tests {integration_reason: _,force_worktree,removed_commit,+ branch_checked_out_at,} => {assert_eq!(main_path.to_str().unwrap(), "/main");assert_eq!(worktree_path.to_str().unwrap(), "/worktree");@@ -364,6 +407,7 @@ mod tests {assert_eq!(target_branch.as_deref(), Some("main"));assert!(!force_worktree);assert_eq!(removed_commit.as_deref(), Some("abc1234567890"));+ assert!(branch_checked_out_at.is_none());}_ => panic!("Expected RemovedWorktree variant"),}@@ -377,6 +421,7 @@ mod tests {pruned: false,target_branch: None,integration_reason: None,+ branch_checked_out_at: None,};match result {RemoveResult::BranchOnly {@@ -385,6 +430,7 @@ mod tests {pruned,target_branch,integration_reason,+ branch_checked_out_at,} => {assert_eq!(branch_name, "stale-branch");assert!(deletion_mode.should_keep());@@ -392,6 +438,7 @@ mod tests {assert!(!pruned);assert!(target_branch.is_none());assert!(integration_reason.is_none());+ assert!(branch_checked_out_at.is_none());}_ => panic!("Expected BranchOnly variant"),}@@ -405,6 +452,7 @@ mod tests {pruned: true,target_branch: Some("main".to_string()),integration_reason: None,+ branch_checked_out_at: None,};match result {RemoveResult::BranchOnly {@@ -413,12 +461,14 @@ mod tests {pruned,target_branch,integration_reason,+ branch_checked_out_at,} => {assert_eq!(branch_name, "pruned-branch");assert!(!deletion_mode.should_keep());assert!(pruned);assert_eq!(target_branch.as_deref(), Some("main"));assert!(integration_reason.is_none());+ assert!(branch_checked_out_at.is_none());}_ => panic!("Expected BranchOnly variant"),}@@ -436,6 +486,7 @@ mod tests {integration_reason: None,force_worktree: true,removed_commit: None, // Detached HEAD may not have meaningful commit+ branch_checked_out_at: None,};match result {RemoveResult::RemovedWorktree {diff --git a/src/git/repository/worktrees.rs b/src/git/repository/worktrees.rsindex 69dac9cf3..9bb501a31 100644--- a/src/git/repository/worktrees.rs+++ b/src/git/repository/worktrees.rs@@ -9,7 +9,9 @@ use dunce::canonicalize;use super::{GitError, Repository, ResolvedWorktree, WorktreeInfo, resolve_input_path};use crate::path::{format_path_for_display, paths_match};-use crate::styling::{eprintln, format_with_gutter, hint_message, warning_message};+use crate::styling::{+ eprintln, format_with_gutter, hint_message, suggest_command, warning_message,+};impl Repository {/// List all worktrees for this repository.@@ -419,8 +421,8 @@ pub fn duplicated_branches(worktrees: &[WorktreeInfo]) -> HashSet<&str> {/// Warn once per process that `branch` resolves ambiguously across worktrees.////// Worktrunk addresses worktrees by branch name and resolves an ambiguous-/// branch to the first worktree git lists, leaving the others unreachable by-/// name. The warning surfaces that otherwise-silent choice — naming every+/// branch to the first worktree git lists, leaving the others reachable only by+/// path. The warning surfaces that otherwise-silent choice — naming every/// path — without changing which worktree is used. Deduplicated per branch so/// a command that resolves the same branch repeatedly (the picker, `wt list`)/// warns only once.@@ -449,14 +451,14 @@ fn warn_duplicate_checkout(branch: &str, paths: &[PathBuf]) {);eprintln!("{}", format_with_gutter(&listing, None));// Name every shadowed worktree so removing them all is actionable; with a- // single extra (the common case) this is one hint.+ // single extra (the common case) this is one hint. `wt remove <path>`+ // removes exactly the worktree named and retains the branch the others+ // still hold, so it's safe to suggest for a duplicate.for extra in &paths[1..] {+ let cmd = suggest_command("remove", &[&format_path_for_display(extra)], &[]);eprintln!("{}",- hint_message(cformat!(- "To drop a duplicate, run <underline>git worktree remove {}</>",- format_path_for_display(extra)- ))+ hint_message(cformat!("To drop a duplicate, run <underline>{cmd}</>")));}}diff --git a/src/output/handlers.rs b/src/output/handlers.rsindex 0ad9106c7..d069f5a0d 100644--- a/src/output/handlers.rs+++ b/src/output/handlers.rs@@ -17,7 +17,9 @@ use crate::commands::process::{HookLog, InternalOp, build_remove_command, build_remove_command_staged, spawn_detached,};use crate::commands::worktree::hooks::PostRemoveContext;-use crate::commands::worktree::{RemoveResult, SwitchBranchInfo, SwitchResult};+use crate::commands::worktree::{+ RemoveResult, SharedBranchCheckout, SwitchBranchInfo, SwitchResult,+};use worktrunk::config::UserConfig;use worktrunk::git::ErrorExt;use worktrunk::git::GitError;@@ -638,6 +640,32 @@ fn print_retained_unmerged_branch(branch_name: &str) {eprintln!("{hint}");}+/// Explain that the branch was kept because another worktree still has it+/// checked out. Removing this worktree can't free a ref that's live elsewhere,+/// so the branch is retained and the surviving checkout is named — the state is+/// only reachable through `git worktree add --force`, so the user may not+/// remember creating it.+///+/// Info by default: nothing went wrong, and this reads as a sibling of+/// [`retained_unmerged_branch_messages`], the other "kept the branch, here's+/// why" line. A refused `-D` is different — `-D` overrides every other+/// retention wt has, so one that doesn't delete is unexpected and warns.+fn print_branch_checked_out_elsewhere(branch_name: &str, shared: &SharedBranchCheckout) {+ let path = format_path_for_display(&shared.path);+ let message = if shared.refused_force_delete {+ warning_message(cformat!(+ "Branch <bold>{branch_name}</> retained despite <bold>-D</>; still checked out @ <bold>{path}</>"+ ))+ .to_string()+ } else {+ info_message(cformat!(+ "Branch <bold>{branch_name}</> retained; still checked out @ <bold>{path}</>"+ ))+ .to_string()+ };+ eprintln!("{message}");+}+/// The canonical "branch retained because the atomic CAS delete was refused"/// warning. The ref moved between the integration check and the delete (a hook/// commit, a concurrent push), so the integrated branch is kept fail-closed@@ -1018,6 +1046,7 @@ pub fn handle_remove_output(integration_reason,force_worktree,removed_commit,+ branch_checked_out_at,} => handle_removed_worktree_output(RemovedWorktreeOutputContext {main_path,@@ -1029,6 +1058,7 @@ pub fn handle_remove_output(integration_reason: *integration_reason,force_worktree: *force_worktree,removed_commit: removed_commit.as_deref(),+ branch_checked_out_at: branch_checked_out_at.as_ref(),plan,foreground,silent,@@ -1042,12 +1072,14 @@ pub fn handle_remove_output(pruned,target_branch,integration_reason,+ branch_checked_out_at,} => handle_branch_only_output(branch_name,*deletion_mode,*pruned,*integration_reason,target_branch.as_deref(),+ branch_checked_out_at.as_ref(),quiet,),}@@ -1063,6 +1095,7 @@ fn handle_branch_only_output(pruned: bool,integration_reason: Option<IntegrationReason>,target_branch: Option<&str>,+ branch_checked_out_at: Option<&SharedBranchCheckout>,quiet: bool,) -> anyhow::Result<()> {let branch_info = if pruned {@@ -1074,6 +1107,11 @@ fn handle_branch_only_output(// If we won't delete the branch, show info and return earlyif deletion_mode.should_keep() {eprintln!("{}", info_message(&branch_info));+ // A sibling `--force` checkout kept the branch alive; name it so the+ // user knows why the pruned branch survived rather than being deleted.+ if let Some(shared) = branch_checked_out_at {+ print_branch_checked_out_elsewhere(branch_name, shared);+ }stderr().flush()?;return Ok(());}@@ -1478,6 +1516,9 @@ struct RemovedWorktreeOutputContext<'a> {integration_reason: Option<IntegrationReason>,force_worktree: bool,removed_commit: Option<&'a str>,+ /// A surviving checkout of this branch, when one exists. `Some` means the+ /// branch was retained rather than deleted; see [`SharedBranchCheckout`].+ branch_checked_out_at: Option<&'a SharedBranchCheckout>,/// The frozen, approved hook plan. `pre-remove` / `post-remove` //// `post-switch` execute only from this — no `.config/wt.toml` re-read,/// no `ProjectConfig` snapshot to thread.@@ -1687,6 +1728,9 @@ fn handle_named_removed_worktree_foreground(display_info.print_message(branch_name, true, Some(stats))?;display_info.print_hints(branch_name, ctx.deletion_mode, ctx.integration_reason)?;+ if let Some(shared) = ctx.branch_checked_out_at {+ print_branch_checked_out_elsewhere(branch_name, shared);+ }print_switch_message_if_changed(ctx.changed_directory, ctx.main_path)?;spawn_hooks_after_remove(repo, ctx, branch_name, announcer)?;@@ -1709,6 +1753,9 @@ fn handle_named_removed_worktree_background(display_info.print_message(branch_name, false, None)?;display_info.print_hints(branch_name, ctx.deletion_mode, ctx.integration_reason)?;+ if let Some(shared) = ctx.branch_checked_out_at {+ print_branch_checked_out_elsewhere(branch_name, shared);+ }print_switch_message_if_changed(ctx.changed_directory, ctx.main_path)?;// Planner predicted retention when the user asked to keep, or when thediff --git a/tests/integration_tests/merge.rs b/tests/integration_tests/merge.rsindex f65a949e8..5f3b4c888 100644--- a/tests/integration_tests/merge.rs+++ b/tests/integration_tests/merge.rs@@ -5109,3 +5109,64 @@ fn test_post_merge_hook_from_rebased_in_config_does_not_run(merge_scenario: (Tesrebase must not run — it was never in the frozen plan");}++/// `wt merge` reaches the same branch deletion `wt remove` does, so it needs the+/// same shared-branch guard.+///+/// This is the likeliest way to meet a `--force` duplicate: the branch has just+/// been merged, so it's integrated and nothing else would decline the delete —+/// and deleting it strands the duplicate at a null OID with an unresolvable+/// `HEAD`. A branch reaches two worktrees only through `git worktree add+/// --force`, which worktrunk never runs itself.+#[rstest]+fn test_merge_retains_branch_checked_out_in_another_worktree(mut repo: TestRepo) {+ let feature_wt = repo.add_feature();++ let dup = repo.root_path().parent().unwrap().join("repo.feature-dup");+ repo.run_git(&[+ "worktree",+ "add",+ "--force",+ dup.to_str().unwrap(),+ "feature",+ ]);++ let output = repo+ .wt_command()+ .args(["merge", "main", "--yes", "--no-hooks"])+ .current_dir(&feature_wt)+ .output()+ .unwrap();+ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(output.status.success(), "merge should succeed:\n{stderr}");++ wait_for_worktree_removed(&feature_wt);++ let branch_exists = repo+ .git_command()+ .args(["show-ref", "--verify", "--quiet", "refs/heads/feature"])+ .run()+ .unwrap()+ .status+ .success();+ assert!(+ branch_exists,+ "branch must be retained while the duplicate still has it checked out:\n{stderr}",+ );++ assert!(+ repo.git_command()+ .args(["rev-parse", "--verify", "HEAD"])+ .current_dir(&dup)+ .run()+ .unwrap()+ .status+ .success(),+ "the duplicate must resolve HEAD to a commit, not a deleted branch:\n{stderr}",+ );++ assert!(+ stderr.contains("retained") && stderr.contains("still checked out"),+ "output should explain the branch was retained:\n{stderr}",+ );+}diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rsindex 90720a98a..a043f62d7 100644--- a/tests/integration_tests/remove.rs+++ b/tests/integration_tests/remove.rs@@ -3946,3 +3946,184 @@ fn test_remove_merged_locally_when_upstream_diverged(#[from(repo_with_remote)] r"feature branch should be deleted after detection via local main");}++// ============================================================================+// Shared-branch retention+//+// A branch reaches two worktrees only through `git worktree add --force`, which+// worktrunk never runs itself. Once it has, deleting the ref orphans whichever+// checkout wt didn't remove: `git update-ref -d` is a compare-and-swap on the+// ref alone and, unlike `git branch -d`, doesn't refuse a ref that's checked+// out. The survivor is left at a null OID with an unresolvable `HEAD`, so every+// test here asserts on the survivor's `HEAD`, not just on the branch.+// ============================================================================++/// Check out `branch` a second time at `<repo>.<suffix>`, the state only+/// `--force` can produce.+fn add_force_duplicate(repo: &TestRepo, branch: &str, suffix: &str) -> std::path::PathBuf {+ let dup = repo+ .root_path()+ .parent()+ .unwrap()+ .join(format!("repo.{suffix}"));+ repo.run_git(&["worktree", "add", "--force", dup.to_str().unwrap(), branch]);+ dup+}++/// Assert `worktree` still resolves `HEAD` to a commit — the corruption a+/// deleted-but-checked-out branch leaves behind.+#[track_caller]+fn assert_not_orphaned(repo: &TestRepo, worktree: &std::path::Path, context: &str) {+ let head = repo+ .git_command()+ .args(["rev-parse", "--verify", "HEAD"])+ .current_dir(worktree)+ .run()+ .unwrap();+ assert!(+ head.status.success(),+ "surviving worktree must resolve HEAD to a commit, not a deleted branch\n{context}",+ );+}++#[track_caller]+fn assert_branch_exists(repo: &TestRepo, branch: &str, expected: bool, context: &str) {+ let found = repo+ .git_command()+ .args([+ "show-ref",+ "--verify",+ "--quiet",+ &format!("refs/heads/{branch}"),+ ])+ .run()+ .unwrap()+ .status+ .success();+ assert_eq!(found, expected, "branch {branch} presence\n{context}");+}++/// Run `wt remove` with `args`, returning ANSI-stripped stderr.+fn run_remove(repo: &TestRepo, args: &[&str]) -> String {+ let output = repo.wt_command().arg("remove").args(args).output().unwrap();+ let stderr = String::from_utf8_lossy(&output.stderr)+ .ansi_strip()+ .into_owned();+ assert!(+ output.status.success(),+ "wt remove {args:?} should succeed\nstderr:\n{stderr}",+ );+ stderr+}++/// Naming a duplicate by its path removes exactly that worktree — resolving the+/// path back to a branch would target git's first-listed checkout instead — and+/// retains the branch the survivor still holds.+#[rstest]+fn test_remove_duplicate_checkout_by_path_retains_survivor(mut repo: TestRepo) {+ use crate::common::wait_for_worktree_removed;++ let survivor = repo.add_worktree("feature");+ let dup = add_force_duplicate(&repo, "feature", "feature-dup");++ let stderr = run_remove(&repo, &[dup.to_str().unwrap()]);++ wait_for_worktree_removed(&dup);+ assert!(+ survivor.exists(),+ "only the named worktree should be removed\nstderr:\n{stderr}",+ );+ assert_branch_exists(&repo, "feature", true, &stderr);+ assert_not_orphaned(&repo, &survivor, &stderr);+ assert!(+ stderr.contains("retained") && stderr.contains("still checked out"),+ "output should explain the branch was retained\nstderr:\n{stderr}",+ );+}++/// Removing a duplicated branch *by name* resolves to git's first-listed+/// worktree and removes that one, still retaining the shared branch rather than+/// orphaning the other checkout.+#[rstest]+fn test_remove_duplicate_checkout_by_name_retains_branch(mut repo: TestRepo) {+ use crate::common::wait_for_worktree_removed;++ let first = repo.add_worktree("feature");+ let dup = add_force_duplicate(&repo, "feature", "feature-dup");++ let stderr = run_remove(&repo, &["feature"]);++ wait_for_worktree_removed(&first);+ assert_branch_exists(&repo, "feature", true, &stderr);+ assert_not_orphaned(&repo, &dup, &stderr);+}++/// `-D` overrides every other retention wt has, but it can't override this one:+/// the ref is live in another worktree, so honoring it would corrupt that+/// worktree. The refusal warns rather than passing silently.+///+/// `--foreground` so the retention is also exercised on the synchronous+/// removal path; the other tests here take the background one.+#[rstest]+fn test_remove_force_delete_refused_while_branch_is_shared(mut repo: TestRepo) {+ let survivor = repo.add_worktree("feature");+ let dup = add_force_duplicate(&repo, "feature", "feature-dup");++ let stderr = run_remove(&repo, &[dup.to_str().unwrap(), "-D", "--foreground"]);++ assert!(+ !dup.exists(),+ "foreground removal should finish before returning\nstderr:\n{stderr}",+ );+ assert_branch_exists(&repo, "feature", true, &stderr);+ assert_not_orphaned(&repo, &survivor, &stderr);+ assert!(+ stderr.contains("retained despite -D"),+ "a refused -D must say so, not retain silently\nstderr:\n{stderr}",+ );+}++/// The missing-directory fallback reaches the same ref deletion, so it needs the+/// same guard: the target's own entry is stale, but the sibling's checkout is+/// live and would be orphaned.+#[rstest]+fn test_remove_pruned_dir_with_sibling_checkout_retains_branch(mut repo: TestRepo) {+ // `feature` has no commits beyond main, so it's integrated and would be+ // deleted by the branch-only fallback absent the sibling guard.+ let survivor = repo.add_worktree("feature");+ let dup = add_force_duplicate(&repo, "feature", "feature-dup");+ std::fs::remove_dir_all(&dup).unwrap();++ let stderr = run_remove(&repo, &[dup.to_str().unwrap()]);++ assert_branch_exists(&repo, "feature", true, &stderr);+ assert_not_orphaned(&repo, &survivor, &stderr);+ assert!(+ stderr.contains("pruned")+ && stderr.contains("retained")+ && stderr.contains("still checked out"),+ "output should report the prune and explain the branch was retained\nstderr:\n{stderr}",+ );+}++/// The mirror image: a *stale* duplicate entry alongside one live checkout. The+/// live checkout is the one being removed, so nothing survives to be orphaned+/// and the branch is deleted as usual. Retaining here would strand the branch+/// and name a directory that no longer exists.+#[rstest]+fn test_remove_last_live_checkout_deletes_branch(mut repo: TestRepo) {+ use crate::common::wait_for_worktree_removed;++ let live = repo.add_worktree("feature");+ let stale = add_force_duplicate(&repo, "feature", "feature-dup");+ std::fs::remove_dir_all(&stale).unwrap();++ let stderr = run_remove(&repo, &[live.to_str().unwrap()]);++ wait_for_worktree_removed(&live);+ assert_branch_exists(&repo, "feature", false, &stderr);+ assert!(+ !stderr.contains("still checked out"),+ "a stale entry is not a checkout to retain the branch for\nstderr:\n{stderr}",+ );+}diff --git a/tests/integration_tests/step_prune.rs b/tests/integration_tests/step_prune.rsindex 774053472..c70b828e5 100644--- a/tests/integration_tests/step_prune.rs+++ b/tests/integration_tests/step_prune.rs@@ -1579,3 +1579,63 @@ exec {real_git} "$@"permissions.set_mode(0o755);std::fs::set_permissions(&path, permissions).unwrap();}++/// `wt step prune` sweeps stale worktrees unattended, so it's the worst place to+/// delete a branch another worktree still has checked out — the user isn't+/// watching, and the survivor is left at a null OID with an unresolvable `HEAD`.+/// It shares `prepare_worktree_removal` with `wt remove`, and this pins that it+/// keeps sharing the guard.+#[rstest]+fn test_prune_retains_branch_checked_out_in_another_worktree(mut repo: TestRepo) {+ let survivor = repo.add_worktree("feature");++ // A `--force` duplicate whose directory then disappears out-of-band: prune+ // finds a stale entry whose branch is still live in `survivor`.+ let dup = repo.root_path().parent().unwrap().join("repo.feature-dup");+ repo.run_git(&[+ "worktree",+ "add",+ "--force",+ dup.to_str().unwrap(),+ "feature",+ ]);+ std::fs::remove_dir_all(&dup).unwrap();++ // Default `min-age`, deliberately: it holds `survivor` back as too young+ // while the stale entry is pruned regardless of age. That asymmetry is what+ // leaves a live checkout standing when the branch deletion runs — with+ // `--min-age=0s` prune would remove both worktrees, and the branch would be+ // free to delete by the time it did.+ let output = repo+ .wt_command()+ .args(["step", "prune", "--yes"])+ .output()+ .unwrap();+ let stderr = String::from_utf8_lossy(&output.stderr)+ .ansi_strip()+ .into_owned();+ assert!(output.status.success(), "prune should succeed:\n{stderr}");++ let branch_exists = repo+ .git_command()+ .args(["show-ref", "--verify", "--quiet", "refs/heads/feature"])+ .run()+ .unwrap()+ .status+ .success();+ assert!(+ branch_exists,+ "prune must retain a branch another worktree still has checked out:\n{stderr}",+ );++ assert!(+ repo.git_command()+ .args(["rev-parse", "--verify", "HEAD"])+ .current_dir(&survivor)+ .run()+ .unwrap()+ .status+ .success(),+ "survivor must resolve HEAD to a commit, not a deleted branch:\n{stderr}",+ );+}diff --git a/tests/snapshots/integration__integration_tests__help__help_remove_long.snap b/tests/snapshots/integration__integration_tests__help__help_remove_long.snapindex 37b3200d1..9b225e1fa 100644--- a/tests/snapshots/integration__integration_tests__help__help_remove_long.snap+++ b/tests/snapshots/integration__integration_tests__help__help_remove_long.snap@@ -8,6 +8,7 @@ info:env:CLICOLOR_FORCE: "1"COLUMNS: "500"+ GIT_ALLOW_PROTOCOL: fileLANG: CLC_ALL: CLLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"@@ -24,6 +25,7 @@ info:WORKTRUNK_TEST_GEMINI_INSTALLED: "0"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_SKIP_URL_HEALTH_CHECK: "1"@@ -136,6 +138,8 @@ The 'same commit' check uses the local default branch; for other checks, 'targetBranches matching these conditions and with empty working trees are dimmed in [2mwt list[0m as safe to delete.+Those six ask whether deleting loses work. A branch checked out in a second worktree (only reachable via [2mgit worktree add --force[0m) fails a different test: deleting the ref would leave that worktree unable to resolve [2mHEAD[0m, which is why [2mgit branch -d[0m refuses the same delete. Such a branch is retained whatever [2m-D[0m asks, and the surviving checkout is named.+[1m[32mForce flags[0mWorktrunk has two force flags for different situations:diff --git a/tests/snapshots/integration__integration_tests__remove__remove_json.snap b/tests/snapshots/integration__integration_tests__remove__remove_json.snapindex 81c368f38..ebbc67627 100644--- a/tests/snapshots/integration__integration_tests__remove__remove_json.snap+++ b/tests/snapshots/integration__integration_tests__remove__remove_json.snap@@ -5,6 +5,7 @@ expression: "String::from_utf8_lossy(&output.stdout)"[{"branch": "feature",+ "branch_checked_out_at": null,"branch_deleted": true,"kind": "worktree","path": "<PATH>"diff --git a/tests/snapshots/integration__integration_tests__remove__remove_json_branch_only.snap b/tests/snapshots/integration__integration_tests__remove__remove_json_branch_only.snapindex 8ea119c22..717bb8fad 100644--- a/tests/snapshots/integration__integration_tests__remove__remove_json_branch_only.snap+++ b/tests/snapshots/integration__integration_tests__remove__remove_json_branch_only.snap@@ -5,6 +5,7 @@ expression: "String::from_utf8_lossy(&output.stdout)"[{"branch": "orphan-branch",+ "branch_checked_out_at": null,"branch_deleted": true,"kind": "branch_only","pruned": falsediff --git a/tests/snapshots/integration__integration_tests__remove__remove_json_current.snap b/tests/snapshots/integration__integration_tests__remove__remove_json_current.snapindex 81c368f38..ebbc67627 100644--- a/tests/snapshots/integration__integration_tests__remove__remove_json_current.snap+++ b/tests/snapshots/integration__integration_tests__remove__remove_json_current.snap@@ -5,6 +5,7 @@ expression: "String::from_utf8_lossy(&output.stdout)"[{"branch": "feature",+ "branch_checked_out_at": null,"branch_deleted": true,"kind": "worktree","path": "<PATH>"diff --git a/tests/snapshots/integration__integration_tests__remove__remove_json_multi_with_branch_only.snap b/tests/snapshots/integration__integration_tests__remove__remove_json_multi_with_branch_only.snapindex c22361d66..990c6b4e7 100644--- a/tests/snapshots/integration__integration_tests__remove__remove_json_multi_with_branch_only.snap+++ b/tests/snapshots/integration__integration_tests__remove__remove_json_multi_with_branch_only.snap@@ -5,12 +5,14 @@ expression: "String::from_utf8_lossy(&output.stdout)"[{"branch": "wt-feature",+ "branch_checked_out_at": null,"branch_deleted": true,"kind": "worktree","path": "<PATH>"},{"branch": "orphan-branch",+ "branch_checked_out_at": null,"branch_deleted": true,"kind": "branch_only","pruned": falsediff --git a/tests/snapshots/integration__integration_tests__step_diff__step_diff_duplicate_branch_warns.snap b/tests/snapshots/integration__integration_tests__step_diff__step_diff_duplicate_branch_warns.snapindex be36a20ba..e96c9861e 100644--- a/tests/snapshots/integration__integration_tests__step_diff__step_diff_duplicate_branch_warns.snap+++ b/tests/snapshots/integration__integration_tests__step_diff__step_diff_duplicate_branch_warns.snap@@ -11,6 +11,7 @@ info:CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"CLICOLOR_FORCE: "1"COLUMNS: "500"+ GIT_ALLOW_PROTOCOL: fileGIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"@@ -52,4 +53,4 @@ exit_code: 0[33m▲[39m [33mBranch [1mfeature[22m is checked out in 2 worktrees; wt uses the first:[39m[107m [0m _REPO_.feature[107m [0m _REPO_.feature-dup-[2m↳[22m [2mTo drop a duplicate, run [4mgit worktree remove _REPO_.feature-dup[24m[22m+[2m↳[22m [2mTo drop a duplicate, run [4mwt remove _REPO_.feature-dup[24m[22m