Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix: picker alt-r removal — validate before removing, use fast path (#1702)
Maximilian Roosf354c788f679
diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rsindex be5992511..28debd19c 100644--- a/src/commands/picker/mod.rs+++ b/src/commands/picker/mod.rs@@ -23,6 +23,7 @@ use skim::prelude::*;use skim::reader::CommandCollector;use worktrunk::git::{Repository, current_or_recover};+use super::branch_deletion::delete_branch_if_safe;use super::handle_switch::{approve_switch_hooks, run_pre_switch_hooks, spawn_switch_background_hooks, switch_extra_vars,};@@ -65,33 +66,48 @@ struct PickerCollector {}impl PickerCollector {- /// Execute worktree removal silently: stop fsmonitor, remove worktree, delete branch.+ /// Execute removal silently: worktree + branch, or branch-only.///- /// No output, no hooks, no cd directives — we're inside skim's TUI.- fn do_removal(result: &RemoveResult) -> anyhow::Result<()> {- let RemoveResult::RemovedWorktree {- main_path,- worktree_path,- branch_name,- deletion_mode,- target_branch,- force_worktree,- ..- } = result- else {- return Ok(());- };-- let repo = Repository::at(main_path)?;- // Branch deletion result intentionally ignored — best-effort in TUI context.- execute_removal(- &repo,- worktree_path,- branch_name.as_deref(),- *deletion_mode,- target_branch.as_deref(),- *force_worktree,- )?;+ /// `repo` is only used for `BranchOnly` deletion. `RemovedWorktree` constructs+ /// its own from `main_path` (which may differ from the picker's startup repo in+ /// bare-repo setups).+ fn do_removal(repo: &Repository, result: &RemoveResult) -> anyhow::Result<()> {+ match result {+ RemoveResult::RemovedWorktree {+ main_path,+ worktree_path,+ branch_name,+ deletion_mode,+ target_branch,+ force_worktree,+ ..+ } => {+ let repo = Repository::at(main_path)?;+ let output = execute_removal(+ &repo,+ worktree_path,+ branch_name.as_deref(),+ *deletion_mode,+ target_branch.as_deref(),+ *force_worktree,+ )?;+ if let Some(staged) = output.staged_path {+ let _ = std::fs::remove_dir_all(&staged);+ }+ }+ RemoveResult::BranchOnly {+ branch_name,+ deletion_mode,+ ..+ } => {+ if !deletion_mode.should_keep() {+ let default_branch = repo.default_branch();+ let target = default_branch.as_deref().unwrap_or("HEAD");+ let _ =+ delete_branch_if_safe(repo, branch_name, target, deletion_mode.is_force());+ }+ }+ }Ok(())}}@@ -106,81 +122,62 @@ impl CommandCollector for PickerCollector {if let Ok(signal) = std::fs::read_to_string(&self.signal_path) {let selected_output = signal.trim().to_string();if !selected_output.is_empty() {- // Look up worktree data from the item list. For detached worktrees,- // we need the path since they have no unique branch name.- let worktree_info = {- let items = self.items.lock().unwrap();- items- .iter()- .find(|item| item.output().as_ref() == selected_output)- .and_then(|item| item.as_any().downcast_ref::<WorktreeSkimItem>())- .and_then(|skim_item| skim_item.item.worktree_data())- .map(|data| (data.path.clone(), data.detached))- };-- let detached_path = worktree_info- .as_ref()- .filter(|(_, d)| *d)- .map(|(p, _)| p.clone());-- // Remove item from the list immediately so the TUI updates fast.- // Git operations run in the background after we return.- {- let mut items = self.items.lock().unwrap();- if let Some(path) = &detached_path {- // Detached items all share output "(detached)" —- // match by worktree path to remove only this one.- items.retain(|item| {- item.as_any()- .downcast_ref::<WorktreeSkimItem>()- .and_then(|s| s.item.worktree_data())- .is_none_or(|d| d.path != *path)- });- } else {- items.retain(|item| item.output().as_ref() != selected_output);- }- }+ // Validate removal before touching the list. prepare_worktree_removal+ // runs a few git commands (~15-20ms) — acceptable on skim's event loop.+ // Only remove the item and spawn background deletion if this succeeds.+ let caller_path = self.repo.current_worktree().root().ok();+ let config = self.repo.user_config();+ let preparation = self.repo.prepare_worktree_removal(+ RemoveTarget::Branch(&selected_output),+ BranchDeletionMode::SafeDelete,+ false,+ config,+ caller_path,+ );++ match preparation {+ Ok(result) => {+ // Removal validated — remove item from the picker list.+ //+ // Note: skim's `as_any().downcast_ref::<WorktreeSkimItem>()` fails+ // at runtime (TypeId mismatch between reader thread and main thread+ // compilation units in skim 0.20). All item lookups use output()+ // matching instead.+ {+ let mut items = self.items.lock().unwrap();+ items.retain(|item| item.output().as_ref() != selected_output);+ }- // If removing the current worktree, update process CWD so skim- // and git commands continue to work. Use starts_with to handle- // CWD being a subdirectory of the worktree root.- if let Some((path, _)) = &worktree_info- && let (Some(current), Some(canon_path)) =- (std::env::current_dir().ok(), dunce::canonicalize(path).ok())- && current.starts_with(&canon_path)- && let Ok(home) = self.repo.home_path()- {- let _ = std::env::set_current_dir(&home);- }+ // If removing the current worktree, cd to home so skim and git+ // commands continue to work after the directory disappears.+ if matches!(+ &result,+ RemoveResult::RemovedWorktree {+ changed_directory: true,+ ..+ }+ ) && let Ok(home) = self.repo.home_path()+ {+ let _ = std::env::set_current_dir(&home);+ }- // Defer git operations to a background thread so skim's event- // loop stays responsive. invoke() is called on skim's main- // thread — blocking it freezes the TUI.- let repo = self.repo.clone();- let _ = std::thread::Builder::new()- .name(format!("picker-remove-{selected_output}"))- .spawn(move || {- let config = repo.user_config();- let target = if let Some(path) = &detached_path {- RemoveTarget::Path(path)- } else {- RemoveTarget::Branch(&selected_output)- };- let removal = repo- .prepare_worktree_removal(- target,- BranchDeletionMode::SafeDelete,- false,- config,- )- .and_then(|result| {- Self::do_removal(&result)?;- Ok(result)+ // Defer actual git removal to a background thread so skim's+ // event loop stays responsive.+ let repo = self.repo.clone();+ let _ = std::thread::Builder::new()+ .name(format!("picker-remove-{selected_output}"))+ .spawn(move || {+ if let Err(e) = Self::do_removal(&repo, &result) {+ log::warn!(+ "picker: failed to remove '{selected_output}': {e:#}"+ );+ }});- if let Err(e) = removal {- log::warn!("picker: failed to remove '{selected_output}': {e:#}");- }- });+ }+ Err(e) => {+ log::info!("picker: cannot remove '{selected_output}': {e:#}");+ }+ }// Clear signal for next removallet _ = std::fs::write(&self.signal_path, "");@@ -645,8 +642,40 @@ pub mod tests {use super::{PickerAction, PickerCollector, resolve_identifier};use crate::commands::worktree::{BranchDeletionMode, RemoveResult};use std::fs;+ use std::path::PathBuf;use worktrunk::shell_exec::Cmd;+ /// Create a git repo with one commit at `tmp/repo` and return the path.+ fn init_test_repo(tmp: &tempfile::TempDir) -> PathBuf {+ let repo_path = tmp.path().join("repo");+ Cmd::new("git")+ .args(["init", "--initial-branch=main", repo_path.to_str().unwrap()])+ .run()+ .unwrap();+ Cmd::new("git")+ .args(["config", "user.email", "[email protected]"])+ .current_dir(&repo_path)+ .run()+ .unwrap();+ Cmd::new("git")+ .args(["config", "user.name", "Test"])+ .current_dir(&repo_path)+ .run()+ .unwrap();+ fs::write(repo_path.join("file.txt"), "hello").unwrap();+ Cmd::new("git")+ .args(["add", "."])+ .current_dir(&repo_path)+ .run()+ .unwrap();+ Cmd::new("git")+ .args(["commit", "-m", "init"])+ .current_dir(&repo_path)+ .run()+ .unwrap();+ repo_path+ }+#[test]fn test_preview_state_data_roundtrip() {let state_path = PreviewStateData::state_path();@@ -719,39 +748,22 @@ pub mod tests {#[test]fn test_execute_removal_removes_worktree_and_branch() {let tmp = tempfile::TempDir::new().unwrap();- let repo_path = tmp.path().join("repo");+ let repo_path = init_test_repo(&tmp);+ let repo = worktrunk::git::Repository::at(&repo_path).unwrap();let wt_path = tmp.path().join("repo.feature");- Cmd::new("git")- .args(["init", "--initial-branch=main", repo_path.to_str().unwrap()])- .run()- .unwrap();- fs::write(repo_path.join("file.txt"), "hello").unwrap();- Cmd::new("git")- .args(["add", "."])- .current_dir(&repo_path)- .run()- .unwrap();- Cmd::new("git")- .args(["commit", "-m", "init"])- .current_dir(&repo_path)- .run()- .unwrap();- Cmd::new("git")- .args([- "worktree",- "add",- "-b",- "feature",- wt_path.to_str().unwrap(),- ])- .current_dir(&repo_path)- .run()- .unwrap();+ repo.run_command(&[+ "worktree",+ "add",+ "-b",+ "feature",+ wt_path.to_str().unwrap(),+ ])+ .unwrap();assert!(wt_path.exists());let result = RemoveResult::RemovedWorktree {- main_path: repo_path.clone(),+ main_path: repo_path,worktree_path: wt_path.clone(),changed_directory: false,branch_name: Some("feature".to_string()),@@ -763,24 +775,65 @@ pub mod tests {removed_commit: None,};- PickerCollector::do_removal(&result).unwrap();+ PickerCollector::do_removal(&repo, &result).unwrap();assert!(!wt_path.exists(), "worktree should be removed");- let output = Cmd::new("git")- .args(["branch", "--list", "feature"])- .current_dir(&repo_path)- .run()- .unwrap();- assert!(output.stdout.is_empty(), "branch should be deleted");+ let output = repo.run_command(&["branch", "--list", "feature"]).unwrap();+ assert!(output.is_empty(), "branch should be deleted");}#[test]- fn test_execute_removal_branch_only_is_noop() {+ fn test_do_removal_branch_only_deletes_integrated_branch() {+ let tmp = tempfile::TempDir::new().unwrap();+ let repo_path = init_test_repo(&tmp);+ let repo = worktrunk::git::Repository::at(&repo_path).unwrap();++ // Create a branch at the same commit (fully integrated into main)+ repo.run_command(&["branch", "feature"]).unwrap();+let result = RemoveResult::BranchOnly {- branch_name: "gone".to_string(),+ branch_name: "feature".to_string(),deletion_mode: BranchDeletionMode::SafeDelete,pruned: false,};- PickerCollector::do_removal(&result).unwrap();+ PickerCollector::do_removal(&repo, &result).unwrap();++ let output = repo.run_command(&["branch", "--list", "feature"]).unwrap();+ assert!(output.is_empty(), "integrated branch should be deleted");}++ #[test]+ fn test_do_removal_branch_only_retains_unmerged_branch() {+ let tmp = tempfile::TempDir::new().unwrap();+ let repo_path = init_test_repo(&tmp);+ let repo = worktrunk::git::Repository::at(&repo_path).unwrap();++ // Create a branch with an unmerged commit+ repo.run_command(&["checkout", "-b", "unmerged"]).unwrap();+ fs::write(repo_path.join("new.txt"), "unmerged work").unwrap();+ repo.run_command(&["add", "."]).unwrap();+ repo.run_command(&["commit", "-m", "unmerged work"])+ .unwrap();+ repo.run_command(&["checkout", "main"]).unwrap();++ let result = RemoveResult::BranchOnly {+ branch_name: "unmerged".to_string(),+ deletion_mode: BranchDeletionMode::SafeDelete,+ pruned: false,+ };+ PickerCollector::do_removal(&repo, &result).unwrap();++ // Branch should be retained — SafeDelete won't delete unmerged branches+ let output = repo.run_command(&["branch", "--list", "unmerged"]).unwrap();+ assert!(+ !output.is_empty(),+ "unmerged branch should be retained with SafeDelete"+ );+ }++ // Note: skim's `as_any().downcast_ref::<WorktreeSkimItem>()` fails at+ // runtime due to TypeId mismatch between skim's reader thread and the main+ // compilation unit (skim 0.20 bug). The invoke() code path uses output()+ // matching instead. Full invoke() tests require interactive skim — verified+ // via tmux-cli during development.}diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rsindex 1807b83a7..c9924b13e 100644--- a/src/commands/repository_ext.rs+++ b/src/commands/repository_ext.rs@@ -34,14 +34,17 @@ pub trait RepositoryCliExt {/// Returns a `RemoveResult` describing what will be removed. The actual/// removal is performed by the output handler.///- /// The `config` parameter is used to compute the expected worktree path- /// for path mismatch detection.+ /// `current_path` overrides process-CWD discovery for determining which+ /// worktree is "current". Pass `None` for normal CLI usage (discovers from+ /// CWD). Pass `Some` when calling from a context where CWD may have changed+ /// (e.g., background threads in the picker).fn prepare_worktree_removal(&self,target: RemoveTarget,deletion_mode: BranchDeletionMode,force_worktree: bool,config: &UserConfig,+ current_path: Option<PathBuf>,) -> anyhow::Result<RemoveResult>;/// Prepare the target worktree for push by auto-stashing non-overlapping changes when safe.@@ -77,8 +80,9 @@ impl RepositoryCliExt for Repository {deletion_mode: BranchDeletionMode,force_worktree: bool,config: &UserConfig,+ current_path: Option<PathBuf>,) -> anyhow::Result<RemoveResult> {- let current_path = self.current_worktree().root()?.to_path_buf();+ let current_path = current_path.map_or_else(|| self.current_worktree().root(), Ok)?;let worktrees = self.list_worktrees()?;// Primary worktree path: prefer default branch's worktree, fall back to first// worktree, then repo base for bare repos with no worktrees.diff --git a/src/commands/step_commands.rs b/src/commands/step_commands.rsindex 11f692176..355a1faa8 100644--- a/src/commands/step_commands.rs+++ b/src/commands/step_commands.rs@@ -1489,6 +1489,7 @@ pub fn step_prune(dry_run: bool, yes: bool, min_age: &str, foreground: bool) ->BranchDeletionMode::SafeDelete,false,config,+ None,) {Ok(plan) => plan,Err(_) => {diff --git a/src/commands/worktree/mod.rs b/src/commands/worktree/mod.rsindex 71c8ac398..755da5754 100644--- a/src/commands/worktree/mod.rs+++ b/src/commands/worktree/mod.rs@@ -84,9 +84,10 @@ mod resolve;mod switch;mod types;-use std::path::Path;+use std::path::{Path, PathBuf};use super::branch_deletion::{BranchDeletionResult, delete_branch_if_safe};+use super::process::generate_removing_path;use worktrunk::git::Repository;// Re-export public types and functions@@ -104,19 +105,25 @@ pub use types::{/// Execute core worktree removal: stop fsmonitor, remove worktree, delete branch.///-/// Performs the three git operations that constitute worktree removal:-/// 1. Stop fsmonitor daemon (best effort — prevents zombie daemons)-/// 2. Remove the git worktree-/// 3. Delete the branch if safe (conditional on `deletion_mode` and `branch_name`)+/// Uses the fast path (rename into `.git/wt/trash/` + prune) when possible,+/// falling back to `git worktree remove` on cross-filesystem setups.+/// On the fast path the directory disappears instantly; the caller is responsible+/// for cleaning up the staged trash entry (returned via `staged_path`).///-/// The outer `Result` covers worktree removal failures. The inner-/// `Option<Result<BranchDeletionResult>>` is the raw `delete_branch_if_safe` result,-/// preserved so callers can handle branch deletion failures independently:+/// `branch_result` is the raw `delete_branch_if_safe` outcome, preserved so+/// callers can handle branch deletion failures independently:/// - The picker ignores it (best-effort in TUI context)/// - The output handler processes it for user-facing display///-/// Returns `Ok(None)` when branch deletion was not attempted (no branch name,+/// `branch_result` is `None` when deletion was not attempted (no branch name,/// or `deletion_mode.should_keep()`).+pub struct RemovalOutput {+ pub branch_result: Option<anyhow::Result<BranchDeletionResult>>,+ /// Path to the staged trash directory (fast path only). Caller should+ /// `remove_dir_all` this — either synchronously or in the background.+ pub staged_path: Option<PathBuf>,+}+pub fn execute_removal(repo: &Repository,worktree_path: &Path,@@ -124,28 +131,59 @@ pub fn execute_removal(deletion_mode: BranchDeletionMode,target_branch: Option<&str>,force_worktree: bool,-) -> anyhow::Result<Option<anyhow::Result<BranchDeletionResult>>> {+) -> anyhow::Result<RemovalOutput> {// Stop fsmonitor daemon (best effort — prevents zombie daemons when using// builtin fsmonitor). Must happen while the worktree path still exists.let _ = repo.worktree_at(worktree_path).run_command(&["fsmonitor--daemon", "stop"]);- // Remove the worktree- repo.remove_worktree(worktree_path, force_worktree)?;+ // Fast path: rename into .git/wt/trash/ (instant on same filesystem),+ // then prune git metadata. Falls back to `git worktree remove` if the+ // rename fails (cross-filesystem, permissions, Windows file locking).+ let staged_path = stage_worktree_removal(repo, worktree_path);+ if staged_path.is_none() {+ repo.remove_worktree(worktree_path, force_worktree)?;+ }// Delete branch if safe- if let Some(branch) = branch_name+ let branch_result = if let Some(branch) = branch_name&& !deletion_mode.should_keep(){let target = target_branch.unwrap_or("HEAD");- Ok(Some(delete_branch_if_safe(+ Some(delete_branch_if_safe(repo,branch,target,deletion_mode.is_force(),- )))+ ))+ } else {+ None+ };++ Ok(RemovalOutput {+ branch_result,+ staged_path,+ })+}++/// Rename a worktree into `.git/wt/trash/` and prune git metadata.+///+/// Returns `Some(staged_path)` on success, `None` if the rename failed.+/// Used internally by `execute_removal` and by the output handler's+/// `execute_instant_removal_or_fallback` (which builds shell command strings+/// and adds a placeholder directory — needs the raw staged path).+pub(crate) 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() {+ log::debug!("Failed to prune worktrees after rename: {e}");+ }+ Some(staged_path)} else {- Ok(None)+ None}}diff --git a/src/main.rs b/src/main.rsindex f34d0e906..acd27d1e8 100644--- a/src/main.rs+++ b/src/main.rs@@ -653,6 +653,7 @@ fn validate_remove_targets(deletion_mode,force,config,+ None,) {Ok(result) => plans.current = Some(result),Err(e) => plans.record_error(e),@@ -667,7 +668,7 @@ fn validate_remove_targets(} else {RemoveTarget::Path(&path_canonical)};- match repo.prepare_worktree_removal(target, deletion_mode, force, config) {+ match repo.prepare_worktree_removal(target, deletion_mode, force, config, None) {Ok(result) => plans.others.push(result),Err(e) => plans.record_error(e),}@@ -678,6 +679,7 @@ fn validate_remove_targets(deletion_mode,force,config,+ None,) {Ok(result) => plans.branch_only.push(result),Err(e) => plans.record_error(e),@@ -732,6 +734,7 @@ fn handle_remove_command(spec: RemoveCommandArgs) -> anyhow::Result<()> {BranchDeletionMode::from_flags(!spec.delete_branch, spec.force_delete),spec.force,&config,+ None,).context("Failed to remove worktree")?;diff --git a/src/output/handlers.rs b/src/output/handlers.rsindex 688037974..9c644a160 100644--- a/src/output/handlers.rs+++ b/src/output/handlers.rs@@ -16,11 +16,11 @@ use crate::commands::hooks::{HookFailureStrategy, execute_hook, prepare_background_hooks, spawn_background_hooks,};use crate::commands::process::{- HookLog, InternalOp, build_remove_command, build_remove_command_staged, generate_removing_path,- spawn_detached,+ HookLog, InternalOp, build_remove_command, build_remove_command_staged, spawn_detached,};use crate::commands::worktree::{BranchDeletionMode, RemoveResult, SwitchBranchInfo, SwitchResult, execute_removal,+ stage_worktree_removal,};use worktrunk::config::UserConfig;use worktrunk::git::GitError;@@ -89,56 +89,43 @@ fn execute_instant_removal_or_fallback(branch_to_delete: Option<&str>,force_worktree: bool,) -> String {- // Fast path: instant removal via rename-then-prune.- // Rename worktree into .git/wt/trash/ (instant on same filesystem), then prune- // git metadata. Background process just does `rm -rf` on the staged directory.- 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);- match std::fs::rename(worktree_path, &staged_path) {- Ok(()) => {- // Fast path succeeded - prune git metadata synchronously.- // If prune fails, log and continue - the staged directory will still be deleted,- // and stale metadata is harmless (cleaned up by git gc or our next worktree operation).- if let Err(e) = repo.prune_worktrees() {- log::debug!("Failed to prune worktrees after rename: {}", e);- }- // Delete branch synchronously now that prune has removed the worktree metadata.- // The branch is no longer checked out, so `git branch -D` will succeed.- // This avoids a race where the user creates a new worktree with the same branch- // name before the background `rm -rf` completes.- if let Some(branch) = branch_to_delete- && let Err(e) = repo.run_command(&["branch", "-D", branch])- {- log::debug!("Failed to delete branch {} synchronously: {}", branch, e);- }- // Create an empty placeholder at the original path so the shell's working- // directory ($env.PWD) remains valid until the wrapper has cd'd away.- // Without this, shells that validate PWD (notably Nushell) emit errors- // between binary exit and the cd directive executing.- // Best-effort: if create_dir fails (permissions, race), the only effect- // is that Nushell may still emit PWD errors — not a correctness issue.- let _ = std::fs::create_dir(worktree_path);- build_remove_command_staged(&staged_path, worktree_path)- }- Err(e) => {- // Fallback: cross-filesystem, permissions, Windows file locking, etc.- // Use legacy git worktree remove which handles these cases.- // Branch deletion stays in the background command since the worktree- // still references the branch until `git worktree remove` runs.- log::debug!("Instant removal unavailable, using legacy: {}", e);- // Git refuses to remove worktrees with initialized submodules without- // --force. We preemptively set --force when .gitmodules exists — broader- // than checking initialization, but harmless for clean worktrees.- //- // TOCTOU note: the clean check runs during planning in- // prepare_worktree_removal(). In this fallback path, we may add --force- // later (at execution time) when .gitmodules is present. That creates a- // small check-vs-use window where newly introduced changes could be- // removed. See remove_worktree() docs for the detailed safety analysis.- let force = force_worktree || worktree_path.join(".gitmodules").exists();- build_remove_command(worktree_path, branch_to_delete, force)+ // Fast path: rename worktree into .git/wt/trash/ (instant on same filesystem),+ // prune git metadata, then background process just does `rm -rf`.+ if let Some(staged_path) = stage_worktree_removal(repo, worktree_path) {+ // Delete branch synchronously now that prune has removed the worktree metadata.+ // The branch is no longer checked out, so `git branch -D` will succeed.+ // This avoids a race where the user creates a new worktree with the same branch+ // name before the background `rm -rf` completes.+ if let Some(branch) = branch_to_delete+ && let Err(e) = repo.run_command(&["branch", "-D", branch])+ {+ log::debug!("Failed to delete branch {} synchronously: {}", branch, e);}+ // Create an empty placeholder at the original path so the shell's working+ // directory ($env.PWD) remains valid until the wrapper has cd'd away.+ // Without this, shells that validate PWD (notably Nushell) emit errors+ // between binary exit and the cd directive executing.+ // Best-effort: if create_dir fails (permissions, race), the only effect+ // is that Nushell may still emit PWD errors — not a correctness issue.+ let _ = std::fs::create_dir(worktree_path);+ build_remove_command_staged(&staged_path, worktree_path)+ } else {+ // Fallback: cross-filesystem, permissions, Windows file locking, etc.+ // Use legacy git worktree remove which handles these cases.+ // Branch deletion stays in the background command since the worktree+ // still references the branch until `git worktree remove` runs.+ //+ // Git refuses to remove worktrees with initialized submodules without+ // --force. We preemptively set --force when .gitmodules exists — broader+ // than checking initialization, but harmless for clean worktrees.+ //+ // TOCTOU note: the clean check runs during planning in+ // prepare_worktree_removal(). In this fallback path, we may add --force+ // later (at execution time) when .gitmodules is present. That creates a+ // small check-vs-use window where newly introduced changes could be+ // removed. See remove_worktree() docs for the detailed safety analysis.+ let force = force_worktree || worktree_path.join(".gitmodules").exists();+ build_remove_command(worktree_path, branch_to_delete, force)}}@@ -1163,7 +1150,7 @@ fn handle_removed_worktree_output(ctx: RemovedWorktreeOutputContext<'_>) -> anyhformat_path_for_display(worktree_path))));- execute_removal(+ let output = execute_removal(&repo,worktree_path,None,@@ -1177,6 +1164,9 @@ fn handle_removed_worktree_output(ctx: RemovedWorktreeOutputContext<'_>) -> anyhremaining_entries: list_remaining_entries(worktree_path),error: err.to_string(),})?;+ if let Some(staged) = output.staged_path {+ let _ = std::fs::remove_dir_all(&staged);+ }eprintln!("{}",success_message(cformat!(@@ -1233,7 +1223,7 @@ fn handle_removed_worktree_output(ctx: RemovedWorktreeOutputContext<'_>) -> anyh);}- let branch_result = execute_removal(+ let output = execute_removal(&repo,worktree_path,Some(branch_name),@@ -1247,9 +1237,12 @@ fn handle_removed_worktree_output(ctx: RemovedWorktreeOutputContext<'_>) -> anyhremaining_entries: list_remaining_entries(worktree_path),error: err.to_string(),})?;+ if let Some(staged) = output.staged_path {+ let _ = std::fs::remove_dir_all(&staged);+ }let display_info = RemovalDisplayInfo::from_branch_result(- branch_result,+ output.branch_result,branch_name,pre_computed_integration,target_branch,diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rsindex 2c720bf3d..203ca616b 100644--- a/tests/integration_tests/remove.rs+++ b/tests/integration_tests/remove.rs@@ -2342,11 +2342,12 @@ fn test_remove_stale_staging_dir_from_crashed_removal(mut repo: TestRepo) {/// `git worktree remove` fails because a directory can't be deleted.////// Uses Unix permissions (non-writable directory) to prevent deletion of-/// a gitignored directory, triggering the `WorktreeRemovalFailed` error path-/// that lists remaining entries.+/// a gitignored directory with a non-writable subdirectory. The fast path+/// (rename to trash) handles this gracefully — the entire worktree directory+/// is renamed atomically regardless of internal permissions.#[rstest]#[cfg(unix)]-fn test_remove_foreground_failure_shows_remaining_entries(mut repo: TestRepo) {+fn test_remove_foreground_succeeds_with_stuck_directory(mut repo: TestRepo) {use std::fs::{self, Permissions};use std::os::unix::fs::PermissionsExt;@@ -2357,12 +2358,10 @@ fn test_remove_foreground_failure_shows_remaining_entries(mut repo: TestRepo) {repo.run_git_in(&worktree_path, &["add", ".gitignore"]);repo.run_git_in(&worktree_path, &["commit", "-m", "Add gitignore"]);- // Create gitignored directory with a file inside+ // Create gitignored directory with a non-writable file insidelet stuck_dir = worktree_path.join("stuck");fs::create_dir_all(&stuck_dir).unwrap();fs::write(stuck_dir.join("file.txt"), "content").unwrap();-- // Make directory non-writable so git can't unlink the file insidefs::set_permissions(&stuck_dir, Permissions::from_mode(0o555)).unwrap();// Check if permissions actually restrict us (skip if running as root)@@ -2382,27 +2381,26 @@ fn test_remove_foreground_failure_shows_remaining_entries(mut repo: TestRepo) {let stderr = String::from_utf8_lossy(&output.stderr);- // Restore permissions before assertions so TempDir cleanup works- restore_dir_permissions(&stuck_dir);+ // Restore permissions in trash dir so TempDir cleanup works+ let git_dir = repo.root_path().join(".git");+ let trash_dir = git_dir.join("wt").join("trash");+ if trash_dir.exists() {+ for entry in fs::read_dir(&trash_dir).unwrap().flatten() {+ restore_dir_permissions(&entry.path());+ }+ }assert!(- !output.status.success(),- "Remove should have failed, got: {stderr}"- );- assert!(- stderr.contains("Remaining in directory:"),- "Error should show remaining entries, got: {stderr}"- );- assert!(- stderr.contains("stuck/"),- "Error should list the stuck directory, got: {stderr}"+ output.status.success(),+ "Remove should succeed via fast path, got: {stderr}");+ assert!(!worktree_path.exists(), "Worktree directory should be gone");}/// Same as above but for the detached HEAD code path.#[rstest]#[cfg(unix)]-fn test_remove_foreground_failure_shows_remaining_entries_detached(mut repo: TestRepo) {+fn test_remove_foreground_succeeds_with_stuck_directory_detached(mut repo: TestRepo) {use std::fs::{self, Permissions};use std::os::unix::fs::PermissionsExt;@@ -2414,7 +2412,7 @@ fn test_remove_foreground_failure_shows_remaining_entries_detached(mut repo: Tesrepo.run_git_in(&worktree_path, &["commit", "-m", "Add gitignore"]);repo.detach_head_in_worktree("feature-stuck-detached");- // Create gitignored directory with a file inside+ // Create gitignored directory with a non-writable file insidelet stuck_dir = worktree_path.join("stuck");fs::create_dir_all(&stuck_dir).unwrap();fs::write(stuck_dir.join("file.txt"), "content").unwrap();@@ -2438,16 +2436,20 @@ fn test_remove_foreground_failure_shows_remaining_entries_detached(mut repo: Teslet stderr = String::from_utf8_lossy(&output.stderr);- restore_dir_permissions(&stuck_dir);+ // Restore permissions in trash dir so TempDir cleanup works+ let git_dir = repo.root_path().join(".git");+ let trash_dir = git_dir.join("wt").join("trash");+ if trash_dir.exists() {+ for entry in fs::read_dir(&trash_dir).unwrap().flatten() {+ restore_dir_permissions(&entry.path());+ }+ }assert!(- !output.status.success(),- "Remove should have failed, got: {stderr}"- );- assert!(- stderr.contains("Remaining in directory:"),- "Error should show remaining entries, got: {stderr}"+ output.status.success(),+ "Remove should succeed via fast path, got: {stderr}");+ assert!(!worktree_path.exists(), "Worktree directory should be gone");}/// Worktrees with initialized git submodules should be removable.