Skip to content

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

fix(remove): force-kill a wedged fsmonitor daemon on worktree removal (#2813)

Maximilian Roos045750f89008
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1097c429b..301800454 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,11 @@
# Changelog
+## Unreleased
+
+### Fixed
+
+- **`wt remove` reaps a wedged fsmonitor daemon**: When `core.fsmonitor=true`, git runs a per-worktree `git fsmonitor--daemon`. Removal already sent `git fsmonitor--daemon stop`, but `stop` is an IPC request to the daemon itself, so a daemon that had stopped answering its socket ignored it and then leaked forever once its worktree was gone (dozens could accumulate, and one wedged daemon hangs `wt list`). Removal now resolves the daemon's PID from its IPC socket and force-terminates it (SIGTERM, brief wait, SIGKILL) when `stop` doesn't take. The signal only ever targets the daemon whose socket resolves to the worktree being removed.
+
## 0.52.0
### Improved
diff --git a/docs/content/faq.md b/docs/content/faq.md
index 00cb5e796..b84ffb293 100644
--- a/docs/content/faq.md
+++ b/docs/content/faq.md
@@ -163,6 +163,7 @@ Use `-D` to force-delete branches with unmerged changes. Use `--no-delete-branch
### Other cleanup
- `wt remove` — in addition to the target worktree, sweeps `.git/wt/trash/` entries older than 24 hours in the background (eventual cleanup for directories orphaned when a previous background removal was interrupted)
+- `wt remove` — terminates the removed worktree's `git fsmonitor--daemon` process. Git starts this per-worktree filesystem-watch daemon when `core.fsmonitor=true`; once its worktree is gone it would leak. Removal sends `git fsmonitor--daemon stop`, then resolves that daemon's PID from its IPC socket and force-terminates it (SIGTERM, then SIGKILL) if it didn't exit. The signal only ever targets the daemon whose socket resolves to the worktree being removed.
- `wt config state clear` — removes all worktrunk data from `.git/` (config keys, caches, markers, hints, variables, logs, stale trash)
- `wt config shell uninstall` — removes shell integration from rc files
diff --git a/skills/worktrunk/reference/faq.md b/skills/worktrunk/reference/faq.md
index 838e5ec18..f552cb50f 100644
--- a/skills/worktrunk/reference/faq.md
+++ b/skills/worktrunk/reference/faq.md
@@ -158,6 +158,7 @@ Use `-D` to force-delete branches with unmerged changes. Use `--no-delete-branch
### Other cleanup
- `wt remove` — in addition to the target worktree, sweeps `.git/wt/trash/` entries older than 24 hours in the background (eventual cleanup for directories orphaned when a previous background removal was interrupted)
+- `wt remove` — terminates the removed worktree's `git fsmonitor--daemon` process. Git starts this per-worktree filesystem-watch daemon when `core.fsmonitor=true`; once its worktree is gone it would leak. Removal sends `git fsmonitor--daemon stop`, then resolves that daemon's PID from its IPC socket and force-terminates it (SIGTERM, then SIGKILL) if it didn't exit. The signal only ever targets the daemon whose socket resolves to the worktree being removed.
- `wt config state clear` — removes all worktrunk data from `.git/` (config keys, caches, markers, hints, variables, logs, stale trash)
- `wt config shell uninstall` — removes shell integration from rc files
diff --git a/skills/worktrunk/reference/troubleshooting.md b/skills/worktrunk/reference/troubleshooting.md
index 52a2a45da..2d699d71b 100644
--- a/skills/worktrunk/reference/troubleshooting.md
+++ b/skills/worktrunk/reference/troubleshooting.md
@@ -115,7 +115,7 @@ done
For a specific hung worktree, kill the daemon whose socket path matches it, or just `pkill -9 -f 'git fsmonitor--daemon'` and let the next `wt list` respawn the live ones. Disabling fsmonitor globally (`git config --global core.fsmonitor false`) avoids the class of problem entirely at the cost of some `git status` speed on large repos.
-Daemons leak when a worktree is removed while its daemon is already unresponsive — `wt remove` calls `git fsmonitor--daemon stop`, but a daemon that can't answer its IPC can't be stopped through it.
+`wt remove` reaps the removed worktree's daemon even when it's wedged: it sends `git fsmonitor--daemon stop`, then resolves the daemon's PID from its IPC socket and force-terminates it (SIGTERM, brief wait, SIGKILL) if it didn't exit. So removal doesn't leak. A daemon only accumulates for a worktree that's never removed and whose daemon wedges in place, or from `wt list` starting a fresh daemon against an already-wedged one. `pkill -9 -f 'git fsmonitor--daemon'` clears those; the live ones respawn on the next `wt list`.
## PowerShell on Windows
diff --git a/src/commands/process.rs b/src/commands/process.rs
index 5adc61ece..f3987b853 100644
--- a/src/commands/process.rs
+++ b/src/commands/process.rs
@@ -718,24 +718,22 @@ pub fn build_remove_command(
let worktree_path_str = worktree_path.to_string_lossy();
let worktree_escaped = escape(worktree_path_str.as_ref().into());
- // Stop fsmonitor daemon first (best effort - ignore errors)
- // This prevents zombie daemons from accumulating when using builtin fsmonitor
- let stop_fsmonitor = format!(
- "{{ git -C {} fsmonitor--daemon stop 2>/dev/null || true; }}",
- worktree_escaped
- );
-
let force_flag = if force_worktree { " --force" } else { "" };
+ // The fsmonitor daemon is stopped (and force-killed if wedged) synchronously
+ // in the Rust foreground by `stop_fsmonitor_daemon`, before this command is
+ // built — see `spawn_background_removal`. The detached process only does the
+ // `git worktree remove` / `rm -rf`.
+ //
// When removing the current worktree, delay so the shell wrapper can cd away
// before the directory is removed. The primary fix for the "shell-init: error
// retrieving current directory" race is in the fish wrapper (using builtins
// instead of subprocesses to read the directive), but this provides defense in
// depth for other shells and edge cases.
let prefix = if changed_directory {
- format!("sleep 1 && {} && ", stop_fsmonitor)
+ "sleep 1 && ".to_string()
} else {
- format!("{} && ", stop_fsmonitor)
+ String::new()
};
match branch_to_delete {
@@ -847,19 +845,19 @@ mod tests {
let path = PathBuf::from("/tmp/test-worktree");
// changed_directory=true: sleep before removal
- assert_snapshot!(build_remove_command(&path, None, false, true), @"sleep 1 && { git -C /tmp/test-worktree fsmonitor--daemon stop 2>/dev/null || true; } && git worktree remove /tmp/test-worktree");
- assert_snapshot!(build_remove_command(&path, Some("feature-branch"), false, true), @"sleep 1 && { git -C /tmp/test-worktree fsmonitor--daemon stop 2>/dev/null || true; } && git worktree remove /tmp/test-worktree && git branch -D feature-branch");
+ assert_snapshot!(build_remove_command(&path, None, false, true), @"sleep 1 && git worktree remove /tmp/test-worktree");
+ assert_snapshot!(build_remove_command(&path, Some("feature-branch"), false, true), @"sleep 1 && git worktree remove /tmp/test-worktree && git branch -D feature-branch");
// changed_directory=false: no sleep
- assert_snapshot!(build_remove_command(&path, None, false, false), @"{ git -C /tmp/test-worktree fsmonitor--daemon stop 2>/dev/null || true; } && git worktree remove /tmp/test-worktree");
- assert_snapshot!(build_remove_command(&path, Some("feature-branch"), false, false), @"{ git -C /tmp/test-worktree fsmonitor--daemon stop 2>/dev/null || true; } && git worktree remove /tmp/test-worktree && git branch -D feature-branch");
+ assert_snapshot!(build_remove_command(&path, None, false, false), @"git worktree remove /tmp/test-worktree");
+ assert_snapshot!(build_remove_command(&path, Some("feature-branch"), false, false), @"git worktree remove /tmp/test-worktree && git branch -D feature-branch");
// With force flag
- assert_snapshot!(build_remove_command(&path, None, true, true), @"sleep 1 && { git -C /tmp/test-worktree fsmonitor--daemon stop 2>/dev/null || true; } && git worktree remove --force /tmp/test-worktree");
+ assert_snapshot!(build_remove_command(&path, None, true, true), @"sleep 1 && git worktree remove --force /tmp/test-worktree");
// Shell escaping for special characters
let special_path = PathBuf::from("/tmp/test worktree");
- assert_snapshot!(build_remove_command(&special_path, Some("feature/branch"), false, true), @"sleep 1 && { git -C '/tmp/test worktree' fsmonitor--daemon stop 2>/dev/null || true; } && git worktree remove '/tmp/test worktree' && git branch -D feature/branch");
+ assert_snapshot!(build_remove_command(&special_path, Some("feature/branch"), false, true), @"sleep 1 && git worktree remove '/tmp/test worktree' && git branch -D feature/branch");
}
#[test]
diff --git a/src/git/mod.rs b/src/git/mod.rs
index 07fbe1002..2f9497f9a 100644
--- a/src/git/mod.rs
+++ b/src/git/mod.rs
@@ -71,6 +71,7 @@ pub use recover::{current_or_recover, cwd_removed_hint};
pub use remove::{
BranchDeletionMode, BranchDeletionOutcome, BranchDeletionResult, RemovalOutput, RemoveOptions,
delete_branch_if_safe, remove_worktree_with_cleanup, stage_worktree_removal,
+ stop_fsmonitor_daemon,
};
pub use repository::sha_cache;
pub use repository::{
diff --git a/src/git/remove.rs b/src/git/remove.rs
index 17ad4f225..3fb22e4a4 100644
--- a/src/git/remove.rs
+++ b/src/git/remove.rs
@@ -8,9 +8,12 @@
//!
//! # What happens during removal
//!
-//! 1. **fsmonitor daemon stopped** (best effort). `git fsmonitor--daemon stop`
-//! runs against the target worktree before its path disappears, preventing
-//! zombie daemons on platforms that use builtin fsmonitor.
+//! 1. **fsmonitor daemon stopped** (best effort). [`stop_fsmonitor_daemon`]
+//! runs against the target worktree before its path disappears: it sends
+//! the graceful `git fsmonitor--daemon stop` IPC request, then verifies the
+//! daemon is actually gone and force-kills it by PID if it has wedged.
+//! Without this, a daemon that has stopped answering its socket leaks
+//! forever once its worktree is removed.
//! 2. **Fast-path trash staging.** The worktree directory is renamed into
//! `<git-common-dir>/wt/trash/<name>-<timestamp>/`. Same-filesystem renames
//! are instant metadata operations, so the user's workspace clears
@@ -58,10 +61,158 @@
//! ```
use std::path::{Path, PathBuf};
+use std::time::Duration;
+use crate::git::repository::WorkingTree;
use crate::git::{IntegrationReason, Repository};
+use crate::shell_exec::Cmd;
use crate::utils::epoch_now;
+/// Bound on the graceful `git fsmonitor--daemon stop` IPC request.
+///
+/// `stop` is itself an IPC call to the daemon, so a wedged daemon (the failure
+/// this whole helper exists for) makes it hang. The force-kill path below is
+/// what actually reaps such a daemon; this timeout just stops the graceful
+/// attempt from blocking `wt remove` while the daemon ignores it.
+const FSMONITOR_STOP_TIMEOUT: Duration = Duration::from_secs(2);
+
+/// Bound on the `lsof` socket→PID lookup.
+#[cfg(unix)]
+const FSMONITOR_LSOF_TIMEOUT: Duration = Duration::from_secs(2);
+
+/// How long to wait for a daemon to exit after SIGTERM before escalating to
+/// SIGKILL. Polled, not slept — a daemon that exits promptly returns early.
+#[cfg(unix)]
+const FSMONITOR_SIGTERM_GRACE: Duration = Duration::from_millis(1500);
+
+/// Stop the fsmonitor daemon serving `worktree`, force-killing it if it has
+/// stopped answering its IPC socket.
+///
+/// `git fsmonitor--daemon` is a per-worktree, self-respawning filesystem-watch
+/// cache git starts when `core.fsmonitor=true`. The graceful shutdown,
+/// `git fsmonitor--daemon stop`, is an IPC request *to the daemon itself*: a
+/// wedged daemon (one that has stopped answering its socket — the common
+/// failure, which also hangs `git status` in that worktree) silently ignores
+/// `stop` and then leaks forever once its worktree is gone, since nothing else
+/// references it. Worktree removal is the one moment we can still identify the
+/// daemon by its socket, so this verifies the daemon is actually gone after
+/// `stop` and, on Unix, kills it by PID (SIGTERM, brief wait, SIGKILL) if not.
+///
+/// This is the single canonical fsmonitor-stop path. It runs **synchronously
+/// while the worktree path still exists** (the socket lives under the
+/// per-worktree git dir and is needed to resolve the owning PID), so every
+/// removal path — the library `remove_worktree_with_cleanup`, the foreground
+/// handler, and the background `spawn_background_removal` — calls it in the
+/// foreground before the directory is staged or pruned. The detached
+/// `rm -rf` background process never touches the daemon; keeping daemon
+/// management in the Rust foreground avoids reimplementing socket/PID
+/// resolution and signal escalation as a shell string.
+///
+/// Best-effort and fail-open: every step is bounded by a timeout and every
+/// error is logged at debug level and swallowed. A failure here must never
+/// fail or materially slow `wt remove`. The PID is only ever resolved from the
+/// IPC socket *inside the specific worktree being removed*, so a signal can
+/// only ever reach that worktree's own daemon, never another worktree's.
+pub fn stop_fsmonitor_daemon(worktree: &WorkingTree) {
+ // Graceful path first: a healthy daemon exits cleanly on this IPC request.
+ let _ = Cmd::new("git")
+ .args(["fsmonitor--daemon", "stop"])
+ .current_dir(worktree.path())
+ .context(crate::git::repository::path_to_logging_context(
+ worktree.path(),
+ ))
+ .timeout(FSMONITOR_STOP_TIMEOUT)
+ .run();
+
+ // Resolve the per-worktree git dir via git (handles the `.git` *file* a
+ // linked worktree uses — never hand-construct `<path>/.git`). The daemon
+ // binds its IPC socket at `<git-dir>/fsmonitor--daemon.ipc`.
+ let socket = match worktree.git_dir() {
+ Ok(git_dir) => git_dir.join("fsmonitor--daemon.ipc"),
+ Err(e) => {
+ log::debug!("fsmonitor: could not resolve git dir, skipping force-kill: {e}");
+ return;
+ }
+ };
+
+ force_kill_fsmonitor_via_socket(&socket);
+}
+
+/// Unix: if `socket` still exists, find the daemon owning it via `lsof` and
+/// terminate it (SIGTERM, bounded wait, SIGKILL).
+///
+/// `lsof -t -- <socket>` prints just the owning PID(s), one per line, and
+/// exits 0 when found / 1 when nothing holds the socket. (`--` ends option
+/// parsing so a socket path is never mistaken for a flag.) Matching by socket
+/// path (not process name) guarantees a signal only ever reaches the daemon
+/// for *this* worktree: a different worktree's daemon binds a different socket,
+/// and once the daemon exits nothing holds the socket so `lsof` returns no
+/// PID — a dead daemon's reused PID is therefore never reported here.
+#[cfg(unix)]
+fn force_kill_fsmonitor_via_socket(socket: &Path) {
+ // No socket means `stop` already reaped a healthy daemon (or one never ran).
+ if !socket.exists() {
+ return;
+ }
+
+ let output = match Cmd::new("lsof")
+ .arg("-t")
+ .arg("--")
+ .arg(socket.to_string_lossy().into_owned())
+ .timeout(FSMONITOR_LSOF_TIMEOUT)
+ .run()
+ {
+ Ok(output) => output,
+ Err(e) => {
+ log::debug!("fsmonitor: lsof failed, cannot force-kill: {e}");
+ return;
+ }
+ };
+
+ for pid in String::from_utf8_lossy(&output.stdout)
+ .lines()
+ .filter_map(|line| line.trim().parse::<i32>().ok())
+ {
+ terminate_pid(pid);
+ }
+}
+
+/// SIGTERM a PID, poll briefly for it to exit, then SIGKILL if it's still
+/// alive. `kill(pid, None)` (signal 0) is the liveness probe — `Ok` means the
+/// process still exists, `Err(ESRCH)` means it's gone.
+#[cfg(unix)]
+fn terminate_pid(pid: i32) {
+ use nix::sys::signal::{Signal, kill};
+ use nix::unistd::Pid;
+
+ let pid = Pid::from_raw(pid);
+
+ if let Err(e) = kill(pid, Signal::SIGTERM) {
+ // ESRCH: the daemon already exited (likely the graceful `stop` won the
+ // race). Anything else (e.g. EPERM) we can't act on — log and move on.
+ log::debug!("fsmonitor: SIGTERM to {pid} failed (likely already gone): {e}");
+ return;
+ }
+
+ let deadline = std::time::Instant::now() + FSMONITOR_SIGTERM_GRACE;
+ while std::time::Instant::now() < deadline {
+ if kill(pid, None).is_err() {
+ log::debug!("fsmonitor: daemon {pid} exited after SIGTERM");
+ return;
+ }
+ std::thread::sleep(Duration::from_millis(50));
+ }
+
+ log::debug!("fsmonitor: daemon {pid} still alive after SIGTERM, sending SIGKILL");
+ let _ = kill(pid, Signal::SIGKILL);
+}
+
+/// Non-Unix: the daemon uses a named pipe rather than a Unix-domain socket, so
+/// the `lsof`-by-socket reaping doesn't apply. The graceful IPC `stop` in
+/// [`stop_fsmonitor_daemon`] is the only stop mechanism here.
+#[cfg(not(unix))]
+fn force_kill_fsmonitor_via_socket(_socket: &Path) {}
+
/// How the branch should be handled after worktree removal.
///
/// Replaces a two-boolean flag pair (`keep`/`force`) to make the three valid
@@ -204,11 +355,9 @@ pub fn remove_worktree_with_cleanup(
worktree_path: &Path,
options: RemoveOptions,
) -> 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"]);
+ // Stop the fsmonitor daemon, force-killing a wedged one. Must happen while
+ // the worktree path still exists (the IPC socket lives under its git dir).
+ stop_fsmonitor_daemon(&repo.worktree_at(worktree_path));
// Fast path: rename into .git/wt/trash/ (instant on same filesystem),
// then prune git metadata. Falls back to `git worktree remove` if the
@@ -400,4 +549,198 @@ mod tests {
assert!(name.starts_with("feature-branch-"));
assert!(removing_path.starts_with(&trash_dir));
}
+
+ /// A linked worktree uses a `.git` *file* pointing at
+ /// `<common>/.git/worktrees/<name>`, not a `.git` directory. The fsmonitor
+ /// IPC socket the force-kill path resolves must land under that
+ /// per-worktree git dir, never under a hand-constructed `<path>/.git`.
+ #[test]
+ fn test_fsmonitor_socket_resolves_to_linked_worktree_git_dir() {
+ use crate::git::Repository;
+
+ let tmp = tempfile::tempdir().unwrap();
+ let gitconfig = tmp.path().join("gitconfig");
+ std::fs::write(
+ &gitconfig,
+ "[init]\n\tdefaultBranch = main\n[user]\n\tname = t\n\temail = t@t\n",
+ )
+ .unwrap();
+ let git = |dir: &Path| {
+ Cmd::new("git")
+ .current_dir(dir)
+ .env("GIT_CONFIG_GLOBAL", &gitconfig)
+ .env("GIT_CONFIG_SYSTEM", "/dev/null")
+ };
+
+ let main = tmp.path().join("repo");
+ std::fs::create_dir(&main).unwrap();
+ git(&main).args(["init", "-b", "main"]).run().unwrap();
+ git(&main)
+ .args(["commit", "--allow-empty", "-m", "init"])
+ .run()
+ .unwrap();
+
+ let linked = tmp.path().join("repo.feature");
+ git(&main)
+ .args(["worktree", "add", linked.to_str().unwrap(), "-b", "feature"])
+ .run()
+ .unwrap();
+ // The defining property of a linked worktree: `.git` is a file.
+ assert!(linked.join(".git").is_file());
+
+ let repo = Repository::at(&main).unwrap();
+ let wt = repo.worktree_at(&linked);
+ let git_dir = wt.git_dir().unwrap();
+
+ // git_dir points into the shared common dir's worktrees/ subtree,
+ // not the worktree's own directory.
+ assert!(
+ git_dir.ends_with("worktrees/repo.feature"),
+ "expected per-worktree git dir, got {}",
+ git_dir.display()
+ );
+ let socket = git_dir.join("fsmonitor--daemon.ipc");
+ assert!(
+ !socket.starts_with(&linked),
+ "socket must resolve via the .git file, not <worktree>/.git: {}",
+ socket.display()
+ );
+
+ // No daemon ever ran, so the socket is absent and the whole force-kill
+ // path is a no-op that returns cleanly.
+ assert!(!socket.exists());
+ stop_fsmonitor_daemon(&wt);
+ }
+
+ /// SIGTERM-honoring process: `terminate_pid` sends SIGTERM, the child
+ /// exits, and the poll loop returns before the SIGKILL escalation.
+ #[cfg(unix)]
+ #[test]
+ fn test_terminate_pid_sigterm_honored() {
+ use std::process::Command;
+
+ let mut child = Command::new("sleep").arg("30").spawn().unwrap();
+ let pid = child.id() as i32;
+
+ terminate_pid(pid);
+
+ // `sleep` exits on SIGTERM; it must be reaped and have a
+ // signal-derived (non-success) status.
+ let status = child.wait().unwrap();
+ assert!(!status.success());
+ }
+
+ /// SIGTERM-ignoring process: the child traps and ignores SIGTERM, so
+ /// `terminate_pid` must escalate to SIGKILL after the grace window.
+ #[cfg(unix)]
+ #[test]
+ fn test_terminate_pid_escalates_to_sigkill() {
+ use std::process::Command;
+
+ // `trap '' TERM` makes SIGTERM a no-op; only SIGKILL can stop it. The
+ // child touches `ready` *after* the trap is installed; the test waits
+ // for that file so the first SIGTERM can't race trap installation
+ // (which would let the child die on SIGTERM and report signal 15).
+ let tmp = tempfile::tempdir().unwrap();
+ let ready = tmp.path().join("ready");
+ let mut child = Command::new("sh")
+ .arg("-c")
+ .arg(format!(
+ "trap '' TERM; : > {}; sleep 30",
+ ready.to_str().unwrap()
+ ))
+ .spawn()
+ .unwrap();
+ let pid = child.id() as i32;
+
+ let deadline = std::time::Instant::now() + Duration::from_secs(5);
+ while !ready.exists() {
+ assert!(
+ std::time::Instant::now() < deadline,
+ "child never installed SIGTERM trap"
+ );
+ std::thread::sleep(Duration::from_millis(10));
+ }
+
+ terminate_pid(pid);
+
+ // Must have been SIGKILLed despite ignoring SIGTERM.
+ use std::os::unix::process::ExitStatusExt;
+ let status = child.wait().unwrap();
+ assert_eq!(
+ status.signal(),
+ Some(nix::sys::signal::Signal::SIGKILL as i32)
+ );
+ }
+
+ /// Fail-open contract: when the per-worktree git dir can't be resolved
+ /// (the path is not a git worktree), `stop_fsmonitor_daemon` logs and
+ /// returns without panicking and without attempting a force-kill.
+ #[test]
+ fn test_fsmonitor_stop_unresolvable_git_dir_is_noop() {
+ use crate::git::Repository;
+
+ let tmp = tempfile::tempdir().unwrap();
+ let gitconfig = tmp.path().join("gitconfig");
+ std::fs::write(
+ &gitconfig,
+ "[init]\n\tdefaultBranch = main\n[user]\n\tname = t\n\temail = t@t\n",
+ )
+ .unwrap();
+ let main = tmp.path().join("repo");
+ std::fs::create_dir(&main).unwrap();
+ Cmd::new("git")
+ .current_dir(&main)
+ .env("GIT_CONFIG_GLOBAL", &gitconfig)
+ .env("GIT_CONFIG_SYSTEM", "/dev/null")
+ .args(["init", "-b", "main"])
+ .run()
+ .unwrap();
+ let repo = Repository::at(&main).unwrap();
+
+ // A path that is not a git worktree: `git_dir()` errors.
+ let not_a_worktree = tmp.path().join("nope");
+ std::fs::create_dir(&not_a_worktree).unwrap();
+ let wt = repo.worktree_at(&not_a_worktree);
+ assert!(wt.git_dir().is_err(), "precondition: git dir unresolvable");
+
+ // Hits the git_dir() Err arm: log + early return, no panic.
+ stop_fsmonitor_daemon(&wt);
+ }
+
+ /// A socket file that no process holds: the force-kill path runs `lsof`,
+ /// resolves no owning PID, and is a clean no-op — nothing is signalled and
+ /// the path is left intact. Exercises the real `lsof` lookup without a
+ /// live daemon.
+ #[cfg(unix)]
+ #[test]
+ fn test_fsmonitor_force_kill_unheld_socket_is_noop() {
+ use crate::git::Repository;
+
+ let tmp = tempfile::tempdir().unwrap();
+ let gitconfig = tmp.path().join("gitconfig");
+ std::fs::write(
+ &gitconfig,
+ "[init]\n\tdefaultBranch = main\n[user]\n\tname = t\n\temail = t@t\n",
+ )
+ .unwrap();
+ let main = tmp.path().join("repo");
+ std::fs::create_dir(&main).unwrap();
+ Cmd::new("git")
+ .current_dir(&main)
+ .env("GIT_CONFIG_GLOBAL", &gitconfig)
+ .env("GIT_CONFIG_SYSTEM", "/dev/null")
+ .args(["init", "-b", "main"])
+ .run()
+ .unwrap();
+ let repo = Repository::at(&main).unwrap();
+ let wt = repo.worktree_at(&main);
+ let socket = wt.git_dir().unwrap().join("fsmonitor--daemon.ipc");
+
+ // Plant a regular file where the IPC socket would be. No process holds
+ // it, so `lsof` resolves no PID and nothing is signalled.
+ std::fs::write(&socket, b"").unwrap();
+ stop_fsmonitor_daemon(&wt);
+ assert!(socket.exists(), "no-op path must not delete the socket");
+ }
}
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index 87beaf5b9..dfd3d5bde 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -26,7 +26,7 @@ use worktrunk::git::Repository;
use worktrunk::git::path_dir_name;
use worktrunk::git::{
BranchDeletionMode, BranchDeletionOutcome, BranchDeletionResult, RemoveOptions,
- remove_worktree_with_cleanup, stage_worktree_removal,
+ remove_worktree_with_cleanup, stage_worktree_removal, stop_fsmonitor_daemon,
};
use worktrunk::path::format_path_for_display;
use worktrunk::progress::{Progress, format_stats_paren};
@@ -84,11 +84,10 @@ fn spawn_background_removal(
log_label: &str,
changed_directory: bool,
) -> anyhow::Result<()> {
- // Stop fsmonitor daemon BEFORE rename (must happen while path still exists).
- // Best effort — prevents zombie daemons from accumulating.
- let _ = repo
- .worktree_at(worktree_path)
- .run_command(&["fsmonitor--daemon", "stop"]);
+ // Stop the fsmonitor daemon BEFORE rename (must happen while the path
+ // still exists — the IPC socket lives under its git dir). Force-kills a
+ // wedged daemon so it can't leak once the worktree is gone.
+ stop_fsmonitor_daemon(&repo.worktree_at(worktree_path));
let remove_command = execute_instant_removal_or_fallback(
repo,