Skip to content

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

feat: recover gracefully when current worktree directory has been deleted (#1146)

Maximilian Roose40ed3a9ce5b
diff --git a/src/commands/handle_switch.rs b/src/commands/handle_switch.rs
index 080ab0e64..3a32fe8eb 100644
--- a/src/commands/handle_switch.rs
+++ b/src/commands/handle_switch.rs
@@ -6,7 +6,7 @@ use std::path::Path;
use anyhow::Context;
use worktrunk::HookType;
use worktrunk::config::{UserConfig, expand_template};
-use worktrunk::git::{GitError, Repository, SwitchSuggestionCtx};
+use worktrunk::git::{GitError, Repository, SwitchSuggestionCtx, current_or_recover};
use worktrunk::styling::{eprintln, info_message};
use super::command_approval::approve_hooks;
@@ -175,10 +175,11 @@ pub fn handle_switch(
verify,
} = opts;
- let repo = Repository::current().context("Failed to switch worktree")?;
+ let (repo, is_recovered) = current_or_recover().context("Failed to switch worktree")?;
// Run pre-switch hooks before anything else (before branch validation, planning, etc.)
- if verify {
+ // Skip when recovered — the source worktree is gone, nothing to run hooks against.
+ if verify && !is_recovered {
run_pre_switch_hooks(&repo, config, yes)?;
}
@@ -236,8 +237,12 @@ pub fn handle_switch(
// Show success message (temporal locality: immediately after worktree operation)
// Returns path to display in hooks when user's shell won't be in the worktree
// Also shows worktree-path hint on first --create (before shell integration warning)
- let cwd = std::env::current_dir().context("Failed to get current directory")?;
- let source_root = repo.current_worktree().root()?;
+ //
+ // When recovered from a deleted worktree, current_dir() and current_worktree().root()
+ // both fail — fall back to repo_path() (the main worktree root).
+ let fallback_path = repo.repo_path().to_path_buf();
+ let cwd = std::env::current_dir().unwrap_or(fallback_path.clone());
+ let source_root = repo.current_worktree().root().unwrap_or(fallback_path);
let hooks_display_path =
handle_switch_output(&result, &branch_info, change_dir, Some(&source_root), &cwd)?;
diff --git a/src/commands/select/mod.rs b/src/commands/select/mod.rs
index 92f265867..cf8b12695 100644
--- a/src/commands/select/mod.rs
+++ b/src/commands/select/mod.rs
@@ -14,7 +14,7 @@ use std::sync::Arc;
use anyhow::Context;
use dashmap::DashMap;
use skim::prelude::*;
-use worktrunk::git::Repository;
+use worktrunk::git::{Repository, current_or_recover};
use super::handle_switch::{
approve_switch_hooks, run_pre_switch_hooks, spawn_switch_background_hooks, switch_extra_vars,
@@ -34,7 +34,7 @@ pub fn handle_select(cli_branches: bool, cli_remotes: bool) -> anyhow::Result<()
anyhow::bail!("Interactive picker requires an interactive terminal");
}
- let repo = Repository::current()?;
+ let (repo, is_recovered) = current_or_recover()?;
// Merge CLI flags with resolved config
let config = repo.config();
@@ -308,12 +308,19 @@ pub fn handle_select(cli_branches: bool, cli_remotes: bool) -> anyhow::Result<()
(selected.output().to_string(), false)
};
- // Load config
- let repo = Repository::current().context("Failed to switch worktree")?;
+ // Load config — reuse recovered repo if we recovered earlier
+ let repo = if is_recovered {
+ repo.clone()
+ } else {
+ Repository::current().context("Failed to switch worktree")?
+ };
let config = repo.user_config();
// Run pre-switch hooks before anything else (before branch validation, planning, etc.)
- run_pre_switch_hooks(&repo, config, true)?;
+ // Skip when recovered — the source worktree is gone, nothing to run hooks against.
+ if !is_recovered {
+ run_pre_switch_hooks(&repo, config, true)?;
+ }
// Switch to existing worktree or create new one
let plan = plan_switch(&repo, &identifier, should_create, None, false, config)?;
@@ -334,8 +341,10 @@ pub fn handle_select(cli_branches: bool, cli_remotes: bool) -> anyhow::Result<()
// Show success message; emit cd directive if shell integration is active
// Interactive picker always performs cd (change_dir: true)
- let cwd = std::env::current_dir().context("Failed to get current directory")?;
- let source_root = repo.current_worktree().root()?;
+ // When recovered from a deleted worktree, fall back to repo_path().
+ let fallback_path = repo.repo_path().to_path_buf();
+ let cwd = std::env::current_dir().unwrap_or(fallback_path.clone());
+ let source_root = repo.current_worktree().root().unwrap_or(fallback_path);
let hooks_display_path =
handle_switch_output(&result, &branch_info, true, Some(&source_root), &cwd)?;
diff --git a/src/git/mod.rs b/src/git/mod.rs
index 03a48d977..d63953486 100644
--- a/src/git/mod.rs
+++ b/src/git/mod.rs
@@ -6,6 +6,7 @@ use std::path::PathBuf;
mod diff;
mod error;
mod parse;
+pub mod recover;
pub mod remote_ref;
mod repository;
mod url;
@@ -53,6 +54,7 @@ pub use error::{
exit_code,
};
pub use parse::{parse_porcelain_z, parse_untracked_files};
+pub use recover::current_or_recover;
pub use repository::{Branch, Repository, ResolvedWorktree, WorkingTree, set_base_path};
pub use url::GitRemoteUrl;
pub use url::{parse_owner_repo, parse_remote_owner};
diff --git a/src/git/recover.rs b/src/git/recover.rs
new file mode 100644
index 000000000..09ceebd61
--- /dev/null
+++ b/src/git/recover.rs
@@ -0,0 +1,421 @@
+//! Recovery from a deleted current working directory.
+//!
+//! When a linked worktree is removed (via `wt remove` or `wt merge` from another
+//! terminal) while a shell is still in that directory, `Repository::current()` fails
+//! because git can't resolve the CWD. This module provides recovery by finding the
+//! parent repository from `$PWD` (which shells preserve after directory deletion).
+
+use std::path::{Path, PathBuf};
+
+use super::Repository;
+
+/// Try to get the current repository, recovering from a deleted CWD if possible.
+///
+/// Returns `(Repository, recovered)` where `recovered` is `true` if the CWD was
+/// deleted and we recovered by finding the parent repository.
+///
+/// Prints an info message when recovery occurs.
+pub fn current_or_recover() -> anyhow::Result<(Repository, bool)> {
+ match Repository::current() {
+ Ok(repo) => Ok((repo, false)),
+ Err(err) => match recover_from_deleted_cwd() {
+ Some(repo) => {
+ eprintln!(
+ "{}",
+ crate::styling::info_message("Current worktree was removed, recovering...")
+ );
+ Ok((repo, true))
+ }
+ None => Err(err),
+ },
+ }
+}
+
+/// Attempt to recover a repository when the current directory has been deleted.
+///
+/// Returns `Some(Repository)` if:
+/// 1. `std::env::current_dir()` fails or returns a non-existent path (CWD is gone)
+/// 2. `$PWD` points to a path whose ancestor contains a git repository
+/// 3. The deleted path was actually a worktree of that repository
+///
+/// Returns `None` if CWD is fine or recovery fails at any step.
+fn recover_from_deleted_cwd() -> Option<Repository> {
+ // If current_dir succeeds and the directory exists, nothing to recover from.
+ // On Windows, current_dir() may succeed even after the directory is removed
+ // (the process handle keeps it alive), so also check existence on disk.
+ match std::env::current_dir() {
+ Ok(p) if p.exists() => return None,
+ _ => {}
+ }
+
+ // Shells preserve the logical path in $PWD even after the directory is deleted
+ let pwd = std::env::var_os("PWD")?;
+ let deleted_path = PathBuf::from(pwd);
+
+ recover_from_path(&deleted_path)
+}
+
+/// Core recovery logic: given a deleted worktree path, find the parent repository.
+///
+/// Walks up from `deleted_path` to find the first existing ancestor, looks for a
+/// git repository there or in its immediate children, and verifies the deleted path
+/// was actually a worktree of that repository.
+fn recover_from_path(deleted_path: &Path) -> Option<Repository> {
+ let ancestor = first_existing_ancestor(deleted_path)?;
+ log::debug!(
+ "Deleted CWD recovery: path={}, ancestor={}",
+ deleted_path.display(),
+ ancestor.display()
+ );
+
+ // Look for a git repository at the ancestor or its immediate children
+ let repo = find_repo_near(&ancestor)?;
+
+ // Verify the deleted path was actually a worktree of this repo
+ if !was_worktree_of(&repo, deleted_path) {
+ log::debug!("Deleted CWD recovery: path was not a worktree of discovered repo");
+ return None;
+ }
+
+ Some(repo)
+}
+
+/// Walk up from `path` to find the first existing ancestor directory.
+fn first_existing_ancestor(path: &Path) -> Option<PathBuf> {
+ let mut candidate = path.parent()?;
+ loop {
+ if candidate.is_dir() {
+ return Some(candidate.to_path_buf());
+ }
+ candidate = candidate.parent()?;
+ }
+}
+
+/// Look for a git repository at `dir` or its immediate children.
+///
+/// Only checks for `.git` **directories** (main repos), not `.git` files
+/// (which are linked worktrees — we need the main repo to recover).
+fn find_repo_near(dir: &Path) -> Option<Repository> {
+ // Check the directory itself first
+ if let Some(repo) = try_repo_at(dir) {
+ return Some(repo);
+ }
+
+ // Check immediate children for .git directories.
+ // Uses is_some_and instead of ? so an unreadable entry (e.g., broken symlink)
+ // skips that entry rather than aborting the entire search.
+ let entries = std::fs::read_dir(dir).ok()?;
+ for entry in entries.flatten() {
+ if entry.file_type().ok().is_some_and(|ft| ft.is_dir())
+ && let Some(repo) = try_repo_at(&entry.path())
+ {
+ return Some(repo);
+ }
+ }
+
+ None
+}
+
+/// Try to discover a repository at the given path.
+///
+/// Returns `Some(repo)` if the path contains a `.git` directory (not a file)
+/// and `Repository::at()` succeeds.
+///
+/// Note: This only matches `.git` directories, so bare repos (which have no
+/// `.git` subdirectory) won't be discovered. The fallback hint in `main.rs`
+/// covers this gracefully.
+fn try_repo_at(dir: &Path) -> Option<Repository> {
+ let git_path = dir.join(".git");
+ // Only match .git directories (main repos), not .git files (linked worktrees)
+ if git_path.is_dir() {
+ Repository::at(dir).ok()
+ } else {
+ None
+ }
+}
+
+/// Check if the deleted path was a worktree of the given repository.
+///
+/// Uses `list_worktrees()` which includes prunable entries — a deleted worktree
+/// directory will show up as prunable, confirming it belonged to this repo.
+fn was_worktree_of(repo: &Repository, deleted_path: &Path) -> bool {
+ let worktrees = match repo.list_worktrees() {
+ Ok(wt) => wt,
+ Err(_) => return false,
+ };
+
+ // Canonicalize the deleted path's parent for comparison, since worktree paths
+ // from git are typically canonical. We can't canonicalize the deleted path
+ // itself (it doesn't exist), but we can check if any worktree path matches.
+ worktrees.iter().any(|wt| {
+ wt.path == deleted_path || (wt.is_prunable() && paths_match(&wt.path, deleted_path))
+ })
+}
+
+/// Compare worktree paths, accounting for the fact that the deleted path
+/// may not be canonical (e.g., symlinks in parent directories).
+fn paths_match(worktree_path: &Path, deleted_path: &Path) -> bool {
+ // Direct comparison first
+ if worktree_path == deleted_path {
+ return true;
+ }
+
+ // Try canonicalizing parents and comparing the final component.
+ // The deleted path doesn't exist, but its parent might.
+ let wt_name = worktree_path.file_name();
+ let del_name = deleted_path.file_name();
+ if wt_name != del_name {
+ return false;
+ }
+
+ // If both parents can be canonicalized and they match, the paths match
+ let wt_parent = worktree_path
+ .parent()
+ .and_then(|p| dunce::canonicalize(p).ok());
+ let del_parent = deleted_path
+ .parent()
+ .and_then(|p| dunce::canonicalize(p).ok());
+ matches!((wt_parent, del_parent), (Some(a), Some(b)) if a == b)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::shell_exec::Cmd;
+
+ fn git_init(path: &Path) {
+ Cmd::new("git")
+ .args(["init", "--quiet"])
+ .current_dir(path)
+ .run()
+ .unwrap();
+ }
+
+ #[test]
+ fn test_first_existing_ancestor_finds_parent() {
+ let tmp = tempfile::tempdir().unwrap();
+ let existing = tmp.path().join("a");
+ std::fs::create_dir(&existing).unwrap();
+ let deleted = existing.join("b").join("c");
+
+ let result = first_existing_ancestor(&deleted);
+ assert_eq!(result, Some(existing));
+ }
+
+ #[test]
+ fn test_first_existing_ancestor_returns_none_for_root() {
+ // A path with no existing ancestors (besides root) should still find something
+ let result = first_existing_ancestor(Path::new("/nonexistent/deep/path"));
+ assert!(result.is_some()); // / exists
+ }
+
+ #[test]
+ fn test_try_repo_at_rejects_git_file() {
+ let tmp = tempfile::tempdir().unwrap();
+ // Create a .git file (not directory) — simulates a linked worktree
+ std::fs::write(tmp.path().join(".git"), "gitdir: /some/path").unwrap();
+ assert!(try_repo_at(tmp.path()).is_none());
+ }
+
+ #[test]
+ fn test_try_repo_at_accepts_git_dir() {
+ let tmp = tempfile::tempdir().unwrap();
+ git_init(tmp.path());
+ assert!(try_repo_at(tmp.path()).is_some());
+ }
+
+ #[test]
+ fn test_find_repo_near_finds_repo_in_child() {
+ let tmp = tempfile::tempdir().unwrap();
+ let child = tmp.path().join("myrepo");
+ std::fs::create_dir(&child).unwrap();
+ git_init(&child);
+
+ let repo = find_repo_near(tmp.path());
+ assert!(repo.is_some());
+ }
+
+ #[test]
+ fn test_recover_returns_none_when_cwd_exists() {
+ // current_dir() succeeds in test environment, so recovery should return None
+ assert!(recover_from_deleted_cwd().is_none());
+ }
+
+ #[test]
+ fn test_find_repo_near_returns_none_when_no_repo() {
+ let tmp = tempfile::tempdir().unwrap();
+ // No .git directory anywhere — should return None
+ assert!(find_repo_near(tmp.path()).is_none());
+ }
+
+ #[test]
+ fn test_find_repo_near_skips_non_directories() {
+ let tmp = tempfile::tempdir().unwrap();
+ // Create a file (not a directory) as child — should be skipped
+ std::fs::write(tmp.path().join("not_a_dir"), "data").unwrap();
+ assert!(find_repo_near(tmp.path()).is_none());
+ }
+
+ #[test]
+ fn test_paths_match_identical_paths() {
+ let p = PathBuf::from("/some/path/feature");
+ assert!(paths_match(&p, &p));
+ }
+
+ #[test]
+ fn test_paths_match_different_names() {
+ let a = PathBuf::from("/repos/feature-a");
+ let b = PathBuf::from("/repos/feature-b");
+ assert!(!paths_match(&a, &b));
+ }
+
+ #[test]
+ fn test_paths_match_same_name_same_parent() {
+ let tmp = tempfile::tempdir().unwrap();
+ // Both paths share the same existing parent and same name
+ let a = tmp.path().join("feature");
+ let b = tmp.path().join("feature");
+ assert!(paths_match(&a, &b));
+ }
+
+ #[test]
+ fn test_paths_match_different_parent() {
+ let tmp = tempfile::tempdir().unwrap();
+ let dir_a = tmp.path().join("a");
+ let dir_b = tmp.path().join("b");
+ std::fs::create_dir(&dir_a).unwrap();
+ std::fs::create_dir(&dir_b).unwrap();
+ let a = dir_a.join("feature");
+ let b = dir_b.join("feature");
+ assert!(!paths_match(&a, &b));
+ }
+
+ #[test]
+ fn test_was_worktree_of_finds_existing_worktree() {
+ let tmp = tempfile::tempdir().unwrap();
+ // Canonicalize to handle symlinks (e.g., /tmp -> /private/tmp on macOS)
+ let base = dunce::canonicalize(tmp.path()).unwrap();
+ let repo_dir = base.join("repo");
+ std::fs::create_dir(&repo_dir).unwrap();
+ git_init(&repo_dir);
+ // Create an initial commit so worktree add works
+ Cmd::new("git")
+ .args(["commit", "--allow-empty", "-m", "init"])
+ .current_dir(&repo_dir)
+ .run()
+ .unwrap();
+
+ // Add a linked worktree
+ let wt_path = base.join("feature-wt");
+ Cmd::new("git")
+ .args([
+ "worktree",
+ "add",
+ &wt_path.to_string_lossy(),
+ "-b",
+ "feature",
+ ])
+ .current_dir(&repo_dir)
+ .run()
+ .unwrap();
+
+ let repo = Repository::at(&repo_dir).unwrap();
+ assert!(was_worktree_of(&repo, &wt_path));
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn test_find_repo_near_handles_broken_symlink() {
+ let tmp = tempfile::tempdir().unwrap();
+ // Create a broken symlink — file_type() returns Err for these
+ std::os::unix::fs::symlink("/nonexistent/target", tmp.path().join("broken_link")).unwrap();
+ // Should return None without aborting (the broken symlink is skipped gracefully)
+ assert!(find_repo_near(tmp.path()).is_none());
+ }
+
+ #[test]
+ fn test_current_or_recover_returns_repo_when_cwd_exists() {
+ // In a test environment, CWD exists, so current_or_recover should succeed
+ // via the normal Repository::current() path (not recovery).
+ // Tests run inside a git repo in CI, so Repository::current() succeeds.
+ let (repo, recovered) = current_or_recover().unwrap();
+ assert!(!recovered);
+ assert!(repo.repo_path().exists());
+ }
+
+ #[test]
+ fn test_was_worktree_of_rejects_unknown_path() {
+ let tmp = tempfile::tempdir().unwrap();
+ git_init(tmp.path());
+ Cmd::new("git")
+ .args(["commit", "--allow-empty", "-m", "init"])
+ .current_dir(tmp.path())
+ .run()
+ .unwrap();
+
+ let repo = Repository::at(tmp.path()).unwrap();
+ let unknown = PathBuf::from("/nonexistent/unknown");
+ assert!(!was_worktree_of(&repo, &unknown));
+ }
+
+ #[test]
+ fn test_recover_from_path_finds_deleted_worktree() {
+ let tmp = tempfile::tempdir().unwrap();
+ let base = dunce::canonicalize(tmp.path()).unwrap();
+ let repo_dir = base.join("repo");
+ std::fs::create_dir(&repo_dir).unwrap();
+ git_init(&repo_dir);
+ Cmd::new("git")
+ .args(["commit", "--allow-empty", "-m", "init"])
+ .current_dir(&repo_dir)
+ .run()
+ .unwrap();
+
+ // Add a linked worktree
+ let wt_path = base.join("feature-wt");
+ Cmd::new("git")
+ .args([
+ "worktree",
+ "add",
+ &wt_path.to_string_lossy(),
+ "-b",
+ "feature",
+ ])
+ .current_dir(&repo_dir)
+ .run()
+ .unwrap();
+
+ // Delete the worktree directory (simulating external removal)
+ std::fs::remove_dir_all(&wt_path).unwrap();
+
+ // recover_from_path should find the parent repo
+ assert!(recover_from_path(&wt_path).is_some());
+ }
+
+ #[test]
+ fn test_recover_from_path_returns_none_for_unrelated_path() {
+ let tmp = tempfile::tempdir().unwrap();
+ let base = dunce::canonicalize(tmp.path()).unwrap();
+ let repo_dir = base.join("repo");
+ std::fs::create_dir(&repo_dir).unwrap();
+ git_init(&repo_dir);
+ Cmd::new("git")
+ .args(["commit", "--allow-empty", "-m", "init"])
+ .current_dir(&repo_dir)
+ .run()
+ .unwrap();
+
+ // Try to recover from a path that was never a worktree
+ let unrelated = base.join("not-a-worktree");
+ assert!(recover_from_path(&unrelated).is_none());
+ }
+
+ #[test]
+ fn test_find_repo_near_finds_repo_at_dir_itself() {
+ let tmp = tempfile::tempdir().unwrap();
+ git_init(tmp.path());
+ // When the directory itself is a git repo, find_repo_near should return it
+ // (covers the early-return path before scanning children)
+ assert!(find_repo_near(tmp.path()).is_some());
+ }
+}
diff --git a/src/main.rs b/src/main.rs
index c6ad33e05..defc01598 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -7,7 +7,7 @@ use clap::error::ErrorKind as ClapErrorKind;
use color_print::{ceprintln, cformat};
use std::process;
use worktrunk::config::{UserConfig, set_config_path};
-use worktrunk::git::{Repository, ResolvedWorktree, exit_code, set_base_path};
+use worktrunk::git::{Repository, ResolvedWorktree, current_or_recover, exit_code, set_base_path};
use worktrunk::path::format_path_for_display;
use worktrunk::shell::extract_filename_from_path;
use worktrunk::styling::{
@@ -704,7 +704,7 @@ fn main() {
commands::statusline::run(effective_format)
}
None => (|| {
- let repo = Repository::current()?;
+ let (repo, _recovered) = current_or_recover()?;
let progressive_opt = match (progressive, no_progressive) {
(true, _) => Some(true),
@@ -1016,11 +1016,16 @@ fn main() {
};
if let Err(e) = result {
- // GitError, WorktrunkError, and HookErrorWithHint produce styled output via Display
+ // GitError, WorktrunkError, and HookErrorWithHint produce styled output via Display.
+ // Some variants (AlreadyDisplayed, CommandNotApproved) have empty Display impls —
+ // skip eprintln! for those to avoid phantom blank lines.
if let Some(err) = e.downcast_ref::<worktrunk::git::GitError>() {
eprintln!("{}", err);
} else if let Some(err) = e.downcast_ref::<worktrunk::git::WorktrunkError>() {
- eprintln!("{}", err);
+ let display = err.to_string();
+ if !display.is_empty() {
+ eprintln!("{display}");
+ }
} else if let Some(err) = e.downcast_ref::<worktrunk::git::HookErrorWithHint>() {
eprintln!("{}", err);
} else if let Some(err) = e.downcast_ref::<worktrunk::config::TemplateExpandError>() {
@@ -1055,6 +1060,18 @@ fn main() {
}
}
+ // If the CWD has been deleted, hint the user to use `wt switch ^`.
+ // Check both: (1) explicit flag set by merge/remove when it knows the CWD
+ // worktree was removed (reliable on all platforms), and (2) OS-level detection
+ // for cases not covered by the flag (e.g., external worktree removal).
+ let cwd_gone = output::was_cwd_removed() || std::env::current_dir().is_err();
+ if cwd_gone {
+ eprintln!(
+ "{}",
+ hint_message("Current directory was removed. Try: wt switch ^")
+ );
+ }
+
// Preserve exit code from child processes (especially for signals like SIGINT)
let code = exit_code(&e).unwrap_or(1);
diff --git a/src/output/global.rs b/src/output/global.rs
index f6cdbb3f7..e93b0fb86 100644
--- a/src/output/global.rs
+++ b/src/output/global.rs
@@ -59,6 +59,11 @@ struct OutputState {
/// Mapping from canonical path prefix to logical (symlink) prefix.
/// Computed once at init from `$PWD` vs `std::env::current_dir()`.
symlink_mapping: Option<SymlinkMapping>,
+ /// Set when a command removes the CWD's worktree (e.g., `wt merge`).
+ /// Used by the error handler to show a "directory was removed" hint.
+ /// This explicit flag avoids unreliable CWD detection on Windows where
+ /// deleted directories remain accessible to the process that held them.
+ cwd_removed: bool,
}
/// Maps canonical path prefixes to logical (symlink-preserved) prefixes.
@@ -181,6 +186,7 @@ fn get_state() -> &'static Mutex<OutputState> {
directive_file,
target_dir: None,
symlink_mapping,
+ cwd_removed: false,
})
})
}
@@ -246,6 +252,26 @@ pub fn change_directory(path: impl AsRef<Path>) -> io::Result<()> {
Ok(())
}
+/// Mark that the current working directory's worktree has been removed.
+///
+/// Called by the removal handler (e.g., during `wt merge`) when it knows the
+/// process CWD was part of the worktree being removed. The error handler in
+/// `main.rs` checks this to show a "directory was removed" hint.
+pub fn mark_cwd_removed() {
+ get_state()
+ .lock()
+ .expect("OUTPUT_STATE lock poisoned")
+ .cwd_removed = true;
+}
+
+/// Check whether the CWD worktree was removed during this command.
+pub fn was_cwd_removed() -> bool {
+ get_state()
+ .lock()
+ .expect("OUTPUT_STATE lock poisoned")
+ .cwd_removed
+}
+
/// Request command execution
///
/// In interactive mode (no directive file), executes the command directly (replacing process on Unix).
@@ -501,6 +527,15 @@ mod tests {
let _ = has_directive_file();
}
+ #[test]
+ fn test_cwd_removed_flag() {
+ // was_cwd_removed() returns the flag set by mark_cwd_removed().
+ // Note: global state persists across tests, so we only test mark + read,
+ // not the default (which another test may have already changed).
+ mark_cwd_removed();
+ assert!(was_cwd_removed());
+ }
+
#[test]
fn test_spawned_thread_uses_correct_state() {
use std::sync::mpsc;
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index 528190d2d..f4d60159b 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -1011,6 +1011,9 @@ fn handle_removed_worktree_output(
if changed_directory {
super::change_directory(main_path)?;
stderr().flush()?; // Force flush to ensure shell processes the cd
+ // Mark that the CWD worktree is being removed, so the error handler
+ // can show a hint if a subsequent command (e.g., post-merge hook) fails.
+ super::mark_cwd_removed();
}
// Handle detached HEAD case (no branch known)
diff --git a/src/output/mod.rs b/src/output/mod.rs
index 4c02bd48a..a7bf51568 100644
--- a/src/output/mod.rs
+++ b/src/output/mod.rs
@@ -37,8 +37,9 @@ pub(crate) mod shell_integration;
// Re-export the public API
pub(crate) use global::{
- change_directory, execute, is_shell_integration_active, post_hook_display_path,
- pre_hook_display_path, set_verbosity, terminate_output, to_logical_path,
+ change_directory, execute, is_shell_integration_active, mark_cwd_removed,
+ post_hook_display_path, pre_hook_display_path, set_verbosity, terminate_output,
+ to_logical_path, was_cwd_removed,
};
// Re-export output handlers
pub(crate) use handlers::{
diff --git a/tests/snapshots/integration__integration_tests__merge__merge_post_merge_command_failure.snap b/tests/snapshots/integration__integration_tests__merge__merge_post_merge_command_failure.snap
index 81e22f759..20e7a2a9e 100644
--- a/tests/snapshots/integration__integration_tests__merge__merge_post_merge_command_failure.snap
+++ b/tests/snapshots/integration__integration_tests__merge__merge_post_merge_command_failure.snap
@@ -26,10 +26,13 @@ info:
SHELL: ""
TERM: alacritty
USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_NUSHELL_ENV: "0"
WORKTRUNK_TEST_POWERSHELL_ENV: "0"
WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
@@ -50,3 +53,4 @@ exit_code: 1
◎ Running post-merge project hook @ _REPO_
  exit 1
✗ Command failed: exit status: 1
+↳ Current directory was removed. Try: wt switch ^